Вы находитесь на странице: 1из 29

sm

Core Data Services (CDS)


Core Data Services(CDS) is one of the most important artifacts in new
ABAP. It effectively helps to Code Push Down and improves performance.
This is a Basic tutorial and just an overview of most important aspects!

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.

Get Technical Flavor of CDS


Before we further move to understand CDS in-depth, first we would like to understand the
artifacts which support CDS view.

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.

This is important to understand that when CDS is consumed from ABAP in a


query, STOB object should be used to make SELECT. The query should not
be made on DDLS or VIEW object.
CDS can be created with Eclipse in an ‘ABAP
Project’. To create a CDS, follow steps:
1. In Project Explorer, Right Click on Project > New > Other > Core Data Services > Data
Definition
2. Provide Package(enter $TMP for local objects), Name(should start with Y or Z) and Description
3. Click Next to select Transport if Package is not $TMP. Either an existing transport to ve selected
or new Transport to be created
4. Click Next and Select one of the Template based on which type of CDS you need to create
5. Click Finish and Editor opens with selected template in EDIT mode
6. Write your CDS in Editor

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

Basic CDS View


Understanding a Basic CDS 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!

Steps to Check, activate and check data:


 Once CDS Editing is complete, a syntax check(Ctrl + F2) can be done. In case of any error,
Problem view in Eclipse can be used to see errors present in CDS view.
 Once errors are fixed, CDS can be activated(Ctrl + F3).
 CDS can be checked for data after activation. For checking data, right click on DDLS object in
Project Explorer view > Open With > Data Preview

Data preview is a feature-rich editor where


following actions can be done:
1. Filters can be set of Fields
2. Number of entries can be checked
3. SQL console can be opened directly from here where query can be fired on CDS or any
table/view of SAP to check data accuracy
4. Columns can be selected which user needs see at a time
5. Data can be exported to local desktop
6. Data can be refreshed if number and sequence of CDS projection is not changed
7. Maximum number of rows can be set which reduces load of database

CDS View with Join


CDS view allows following types of Joins:

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.

CDS View with Association and


Path Expressions
Let’s  make ourselves familiar with some important keywords before we jump in to understand
Association with examples:

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.

All the code for Case 1 can be found on GitHub.

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’

      // Business partner

  key b20.partner                  as partner,

      // Address #

  key b20.addrnumber               as addrnumber,

      b20.addr_valid_from,

      b20.addr_valid_to,

      _adr6

where

  // Address should be valid on the current date!

9
      b20.addr_valid_from <= tstmp_current_utctimestamp()

  and b20.addr_valid_to   >= tstmp_current_utctimestamp()

Above CDS links Business Partner with the ADR6 table.

CDS- ZADRC_STOB:

@AbapCatalog.sqlViewName: ‘Zadrc_view‘

@AbapCatalog.compiler.compareFilter: true

@AccessControl.authorizationCheck: #CHECK

@EndUserText.label: ‘BP + ADR6 + ADRC’

define view Zadrc_stob

  as select from adrc

  association [1..1] to Zadr6_stob

  as _adrc on $projection.addrnumber = _adrc.addrnumber

      // Business partner

  key _adrc.partner                  as partner,

      // Address #

  key adrc.addrnumber                as addrnumber,

      // Name

      adrc.name1                     as name,

      _adrc

CDS links ZADR6_STOB with 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

// See how information is being fetched using Path expression

// Root Path : _address > fields

_address.partner,

_address.name,

_address.addrnumber,

// Path : _address > _adrc > Fields

_address._adrc.addr_valid_from,

_address._adrc.addr_valid_to,

// Path : address > _adrc > _adr6 > email

_address._adrc._adr6.smtp_addr

CDS links ZADRC_STOB with ZADR6_STOB and hence provide full address for a Business


Partner. CDS can be readily consumed in an ABAP program as below:

Report: ZCDS_TEST

*&———————————————————————*

*& 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.

This program passes a business partner to the CDS ZGET_FULL_ADDRESS and in return,


CDS returns full address.

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.

All the code for Case 2 can be found on GitHub.

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

// Exposed association is used to future reusability

// Association is on demand join,

// so if no field of ADRC is selected, join will never execute!

_address

where

    b20.partner = :i_partner

