Create A Simple ABAP CDS View in ADT
Create A Simple ABAP CDS View in ADT
You will learn how to create a CDS (Core Data Services) view using ABAP Development
Tools (ADT).
You will learn
How to use the new Core Data Services (CDS) tools in ABAP Development Tools for
Eclipse (ADT).
How to use the following ABAP and SQL elements in a CDS view:
o SELECT statement
o CASE statement
o WHERE clause
Prerequisites
You have a valid instance of an on-premise AS ABAP server, version 7.51 or higher
(some ABAP Development Tools may not be available in earlier versions)
You have run the transaction SEPM_DG_OIA_NEW or transaction STC01 -> tasklist
SAP_BASIS_EPM_OIA_CONFIG. (If you do not, your CDS view will display empty.)
Tutorial: Create an ABAP Project in ABAP Development Tools (ADT)
Tutorial: Create an ABAP Package
CDS is an extension of the ABAP Dictionary that allows you to define semantically rich data
models in the database and to use these data models in your ABAP programs. CDS is a
central part of enabling code push-down in ABAP applications.
You can find more information about CDS in the ABAP keyword documentation and the SAP
Community.
Throughout this tutorial, objects name include the suffix XXX . Always replace this with
Name = Z_INVOICE_ITEMS_XXX
2. Enter the CDS view sepm_sddl_so_invoice_item as the data source for your view. You
can get proposals for the data source by entering a few characters, then using code
completion (keyboard shortcut CTRL+SPACE).
The SQL view name is the internal/technical name of the view which will be created in the
database. Z_Invoice_Items is the name of the CDS view which provides enhanced view-
building capabilities in ABAP. You should always use the CDS view name in your ABAP
applications.
STEP 3
follows:
1. Trigger code completion in the SELECT list (by clicking on the SELECT list and using
keyboard shortcut CTRL+SPACE), then double click on the entry Insert all elements -
template. All the elements (fields and associations) of the underlying data source are
inserted into the SELECT list.
2. Remove all the elements in the SELECT list which were inserted by the code completion
To see the related data sources that can be accessed using associations, scroll down.To see
details about the target data source of the association header, choose the
hyperlink sepm_sddl_so_invoice_header .
using the associations in path expressions. Each element in the path expression must be
separated by a period.
1. Add the association header to your selection list, preferably with a comment, by adding
the following the code. do not forget to add a comma after the previous
item, gross_amount :
2. You will get an error, “Field header must be included in the selection list together with
statement.
3. Add the company_name of the business partner to the SELECT list using the
4. Add the payment_status from the invoice header to the SELECT list using the
association header
STEP 6
expression.
Remove the existing declaration, header.payment_status, and replace it with the following
retrieved.
1. Add a WHERE clause:
STEP 9
Test yourself
Which of the following is<br/> not a valid association path? Choose one answer
only.
o sepm_sddl_so_invoice_item.product.changed_by
o sepm_sddl_so_invoice_item.product.dim_unit
o sepm_sddl_so_invoice_item.product.supplier
o sepm_sddl_so_invoice_item.product.storage_bins
ABAP on HANA : CDS Views
This page contains link to all the posts in the series ABAP on HANA –
CDS Views.
1. Introduction to CDS Views
2. Joins in CDS Views
3. CDS View with parameters
4. Extend a CDS View
5. Associations in CDS View
6. Currency/Unit Conversion in CDS Views
7. Expressions & Operations in CDS Views
8. CDS Table Function
9. CDS View Entity
Exploring ABAP on HANA [1] : Introduction To CDS Views
This is first post of the series Exploring ABAP on HANA which will cover ABAP on HANA
objects like CDS, AMD, ALV IDA and so on.
CDS or Core Data Services are part of SAPs Code Pushdown approach where you try to do as
much as possible at database layer than application layer. One example of Code Pushdown
can be calculating aggregates at database layer using aggregate functions in SQL rather than
bringing all data in application layer and calculating the aggregates.
CDS offers capabilities such as relationship definitions like associations, built-in functions like
currency conversion, extensions, semantic capabilities like annotations along with all SQL
enhancements.
CDS was introduced in ABAP 7.40 SP05 and additional features were added subsequently in
SP08, SP10, ABAP 7.50 SP00 and so on.
2. At the top we have an annotation that tells us the name of related SQLView
– DEMO_CDS_PRJCTN
5. The fields selected are carrid, connid, cityfrom and cityto with first 2 being the key
fields
It is simple to read and understand, right? With this example, we can imagine a CDS view
as a query written inside some kind of a reusable container which can be executed to get
the data.
CDS views can only be created from ABAP Development Tools (ADT) in Eclipse. You can not
create CDS views from SAPGUI.
To install Eclipse, check the post Install Eclipse for ABAP Development and if you are
not familiar with Eclipse, visit Working with Eclipse for ABAP development.
1. Right click on your package, New > Other ABAP Repository Object
2. Search for ‘Data Definition’, select the node Data Definition and click Next
7. Enter sqlViewName, edit the data_source_name and add fields. Separate the elements
within { … } with a comma.
10. To test the CDS view right click on your CDS view / Data definition and chose option
Open With > Data Preview.
11. OR, you can simply execute the CDS View with application toolbar button Run As.. and
select ABAP Application.
The steps to create a CDS view are covered in post Exploring ABAP on HANA [1] :
Introduction To CDS Views.
Output Sample
CDS View with LEFT OUTER JOIN
Left Outer Join returns all entries from left table even when there is no matching entry in
right table. The fields from right table will be populated if matching entry is found, else the
fields will be kept blank.
Example
Right Outer Join returns all entries from right table even when there is no matching entry
in left table. The fields from left table will be populated if matching entry is found, else the
fields will be kept blank.
Note that WHERE condition fis applied to the results set created using the join.
The output looks like below. (You might get different output based on entries in your
system)
CDS View with CROSS JOIN
Cross Join returns the Cartesian product of rows from tables in the join i.e., it will produce
rows which combine each row from the left table with each row from the right table.
Example – Imagine a table with single field Color and another table with single field Shape.
If we want to output all possible color and shape combinations – we can use cross join.
\
And the output
Buffering should not be enabled for a CDS view with outer join.
In nested joins, parentheses should be used explicitly to make the code readable.
Exploring ABAP on HANA [3] : CDS View with parameters
In this post, you will learn to create and consume a CDS View with a parameter.
A CDS View with a parameter is created to pass input to CDS View. You can compare this
parameter to a selection screen parameter. Multiple parameters, however there is no option
similar to select-options on selection screen.
1. Create new Data Definition using template ‘Define View with Parameters’
CDS View with parameters
Notes
After the view name, ‘with parameters‘ key words are added
Parameter type can be either predefined ABAP types or a data element. Predefined
ABAP types for CDS are not same as ABAP data dictionary and input help can be used
(Ctrl + Space)
Default value can be assigned with annotation – @Environment.systemField:
#SYSTEM_DATE
Parameters are optional only when default value is assigned. We can only use system
fields such as #SYSTEM_DATE. Possible values are as below.
Parameters can be used in the select field list as it is or for calculation, and using alias
for such fields is mandatory
Output
When a view with parameter is executed, a pop up appears where parameters can be
entered. All parameters will be mandatory unless assigned with default values.
Enter parameters and click OK to get the output.
Pass the parameters after the CDS View name in the FROM clause in closed round brackets
with a comma separated list.
The result matches with the direct execution of CDS view using same parameter. The date
is used different than system date to demonstrate that the parameter can be written to
output as well.
A CDS view extension can be compared to APPEND STRUCTURE in ABAP Dictionary Table as
we add fields to the view with extension.
Consider below CDS view which projects few fields from table SPFLI. As you can see, not all
fields are available in the list.
Now, if we want to add few more fields such as fltime and distance, we can extend the view.
Create new data definition using New > Other Repository Object … > Data Definition
Enter Name and Description.
Give a name for the sqlViewAppendName, view to extend and add required fields. All the
fields should be prefixed with the data source from original CDS view.
Activate. The base view will see the enhanced / extended sign.
Execute the base view and you will get the added fields in the output.
Parameters
Same number of UNION statements are required when base view contains UNION
Restricting Extendibility
#NONE – No extension
#UNION – Extensions of the SELECT list of a CDS view with a UNION clause are
allowed
It is possible to create multiple extensions for a view. If you are working with custom
applications, extension might not be needed, but when you are extending standard
applications, it might be useful. However, extending standard views should be done only
after lot of consideration and it is a good idea to check with SAP before we do so.
Standard view extension looks like below.
Base View
Extension
CDS view extension can be a never ending topic as we can add associations, unions, group
by etc., more on that after we go through the basics of association etc., in next posts.
Exploring ABAP on HANA [5] : Associations in CDS View
In this post, you will learn about Associations in CDS Views.
What is Association?
Associations define relationships between entities such as a database table or another CDS
view. Associations can also be viewed as a Join-On-Demand. This means that the
association will only be executed when the fields from associated entity are referred. Typically,
CDS associations can be compared to LEFT OUTER Joins.
Left
Outer Join
Note: All the code is available at the end in text format if you need to copy it
Explanation
Associated table is given alias starting with _ (underscore). This is not mandatory, just
a naming convention.
The ON condition uses a field from Projection list which comes from the primary table
scarr.
Selection of the key is mandatory – if key is not selected all entries from associated
table are returned when association is called.
Output of the such a CDS view shows the data from LEFT table only. Data from associated
table is shown only on demand.
Select a key, click on the triangle after the view name to see List of Associations and
chose the one to display association data.
Notice the data returned from associated table is based on key carrid = 'AA'.
Template
Cardinality
Cardinality denotes 1 entry from primary tables has a to b entries in associated table using
format [a..b].
to exactly-one : [ 1..1 ]
to many : [ ] or [ * ] or [ n..* ]
[ 0..1 ]
to zero-or- One record in primary table has zero or one
[1]
one record in associated table
don’t mention cardinality
Cardinality How to write Meaning
When you are accessing the association fields, use \ followed by association name and
use an alias
Use the FIELDS clause to write fields after the FROM clause – which is easier to write
as you have already selected an alias
Why to use associations when join can give the same data?
Think of an application that needs to show the Carriers first and when user clicks on the
carrier then show the associated flights. Here, user may end up checking 4-5 carriers
sometimes just 1. With joins all the data will be selected at one go. With associations only
when user needs the data, it will be fetched.
Multiple associations
The real of associations can be seen while working with UI5 applications and OData
Services, which will be a series that I will start after the ABAP on HANA series.
Exploring ABAP on HANA [6] : Currency/Unit Conversion in CDS Views
In ABAP, we use one of below or similar FM to convert amounts from one currency to
another.
1. CONVERT_AMOUNT_TO_CURRENCY
2. CONVERT_TO_LOCAL_CURRENCY
We need to do this in a loop when we need to do this for multiple records. With CDS, we
can do this while we fetch the data. Interesting, right?
Currency Conversion
Consider below table data. I have created a custom table for this demonstration. As you can
see, GROSSCOL is a column that has gross collection for the movies in the table and all
records have currency USD.
Let us convert it to a another currency, say EUR using a CDS view. The target currency can
be passed using a parameter, to make this more dynamic.
Execute the CDS view, provide the target currency as ‘EUR’ and the conversion is done.
The conversion errors can also be handled with possible error handling values as below.
Unit Conversion
Unit conversion has a similar syntax but it has less parameters than Currency conversion.
Here is a standard demo view that explains Unit Conversion.
Exploring ABAP on HANA [7] : Expressions & Operations in CDS Views
In this post, you will learn about various expressions and operations in CDS view.
So far, we have looked at creating a simple CDS view, CDS view with associations, parameters
etc. Read earlier posts in this series at Exploring ABAP on HANA.
This post will focus bit more on syntax part rather than concepts as concepts here are either
self explanatory or have been covered in earlier posts.
Projection List
Field can be a key field or a non-key field. Alias can be used. If alias is not used then the
field name itself becomes the final column name.
Literals
These are constants of numeric or characters type and simply put the constant value for all
rows in the output. Eg. ‘12345’, ‘CDS’. It is mandatory to specify alias name for literals in
the field list.
Session Variables
Variable Usage
Complex / Searched case -This has multiple conditions in each case and it can have
conditions other than ‘equal to’ ( = ).
Suppose, we want to produce Phase as First, Second, Third, Fourth instead of Phase 1,
Phase 2 and so on, we can use Simple Case statement.
Similarly, if we want to call a movie Hit, Flop etc based on the opening collection, we can
use Complex Case statement.
Projection List
Fields from projection list can be accessed using $projection. You can use this
in Associations.
Parameters
In a CDS view with a parameter, a parameter can be addressed with a colon ( : ) or
with $parameters.
Conditions
Regular Comparisons
Pattern comparisons
This is similar to contains string or the like operation that we perform in Open SQL.
Arithmetic Operations
Aggregates Functions
Aggregate functions evaluate multiple records from the source and return aggregations such
as total, count.
MAX, MIN, AVG, SUM, COUNT are the aggregate functions available. These are pretty self
explanatory, so I am going to mention only one example.
Group By clause is mandatory when using aggregate functions. Having clause can be
added to filter data based on aggregation.
As phase 4 collection does not match the condition, it is not shown.
Type Casting
abap.clnt[(3)] Client
abap.fltp[(16,16)] Float
abap.int1[(3)] INT1
abap.int2[(5)] INT2
abap.int4[(10)] INT4
abap.int8[(19)] INT8
abap.lang[(1)] Language
abap.raw(len) RAW
abap.sstring(len) SSTRING
abap.tims[(6)] Time
Numeric Functions
FUNCTION OUTPUT
CEIL(arg) Round Up
String Functions
Operations like concatenation, Substring, replace, length, left substring, right substring
removing right or left blanks or zeros etc. are possible.
concat( char1, char2 ) as concat,
length( char1 ) as length,
left( char1, 3 ) as left,
lower( char2 ) as lower,
upper( char2 ) as upper,
right( char1, 3 ) as right,
substring( char1, 3, 3 ) as substring,
replace( char1, ',' , '.' ) as replace,
concat_with_space( char1, char2, 1 ) as concat_with_space
Decimal Shift
This can be used to get the amount as per the currencies, specially the ones which have
other than 2 decimal places.
decimal_shift( amount => amount, currency => currency ) as Amount
Date Functions
Functions like add days, add months, days between dates, and date validation can be used
in the CDS.
dats_add_days (releasedon, 14, 'INITIAL') as DateAfter2Weeks,
dats_add_months (releasedon, 3, 'NULL' ) as Dateafter3Months,
dats_days_between (releasedon, :iv_curr_date ) as DaysSinceTheRelease,
dats_is_valid (releasedon) as IsValidDate
Nesting Functions
It is also possible to use functions within functions like below which converts time from
minutes to format HH:MM.
concat( concat(lpad ( ltrim ( cast( div(fltime, 60) as abap.char( 12 ) ), '0' ), 2, '0' ), ':' ) ,
lpad ( ltrim ( cast( mod(fltime, 60) as abap.char( 12 ) ), '0'), 2, '0' ) ) as Flight_Time
repeats this process for minutes, just this time uses mod to get remaining minutes
then concatenates HH and : into say HH: and then concatenates it with MM to get
HH:MM
The point here is not to understand all this right away, but to know that such complex
expressions are possible.
I have not given examples of actual CDS code and outputs here as so far, I am sure you are
comfortable with CDS views and can try these out yourselves.
However, if you need such examples, do let me know in the comment section and I will post
dedicate article on required section.
– Jagdish
Exploring ABAP on HANA [11] : CDS Table Function
ABAP CDS table functions define table functions that are implemented natively on the
database and can be called in CDS. This is as per the SAP documentation.
In simple words,
2. It is defined similar to CDS except for data source i.e. you create a field list similar to
CDS View
If this is still confusing – let us go through the creation process and then revisit these 3
statements.
1. In Eclipse ABAP perspective, right click on your package and chose New > Other
Repository Object
2. Select Data Definition under Core Data Services and click Next.
8. Save it. Do not try to activate it at this point as the method and class does not exist.
2. Define a static method get_flights with addition FOR TABLE FUNCTION with table
function name. Add implementation for the method as below.
ENDMETHOD.
ENDCLASS.
3.Click on Activate inactive objects. This allows you to active multiple objects at a time.
4. Select the class and table function objects and click Activate.
Method Explanation
Definition
The method gets Importing and Returning parameters automatically from CDS table
function where CDS parameters become the Importing Parameters and it has only one
table as returning parameter with fields defined in the CDS.
FOR TABLE FUNCTION key word followed by CDS Table Function name is used to define
the method.
Implementation
The parameters defined in CDS Table Function can be directly access here
using :parameter_name
RETURN statement is mandatory here. It can be used to pass result of query directly or
any table used in the script.
The CDS Table Function can be used to take benefits of CDS with flexibility of SQLSCRIPT.
CDS view entities will replace the CDS views. CDS views were first released in ABAP 7.40,
SP05. These are declared using DEFINE VIEW and they create a DDIC / ABAP Dictionary
view. The annotation @AbapCatalog.sqlViewName is used to specify the DDIC view
name.
@AbapCatalog.sqlViewName: 'DEMO_CDS_PRJCTN'
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view demo_cds_spfli
as select from
spfli
{
key spfli.carrid,
key spfli.connid,
spfli.cityfrom,
spfli.cityto
}
The SQL view is created/adjusted in the background during activation which impacts the
activation performance. We also need to specify additional annotations for key preservation,
client handling etc, but for me the real problem is that the CDS view name and SQL view
name must have a different name – managing this becomes difficult at times.
Hence CDS View Entities. Here is one example.
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity DEMO_CDS_VIEW_ENTITY_KEY
as select from spfli
{
key cityfrom,
key cityto,
carrid,
connid
}
Important points to note are
The CDS view entity can be used in ABAP programs using ABAP SQL
The data source can be database table, CDS view, CDS view entity, CDS table function.
Simpler to extend
New functionalities like regex replace, new operators like EXCEPT & INTERSECT are
available from 7.56
Restrictions
DISTINCT and UNION clause were not allowed in version 7.55 but it allowed from
version 7.56
As of now, both CDS View and CDS View entities will co-exist. However, if your ABAP
version support entities – create entities as eventually we will need to replace the views
with entities using the tools provided.
Most of the syntax remains the same so if you already understand CDS Views – you do not
need to worry much, but if you do want to learn CDS Views head over to ABAP on HANA :
CDS Views.