Академический Документы
Профессиональный Документы
Культура Документы
CDS Introduction
Core Data Services (CDS) as the name suggests, is a service directly by HANA core. To present
CDS in a very understandable manner, CDS is a view of one or multiple tables and can be
enriched with metadata which makes it even more useful than just a pile of dumb data. Just to
mention some pointers which will help to understand why CDS framework is more useful:
1. CDS artifacts are present and execute on database(HANA or other) layer. This strategy is
called code push down where Application layer logic can be easily moved to Database layer
for execution. This has many performance advantages if used carefully.
2. CDS can be assigned to authorization object and visibility can be easily controlled
3. CDS view can be easily consumed by oData service
4. CDS view can provide semantic information to each field which is particularly helpful
when information is to be displayed on browser
5. CDS can be buffered just like a transparent table
6. CDS can be enabled for Search
7. CDS can be used to define Data Hierarchy and relationships which is particularly helpful
is navigation and drill downs
HANA is in memory database and performance capabilities can be leveraged only when
calculations are done in-memory. If the business logic is fully written on the application layer,
this defeats the purpose of in-memory computation. New HANA artifacts like CDS,
AMDP(ABAP Managed Database Procedure), CTE(Common Table Expressions) etc. fully
complement code push down and are designed for performance optimization.
When CDS is created, Developer needs to enter three artifact names which
together work as a CDS. All three artifacts are created in the custom
namespace and their name must start with Z or Y.
1
The artifacts created during CDS creation are:
1. DDLS(Data Definition Language Source) – We enter DDLS name along with package name
and Description
2. VIEW(A structure which can be seen in SE11) – is mentioned with annotation
@AbapCatalog.sqlViewName. Just press Control and Click on View name and it leads to SE11
structure
3. STOB(Structured Object) – is mentioned with ‘define view’ or ‘extend view’ syntax.
Types of CDS views
CDS view is evolving and new features are added with almost every technical release. Let’s try
to understand most important types of Core Data Services without going into details. Of course,
we are going to do a deep dive and will understand them one by one!
1. CDS view
1. Basic CDS view
2. CDS View with Join
3. CDS View with Association
4. CDS View with Parameters
5. Extended CDS view
6. CDS View on View
2. Table Function
1. Normal Table Function
2. Table Function with Parameters
3. Abstract Entity – Future Planned Feature
1. Normal Abstract Entity – Future Planned Feature
2. Abstract Entity with Parameters – Future Planned Feature
2
CDS View
CDS view is a mechanism for data projection and makes them semantically rich. There are slight
differences between CDS views, Table Function and Abstract Entities where all of three can be
defined using same Data Definition editor.
1. CDS view
1. Basic CDS view
2. CDS View with Join
3. CDS View with Association
4. CDS View with Parameters
5. Extended CDS view
6. CDS View on View
3
1. In Top part of a basic CDS, annotations are mentioned. Annotations make CDS view
semantically rich. Every CDS annotation has a different meaning. If you need to take a look at
available annotations, just type @ in the top part of CDS and press Control + Space.
2. CDS starts with DEFINE/EXTEND syntax and gives CDS a Structured Object name.
3. After name of CDS, SELECT query is initiated and JOINS are defined beforehand
4. Inside curly braces, projection list(fields to be selected) is provided
5. An individual field can be associated with special semantic meaning using annotations
6. Inbuilt functions can be used inside CDS which effectively helps in Code Push Down.
7. ‘Where’ conditions for CDS query can be mentioned just below projection list which filters the
data and reduces selection effort
8. A “Group By” clause can be added if aggregation(sum, count etc.) is used in query
9. A selection can be UNIONed with another select using UNION ALL/DISTINCT clause. All
projections of UNION should be the similar i.e. number of field selection, their type and sequence
must be same!
1. Inner Join: Inner join requires each row in the two joined tables to have matching column
values, and is a commonly used join operation in applications but should not be assumed to be
the best choice in all situations. Inner join creates a new result table by combining column values
of two tables (A and B) based upon the join-predicate. The query compares each row of A with
4
each row of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate
is satisfied by matching non-NULL values, column values for each matched pair of rows of A
and B are combined into a result row. E.g.
2. Left Outer Join: The result of a left outer join (or simply left join) for tables A and B always
contains all rows of the “left” table (A), even if the join-condition does not find any matching
row in the “right” table (B). This means that if the ON clause matches 0 (zero) rows in B (for a
given row in A), the join will still return a row in the result (for that row)—but with NULL in
each column from B. A left outer join returns all the values from an inner join plus all values in
the left table that do not match to the right table, including rows with NULL (empty) values in
the link column. e.g.
5
In this example, all records found in VBAK are considered in the output whereas records in
VBAP which doesn’t have JOIN matching condition will have a NULL value in output as below:
3. Right Outer Join: A right outer join (or right join) closely resembles a left outer join, except
with the treatment of the tables reversed. Every row from the “right” table (B) will appear in the
joined table at least once. If no matching row from the “left” table (A) exists, NULL will appear
in columns from A for those rows that have no match in B.
A right outer join returns all the values from the right table and matched values from the left
table (NULL in the case of no matching join predicate). For example, this allows us to find each
employee and his or her department, but still show departments that have no employees.
Right outer join is just reverse of table sequence of the Left outer join.
6
And the output is same:
4. Cross Join: CROSS JOIN returns the Cartesian product of rows from tables in the join. In
other words, it will produce rows which combine each row from the first table with each row
from the second table
Cross Join should be carefully used because a cartesian product can create a large data set.
7
Association
Association is different than join in that sense that association defines how two entities are
connected to each other. It is sometimes understood as “Conceptual Thinking” also because its
nature of linking entities rather than joining them directly. The join may be the next step once the
association is defined.
Cardinality
In database design, the cardinality or fundamental principle of one data aspect with respect to
another is a critical feature. The relationship of one to the other must be precise and exact
between each other in order to explain how each aspect links together.
In the relational model, tables can be related as any of “one-to-many”, “many-to-many” “one-to-
zero-or-one”, etc.. This is said to be the cardinality of a given table in relation to another.
In terms of SAP:
A [1..1] B means that for every row of A, there is a unique row in B and vice versa
A[0..1] B or just A [1] B means that B may have a record for which there no source information
in A.
A [0..*] B means that B may have many records for which there no source information in A.
Path Expressions
Path expressions identify an object by describing how to navigate to it to objects via steps/route.
For example, the path expression Object.Employee.Address.ZipCode can refer to Zip Code of
particular Employee’s address. Of course, this relationship should be established beforehand
using association/cardinality to use this kind of Path to access particular information.
To understand Association better, let’s take help of some CDS views and an ABAP program to
consume CDS.
8
Case 1:
In Case 1, we create 3 CDS views and a report for concept demonstration. We create first CDS
view to link Business Partner with ADR6 table. In Second CDS we link first CDS and ADRC
table. In Third CDS, we link first and second CDS so that it can be consumed by ABAP, oData
service, and other CDS. In the last step of Case 1, we create an ABAP program and consume
third CDS view.
CDS- ZADR6_STOB:
@AbapCatalog.sqlViewName: ‘Zadr6_view’
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: ‘BP + ADR6’
define view Zadr6_stob
as select from but020 as b20
association [1..1] to adr6 as _adr6 on b20.addrnumber = _adr6.addrnumber
and _adr6.flgdefault = ‘X’
key b20.partner as partner,
// Address #
key b20.addrnumber as addrnumber,
b20.addr_valid_from,
b20.addr_valid_to,
_adr6
where
9
b20.addr_valid_from <= tstmp_current_utctimestamp()
and b20.addr_valid_to >= tstmp_current_utctimestamp()
CDS- ZADRC_STOB:
@AbapCatalog.sqlViewName: ‘Zadrc_view‘
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
define view Zadrc_stob
as select from adrc
association [1..1] to Zadr6_stob
as _adrc on $projection.addrnumber = _adrc.addrnumber
key _adrc.partner as partner,
// Address #
key adrc.addrnumber as addrnumber,
// Name
adrc.name1 as name,
_adrc
CDS- ZGET_FULL_ADDRESS:
@AbapCatalog.sqlViewName: ‘zget_full_addr‘
10
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: ‘Full Address’
define view zget_full_address
as select from Zadrc_stob as _address
_address.partner,
_address.name,
_address.addrnumber,
_address._adrc.addr_valid_from,
_address._adrc.addr_valid_to,
_address._adrc._adr6.smtp_addr
Report: ZCDS_TEST
*&———————————————————————*
*&———————————————————————*
*&
*&———————————————————————*
REPORT zcds_test.
11
SELECT *
FROM zget_full_address
INTO TABLE @DATA(lt_data)
WHERE partner = ‘0010100001’.
IF sy–subrc IS INITIAL.
cl_demo_output=>display( lt_data ).
ENDIF.
Output:
Case 2
In this case, we create a CDS to demonstrate how multiple tables can be linked using association
and then information can be fetched using path expression.
CDS:
CDS is written to join Business Partner, ADR6, and ADRC tables. This is also an example of
CDS view with Parameters. We are going to cover that in next section!
@AbapCatalog.sqlViewName: ‘Ztest_cds_view‘
12
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: ‘ZTEST_CDS’
define view Ztest_CDS_2
with parameters
i_partner :bu_partner
as select from but020 as b20
association to adr6 as a6 on
b20.addrnumber = a6.addrnumber
and a6.flgdefault = ‘X’
association [1..1] to adrc as _address
on $projection.addrnumber = _address.addrnumber
// Business partner
key b20.partner as partner,
// Address #
key b20.addrnumber as addrnumber,
a6[1: left outer].smtp_addr as email, // Email ID
_address
where
b20.partner = :i_partner
and(
b20.addr_valid_from <= tstmp_current_utctimestamp()
and b20.addr_valid_to >= tstmp_current_utctimestamp() )
CDS Output:
13
Program:
Program consumes CDS and since CDS is an exposed association, logic fetches exposed
columns.
*&———————————————————————*
*&
Report ZCDS_TEST
*&———————————————————————*
*&
*&———————————————————————*
REPORT zcds_test.
DATA : i_bp TYPE bu_partner VALUE ‘0123456789’.
SELECT
FROMztest_cds_2( i_partner = @i_bp )
FIELDS
\_address–tel_number AS telephone, ” Telephone
email AS email ” Email
INTO TABLE @DATA(lt_address).
IF sy–subrc IS INITIAL.
cl_demo_output=>display( lt_address ).
ENDIF.
14
Program output:
CDS with Parameter is very similar to normal CDS with the addition of keyword WITH
PARAMETERS followed by the parameter name and its type.
Till ABAP version 7.51, structured or tabular parameters are not allowed.
Let’s take a simple example to understand this:
Here, CDS view ZCDS_PARAM has single parameter PART_NUMBER with type MATNR.
This input parameter is used in WHERE condition with “:” operator. Instead of “:” operator,
“$PARAMETERS” can also be used (line 16).
15
Consuming CDS view is very easy and it can be achieved by passing parameters with SELECT.
A CDS can be consumed by e.g. other CDS or an ABAP program.
SAP provides a limited way(till release 7.51) for CDS view to accept optional parameters.
Optional parameters here mean that parameters are optional in nature during CDS consumption.
This is possible with Environment System fields made available by CDS framework.
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
define view z_cds_default_input
with parameters
16
@Environment.systemField: #CLIENT
p1 : mandt,
p2 : uname @<Environment.systemField: #USER,
p3 : erdat @<Environment.systemField: #SYSTEM_DATE
as select from vbak as a
:p1 as Client,
:p2 as Ordered_By, // a.bname
:p3 as OrderDate, // a.erdat
a.vbeln as OrderNumber
where
a.mandt = :p1 // sy-mandt
and a.bname = :p2 // sy-uname
and a.erdat = :p3 // sy-datum
” Use case 1
SELECT *
FROM z_cds_default_input
INTO TABLE @DATA(lt_data1).
” Use case 2
SELECT *
p2 = @sy–uname )
17
INTO TABLE @DATA(lt_data2).
” Use case 3
SELECT *
FROM z_cds_default_input( p2 = @sy–uname ,
p3 = @sy–datum )
INTO TABLE @DATA(lt_data3).
Conclusion:
Limited System fields can be made optional in a CDS view or Table function. This can be
achieved only with Environment System fields with two syntax possibilities.
Goto Eclipse > Right Click on Project > New > Other > Data Definition > Enter Package,
Name(Starts with Y or Z) and Description > Next > Enter Package if required > Next > Define
View(or Define View with Join/Define View with Association/Define View withParameters) >
Finish > Create a Test Base View
18
If you need to extend a Standard CDS view, you need to skip above step. The standard view is
equivalent to above-created custom CDS view.
Now to create an Extended view: Right Click on Project > New > Other > Data Definition >
Enter Package, Name(Starts with Y or Z) and Description > Next > Enter Package if required >
Next > Extend View > Finish > Create a Test View Extension
CDS view extension is created by extending Base view as in this example. The result of above
extension can be seen by checking Data preview of First Base view where new fields are added.
Note: Fields are added to the base view. Try “Ctrl + Click” the corresponding “sqlViewName” of
the Base view and it leads to the SE11 transaction where extension concept will be crystal clear
that how it works!
19
It is clear that second CDS along with fields are simply appended to first CDS!
Now a brain twister! Is it possible to extend a CDS view more than once? Is
it even possible?
20
In What Scenario, an Extended view should be
used?
When a standard CDS view needs the addition of new fields.
When a standard CDS view needs a change of fields, a good idea can be: adding new changed
fields by extending CDS.
When a Custom CDS needs a change and original CDS can’t be altered for some reasons.
Happy Learning!
There is no other special syntax for View on View. It works just like a normal CDS view and can
be parameter enabled also.
Table Function
A Table function is an integral part of CDS evolution which challenges CDS to do more! It is
essentially a Code push down mechanism just like a CDS entity. We call Table function a CDS
Data Definition Language(DDL) which uses syntax DEFINE TABLE FUNCTION. Some
salient features of table functions can be summarized as below:
21
Table function is defined in Core data service Source code
It can be consumed by ABAP just like a CDS view
CDS table function is implemented with AMDP framework
AMDP method which creates the core logic of Table function is written in SQL script
AMDP lifecycle management is different than CDS. AMDP can be created using Eclipse
ADT just like CDS in AS ABAP(Application Server ABAP) however AMDP creates a
corresponding Database Stored Procedure on its first execution(unlike CDS view). Once a
corresponding Stored procedure is created, AMDP gets a license to do Code Push Down
because of that time onwards, it makes its presence on Database layer. Since AMDP is
invoked from CDS, it is mandatory that CDS must be activated first before CDS can be
referred to AMDP. Transport must also follow this thumb rule that CDS must be transported
before AMDP.
Client handling can be done using annotations and there is a good specific way to it.
Open SQL does a default client handling for CDS view as well as Table function.
Let’s try to understand Table function with a High-level diagram when Table function is
consumed by an ABAP program:
With this diagram, it is clear that Application layer delegates all the workload to Database Layer
which is the essential for Code Push Down. With Code Push Down, we always transfer workload
to Database layer keeping in mind not to overload Database unnecessarily.
22
Steps to create and test CDS Table Function which is always created along with AMDP class
method:
1. Right Click on Project > New > Other > Data Definition
2. Provide Package, CDS name, and Description and Click Next
3. Select Package if Package is not $TMP and Click Next
4. Select “Define Table Function with Parameters” and Click Finish
5. Code the CDS Table function in CDS Editor as
below:
1. Table Functions may start with Header annotations like in this
example, @ClientHandling.type defines whether CDS is Client dependent or not.
2. Table Function is defined using syntax DEFINE TABLE FUNCTION. Here
CDS Table Function name is ZCDS_TABLE_FUNCTION1.
3. Table function in this example is Parameter enabled which is made evident with
syntax WITH PARAMETERS. In this case, annotation @Environment.systemField :
#CLIENT specifies that the Parameter clnt with type syst_mandt is an optional parameter
and if Parameter is not passed, the default value of clnt will be taken from System
environment context. This means that any other entity e.g. ABAP program which
consumes this CDS, may or may not pass this Parameter.
4. The table function returns set of fields and this is specified in section-d. In this
example, there are two return attributes viz. Mandt(Client) and matnr(Material Number).
The first Parameter is mandatory on the first position because we defined this Table
Function Client dependent on top annotation: @ClientHandling.type. The second field is
Material number which selection logic will be written in AMDP(ABAP Managed
Database Procedure) defined in next step.
5. Table Function is implemented by a class method which must be an
AMDP(ABAP Managed Database Procedure). AMDP to be called is defined by syntax
IMPLEMENTED BY METHOD. We define the Class of AMDP method along with the
class.
Note: During activation of Table Function, it is not necessary that AMDP
class/method is already created. Table function must be activated first to activate
AMDP class/method.
23
6. Create a Global class to consume CDS Table function as
below:
1. AMDP class which is called in Table Function is to be defined separately using
Eclipse ADT since AMDP creation is not provisioned in SAP GUI workbench. The name
of the class is ZCDS_TABLE_FUNCTION in this example.
Note: The name of CDS Table Function and Class can’t be same. Also,
there is one to one relationship between Table function and Class.
2. This is mandatory to define marker interface IF_AMDP_MARKER_HDB for an
AMDP. This is the way to tell ABAP compiler that particular class is special. In this case
of AMDP, we can write embedded non-ABAP code(SQL script) in this class!
3. A table function is implemented by a class method. The class method must be
defined with syntax FOR TABLE FUNCTION with mention of Table Function name.
4. AMDP method implementation has particular signature for Table function which
mentions function is for HANA database with BY DATABASE FUNCTION FOR HDB,
script language. Options READ-ONLY for performance optimization and USING
keyword for the mention of to be used Tables/Methods.
5. Section-e declares a local table with two fields in SQL script. This is of course
not ABAP so data type and syntax are different.
Notice the comment initiated by ‘–’. This is possible because this is an
SQL script comment and not an ABAP comment!
6. This section SELECTs two fields MANDT and MATNR from MARA table and
also returns a table from the method.
24
Small tip: Goto Eclipse> Windows > Preferences > General > Appearance
> Color and Fonts > ABAP > Syntax Coloring > Embedded Languages (background
color) > Edit to set a different background color to differentiate SQL script from
normal ABAP
7. Right click on CDS Editor > Open with > Data preview
8. Check the output
There may not always code reviews in place and write a first-hand optimal code is important for
development, and ABAPers, in that case, have more responsibility when they code. The code
should be performing as per HANA’s credentials. There is a clear need of checklist of good
programming practices which define the way an ABAPer chooses SELECTing mechanism.
I am trying to compare new SELECTion mechanisms and comparison can be “raw” in nature.
(Disclaimer)I am also taking help from another blog Spotlight on ABAP for SAP HANA –
Again for the decision-making process in the usage of New SQL and CDS. Please feel free to
comment so that this post can be made more useful further for open ABAP development
community.
25
Use when a query to be used on single table
Good to use when a simple join on two tables/views/CDS(consider small size category) is
required
Use when standard table buffering can be utilized and can potentially increase performance
Try to use subqueries whenever possible rather than multiple new open SQL SELECTs
26
Data Definition Table Function can’t be published to oData services till the time blog was
written however we expect CDS, Table function and oData (V4) together have a long way to go
AMDP should always be used with ABDP BADI framework for two reasons:
There is possibility to provide Fallback logic in case of future migration
In case of exceptions in Production server, BADI can be deactivated and business process
can continue to run with limited features
Open ABAP
AMDP CTE
SQL CDS
Data modeling – + – –
Open SQL
Ad-hoc / single queries + – – SELECT is
subset of CTE
With Table
Domain-specific metadata – + –
Function
Reusability – + + –
Dynamic programming + – – –
With
Modification-free extensibility – + AMDP –
BADI
27
Declarative Access control – + + –
† Caution: Know and analyze what you are doing. It is recommended to do a comparison POC
before you take a usage decision!
Disclaimer: Use this article and its derived conclusion with your own
conscience. The author doesn’t take any responsibility if you get other results
and lead to another conclusion.
For comparison, we take a scenario of joining four tables. We join tables using new Open SQL,
CDS, CTE and AMDP by keeping the same query across different approaches.
You can find the code on GitHub and clone for yourself to test it.
You may also like to check Best Practices in Code Push Down with S4
HANA.
To compare runtime for each, I am executing each for 10 times and taking an average of them.To
compare runtime for each, I am executing each for 10 times and taking the average of them.I am
not giving time for CTE because it has a different use case than a simple join. You can anyway
go ahead and execute by yourself to see CTE performance.
28
All Times in milliseconds!
Open SQL CDS AMDP
—————————————————
Conclusion: Open SQL, CDS, and AMDP are not competitors for each other and they have
different use-cases.
In this particular case of joining 4 tables, CDS is clear winner followed by open SQL and
AMDP.
29