and(

// Address should be valid on current date

      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

” Path expression used to get Telephone #

    \_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.

Notice the way Path expression is used to access Telephone number!

14
Program output:

CDS View with Parameters


CDS views now come with the request Parameterization where scalar parameters can be passed
to a CDS view.

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.

Above, a simple ABAP SELECT is consuming CDS – ZCDS_PARAM by passing parameter


PART_NUMBER!

CDS with Optional Parameters


In the previous Tutorial, we saw how a CDS view can be made input enabled. This opens a new
set of Code Push Down possibilities in AS ABAP.

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.

Let’s directly go to an example and check how to get this done!

CDS Source Code:


@AbapCatalog.sqlViewName: ‘ZTEST_CDS123’

@AbapCatalog.compiler.compareFilter: true

@AccessControl.authorizationCheck: #CHECK

@EndUserText.label: ‘Example optional Input in CDS…’

// …Using Environment System field

// Use ofsuch optional parameter in CDS is limited

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

ABAP Source code to consume CDS:


REPORT zcds_optinal_input.

” Use case 1

SELECT *

FROM z_cds_default_input

INTO TABLE @DATA(lt_data1).

” Use case 2

SELECT *

FROM z_cds_default_input( ” p1 = @sy–mandt – NOT ALLOWED

                          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.

Extended CDS View


How Extended CDS view Works?
Extended CDS view works very similarly to Extension of Transparent Table. The CDS is
extended in Eclipse IDE by writing some code. It’s very simple to understand the basics of CDS
extension. So, Let’s extend a CDS:

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

Something like this:

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?

The answer is YES! Another APPEND takes place on each extension.

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!

CDS View on View


CDS View on View is a concept where a CDS selects from other CDS. It may be a good Idea to
create an Exposed association and then create another view(View on View) to select specifically
the required fields. This is a good programming practice and enhances clarity with CDS
programming!

There is no other special syntax for View on View. It works just like a normal CDS view and can
be parameter enabled also.

Good Practice: In what scenario, we like to use


CDS View on View?
 It is a good idea to create View on View and use WHERE condition, filters, inbuilt functions on
database layer rather than using a where condition in application logic with AS ABAP
 When The second derived CDS is to be directly used by ABAP… it provides clarity to
maintenance IT staff.
 This is more use useful when path expressions and/or exposed association make first CDS
complex to understand. It is advised to create second with direct mention of fields to be consumed.

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.

Table Function with Parameters

Let’s create a Simple Table Function right away…

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

CDS Session Variables


As of ABAP 7.51, CDS framework provides some runtime system variables which can be
readily used to make CDS more optimal and feature-rich. These session variables sometimes also
discard the need of parameterization of CDS view.

 $session.client is runtime SAP client which is equivalent to sy-mandt


 $session.system_date is current system date and works same as sy-datum
 $session.system_language works very similar to sy-langu
 $session.user is essentially same as sy-uname

Best Practices: New Open SQL/CDS/CTE/AMDP


Code Push Down is a very effective mechanism to improve the performance of ABAP code,
however, the usage should be properly analyzed and planned. A developer generally has multiple
options to use when hitting the database. The main options can be:

 New Open SQL


 Core Data Services(CDS)
 ABAP Managed Database Procedure(AMDP)
 Common Table Expressions(CTE)

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.

New Open SQL Best practices


 Use when you need to make a SELECT SINGLE or SELECT UP TO ONE ROW

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

CDS Best practices


 Use when more than two tables(big size category) are to be joined †
 Use when a SQL function is available only in CDS(not in open SQL) and can push down logic to
the database. †
 Use when Domain-specific metadata to be used
 Use when CDS can be reused
 Use when SELECT is to be published to oData
 Use when SELECT is to be Access Controlled
 CDS overrides default buffering, so it should not be used where it suppresses table buffering.
 CDS separately provides buffering feature where a CDS view can be buffered just like a
Transparent table. CDS buffering can be leveraged using top annotation. Utilize it for the right use
case! †

CTE Best practices


 Best to use when series of SELECTs to be written in AS ABAP logic
 Use when multiple interdependent SELECT statements which can’t be joined but to be used one
after another either conditionally or by using previous output, CTE can be good candidate for Code
Push Down
 CTE can potentially work as a LOOP(WITH-ENDWITH) just like SELECT-ENDSELECT,
however, should be used with appropriate use-case
 It is a good practice to merge many SELECTs into one CTE if possible(without complicating
CTE) because it reduces the number of DB hits
 CTE adds cherry in performance when used effectively with sub-queries

AMDP Best practices


 AMDP should be used when a large business logic can be written fully in SQL script which
executes fully on database layer
 Of course, you should have right resources in team with skills to do HANA SQL
Scripting
 AMDP should not be used for normal SELECTs, JOINs or comparatively smaller logic
constructs
 AMDP works with Table Functions and can be used for right use cases where AMDP output can
be enriched with CDS metadata and to leverage best of CDS and AMDP features

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

Use Cases for Code Push Down

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

Rich set of built-in function + + + +

Reusability – + + –

Dynamic programming +  – – –

Direct binding into ABAP + – – +


Language

Data manipulation language + – + –


(DML)

With
Modification-free extensibility – + AMDP –
BADI

27
Declarative Access control – + + –

Seamless mapping to OData – + – –

Access to advanced SAP – + + –


HANA capabilities

Series of SELECTs followed


by conditions(e.g. sy-subrc) – – – +
where joining not possible

† Caution: Know and analyze what you are doing. It is recommended to do a comparison POC
before you take a usage decision!

Performance Comparison:  New Open SQL


vs CDS vs AMDP vs CTE
It is a very common question nowadays, which one to chose when hitting the database? Option
candidates are New Open SQL, CDS(Core Data Services), AMDP(ABAP Managed Database
Procedure) or CTE(Common Table Expression). They all are designed for new enhanced ABAP
and they all are made for delivering performance. Moreover, all of them do code push down!

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

1. 264.16      228.28      197.63


2. 178.75      204.22      223.59
3. 210.28      201.12      219.49
4. 203.02      184.15      223.47
5. 207.51      170.6        221.25
6. 182.65      207.63      207.4
7. 194.28      170.00      209.98
8. 195.05      181.01      238.32
9. 215.18      170.15      232.45
10. 184.97      161.35      208.81

—————————————————

Avg: 203.58    187.85    218.23

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

Вам также может понравиться