CDS, Amdp & Abap 7.4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 263

Table of Contents

Attribute View ............................................................................................................................................... 3


1. Inner Join Example ........................................................................................................................ 4
1. Text Join Example........................................................................................................................ 13
2. Generate Time Data in Schema "_SYS_BI".................................................................................. 27
3. Time Based Attribute View ......................................................................................................... 35
a) Create Time Attribute Using Auto Create Option ....................................................................... 35
b) Create Time Attribute without Auto Create Option ................................................................... 39
4. Derived Attribute View ............................................................................................................... 41
5. Calling Attribute View using SQLScript in Procedure .................................................................. 43
6. Calling Attribute View using CE Operation in Procedure ............................................................ 48
7. Implement Attribute View via Native SQL in ABAP .................................................................... 51
8. Implement Attribute View via Open SQL using External View ................................................... 54
Analytic Views ............................................................................................................................................. 62
1. Analytic View with Central Entity Scenario ................................................................................. 64
2. Currency Conversion from USD to INR in Analytic View ............................................................. 79
a) Saving the Currency Conversion Value in Original Column (NETWR) ......................................... 79
b) Creating New Column for Currency Conversion and keeping the Original Column ................... 89
3. Calling Analytic View using SQLScript in Procedure.................................................................... 98
4. CE Operator with Scalar Variables in Procedure....................................................................... 102
5. CE Operator with Unit Conversion Example in Procedure ....................................................... 105
6. CE Operator with Input Parameters in Procedure .................................................................... 108
7. Calling Procedure in Native SQL with Scalar Input ................................................................... 111
8. Calling Procedure in Native SQL with Tabular Input ................................................................. 114
9. Database Procedure Proxy in ABAP .......................................................................................... 119
Calculation View........................................................................................................................................ 123
1. CA Graphical View => Cube ....................................................................................................... 126
a) Implementation via Procedure ................................................................................................. 138
b) Implementation via External View ............................................................................................ 140
2. CA Graphical View => Dimension .............................................................................................. 146
a) Implementation via Procedure and Single Value Inputs for Sales Order and Client ................ 152
b) Implementation via Procedure and Dynamic Where Clause .................................................... 155
3. CA Graphical View => Star Join ................................................................................................. 163
4. CA Graphical View => Union ..................................................................................................... 176
5. CA Graphical View => Variable Mapping .................................................................................. 183
6. CA Graphical View => SQLScript................................................................................................ 188
ABAP Managed Database Procedure (AMDP) .......................................................................................... 192
1. AMDP Process Overview: .......................................................................................................... 192
a. Step 1 => Declare your AMDP Class .......................................................................................... 192
b. Step 2 => Declare your AMDP Methods ................................................................................... 194
c. Step 3 => Implement your AMDP Methods .............................................................................. 195
d. Step 4 => Consume AMDP Methods in ABAP ........................................................................... 196
2. Calling an AMDP Procedure from SQLScript ............................................................................. 199
3. Calling an SQLScript Procedure from AMDP ............................................................................. 203
4. AMDP, SQL Script with Tabular CHANGING Parameter ............................................................ 203
Core Data Service (CDS) ............................................................................................................................ 204
ABAP CDS in ABAP Dictionary ........................................................................................................... 205
1. CDS Views.................................................................................................................................. 215
a. Example 1: Simple Select Statement ........................................................................................ 216
b. Example 2: Name List ................................................................................................................ 216
c. Example 3: Parameter List ........................................................................................................ 216
2. CDS View Enhancements .......................................................................................................... 217
3. CDS Roles .................................................................................................................................. 218
4. CDS Access Policies ................................................................................................................... 218
ABAP 7.40 and above release ................................................................................................................... 218
1. Escape Character for Host Variables ......................................................................................... 218
2. String Templates ....................................................................................................................... 219
3. Chaining Operator ..................................................................................................................... 220
4. Inline Declaration ...................................................................................................................... 220
5. Table Expression ....................................................................................................................... 221
6. Conversion Operator................................................................................................................. 228
7. Value Operator.......................................................................................................................... 229
8. New Operator ........................................................................................................................... 230
9. For Operator ............................................................................................................................. 231
10. Filter in ABAP 7.50 .................................................................................................................... 233
11. Casting Operator ...................................................................................................................... 236
12. Condition Operators ................................................................................................................. 238
13. Is Instance of ............................................................................................................................ 239
14. Move-Corresponding ............................................................................................................... 240
15. CL_ABAP_CORRESPONDING - SYSTEM CLASS in ABAP 7.50 .................................................... 243
16. Corresponding .......................................................................................................................... 245
17. REF Operator ............................................................................................................................ 245
18. LET expression .......................................................................................................................... 246
19. Lossless Operator EXACT .......................................................................................................... 247
20. MESHES .................................................................................................................................... 249
21. Open SQL in Release 7.40 ......................................................................................................... 257

Attribute View
 It is used to create data view based on Join condition.
 Mostly used for Master Data such as Customer, Vendor, Material and so on.
 Allowed Joins are mentioned below

 There are 3 sub types in Attribute View namely,


a. Standard :
Normally used when defining Attribute View.
b. Time:
Used when you want tables related to "Time"(which is present in "_SYS_BI" Schema).It
is important that you import tables T009 and T009B before using them.

c. Derived:
Used for reading existing attribute view (Read-Only Attribute View). You can only
change the description of the attribute when using this type.

Data Flow in Attribute View

 Attribute view has two sections namely


a. Semantics:
It is used for creating key attributes, labels for attributes, hiding the attributes, default
client, create hierarchies.

b. Data Foundation:
It is used for adding tables, creating table joins, creating output columns and calculated
columns, Add filter to attributes.

Points to Remember:
 Valid scenario for Referential Join is
i. It is 100% guaranteed that for each row in one table, there is at least one join partner in
the other table
ii. That holds true in both directions
iii. At all times.
 Referential Join is a feature available only in OLAP engine. When testing Attribute View outside
the context of an Analytical view then the join engine will perform an inner join.
 Referential Join cannot be used if a filter is set on a field in the right table.
 Text Join is available only for SAP ERP tables with SPRAS field.

1. Inner Join Example


 Create Attribute View using the path : Content => Your Package => Right click on the Package
and select New as shown below,
 Enter the Attribute Name, description and select the right Subtype,
 Next step is to add required tables to Data Foundation using the path Catalog=>ABAP Schema
(SAPEH2 in our case)=> Tables as shown below,

 Use filter on table so that only required table is loaded,


 Select the required table and drag and drop it on data foundation,
 Next step is to create Join Conditions between data foundation tables as shown below,
Always validate the
join if available

 Next step is to select fields which will form the part of output list as shown below,
 To add new calculated field, select Data Foundation and then click on "+" sign in the output
section as shown below,

 Enter the required details for newly created column along with its formula as shown below,
Always validate your
formula before
saving or activating.

 The newly created column appears in output section as shown below,

 Next step is mandatory for Attribute View i.e. selection of Key Fields.
Click on Semantics and then from Columns tab, select the key fields as shown below,

 Save the changes.


 Activate the changes.

 To preview output of your attribute view, click on below icon and select any one of the options
as shown below,

1. Text Join Example


In content folder, right click on the package where you intend to create the view and select the required
view as shown below,
Enter the desired name for the view and select proper view type, subtype and click on Finish button.
Click on Data Foundation and then go to Catalog folder (where all the tables exists either from SAP or
created in HANA Studio itself).

Choose the Schema "SAP" followed by your ABAP system ID from which table is coming. In our example,
it is SAPEH2. In the required schema, find the structure by the name "Tables" as shown below,
Select "Tables" from tree structure and right click on it and select Filters so that we can narrow down
our search to required tables. In our case, we want to search MARA table as shown below,
Drag MARA table and drop it on Data Foundation.
Follow same process of filtering for MAKT table and drag and down it on Data Foundation as shown
below,
Now that required tables are selected in Data Foundation, next step is to create Joins between them.
Select any field and right click on it and choose "Create Join" as shown below,
Now apply the required join conditions to as many fields as you want as shown below,
You can add the required column to output either from Details of Data Foundation or Details from
Semantics as shown below,
Now we want to restrict the "Material Description" only to "English Language" so we need filter at
MAKT-SPRAS = "EN" which is achieved as shown below,
Now select the key field (as it is mandatory for Attribute View) from details section in Semantics as
shown below,
To create New Calculated Column, go back to Data Foundation and in Output Section, click on "+"
Button as shown below,

Now enter the name, data type and required formula for new calculated field as shown below,

In our case, we want the new calculated column to show Material Number followed by Material Type
followed by Material description as shown below,
New calculated column is shown with "Calculator indicator" as shown below,
Now go back to Semantics section and click on "View Properties" to define
 Default Client.
 Privileges.

Now you can either "Save and Validate" or "Save and Activate" our Attribute View as shown,

Once Attribute is activated without errors, we can check the results of our view in 2 ways namely,
 Data Preview Editor.
 Open SQL Editor.

Below is example of SQL Editor,


2. Generate Time Data in Schema "_SYS_BI"
 Now consider a scenario where you want to display the year and month on which material was
created in the output of Attribute View.
 In ABAP, we would select the data from MARA table then using field MARA-ERSDA, we would
find the year and month via YYYYMMDD format.
We can use Time Table from "_SYS_BI" schema exactly for this purpose. No need for any calculation.
First, we need to get "Quick View" available in Modeler Perspective. Go to Help Menu and click on
"Quick View" as shown below,
Now select "Generate Time Data" from Quick View as shown below,
Now select the system where you want to perform the time table operation as shown below,
Now select the Calendar Type as per your requirement (Gregorian or Fiscal) as shown below,
In our case, we are using option of "Gregorian" Calendar Type as shown below,
Now go to Schema "_SYS_BI" where tables are stored for Time Dimensions.
Select any Time table and right click on it and see the data preview of the table as shown below,
Now you can use Time Generated Tables as normal table, drag and drop it on Data Foundation and join
them according to you requirement.

Time Generated Tables Based on Calendar Type are shown below,


3. Time Based Attribute View
 There are 2 options for Time based Attribute View which are mentioned below,

a) Create Time Attribute Using Auto Create Option


 This option will automatically add the required tables in Data Foundation and create key fields in
Semantics based on Calendar Type and Granularity.
It will
add
tables
and
create
key
fields.
 Below Hierarchies are created by default.
Data preview of output:
b) Create Time Attribute without Auto Create Option
 Here, we need to add the required tables in Data Foundation and then create Key field as per
normal definition of Attribute View.

 Drag and drop Time tables from Schema "_SYS_BI" as shown below,
 Select the field which needs to be shown in output.

 Create Key fields for Attribute View as shown below,


Data Preview of Output:

4. Derived Attribute View


 In this view, you can only change the label of existing Attribute View as shown below,

You can only change this Label in Derived


Attribute View. Rest of the thing are
copied from Existing Attribute View
 In our example, we are using existing Attribute View "AT_INNER_JOIN_KNA1_ADDRESS" as
shown below,

 We normally receive below warning message when creating Derived Attribute View.

 Semantic section of existing view is copied to Derived Attribute View as shown below,
Data Preview of Output:

5. Calling Attribute View using SQLScript in Procedure


 Implementing example AT_INNER_JOIN_KNA1_ADDRESS (created in Attribute View step 1 Inner
Join Example) in Procedure via SQLScript.
 Follow below path for creating Procedure,
Content => Package where Procedure is to be created => Right click on it and select New =>
Procedure
 Below popup will appear where required details of Procedure need to be filled.
Default Schema is very important field when defining the Procedure. It determines the source of
system for data fetching.
Default Schema can be mapped in Quality /
Production system via Schema Mapping so don’t
hardcode it in SQLScript when fetching data from
SAP tables.

So don't use "SAPEH2"."VBAP" in SQLScript, instead


use "VBAP" and Default Schema / Schema Mapping
will take care of Prefix.

 By default two sections are created namely,


a. Script View:
This is the place where SQLScript code is written such as selection query.

b. Output Pane:
This is the place where you define Input structure (Variables or Input Parameters) and
output structure.
 To create output structure, right click on "Output Parameters and define the fields which needs
to be output as shown below,
 Once Output table is defined, we can use it in Script View for passing the final value as shown
below,

Testing of Procedure via SQL Console:

 To test the Procedure, Click on Procedure name in Content and select the SQL Console as shown
below,
 Empty SQL console will appear as shown below,

 Use the syntax of call procedure for testing the procedure.


 Output Parameter should be NULL if initially it does not have any value. It is important to pass
"NULL" since during the call of procedure it will be empty and get filled after execution of
procedure.

 Click on execute button to get the output of procedure as shown below,

Output of Procedure:

6. Calling Attribute View using CE Operation in Procedure


 Implementing example AT_INNER_JOIN_KNA1_ADDRESS (created in Attribute View step 1 Inner
Join Example) in Procedure via CE Operation.
 Follow same steps as mentioned in Attribute View step 6 (Calling Attribute View using SQLScript
in Procedure) for creating Procedure. Only change is using CE Operation instead of SQLScript.
 Create a new Procedure and create its Output Structure as shown below,

Default Schema can be mapped in Quality /


Production system via Schema Mapping so don’t
hardcode it in SQLScript when fetching data from
SAP tables.

So don't use "SAPEH2"."VBAP" in SQLScript, instead


use "VBAP" and Default Schema / Schema Mapping
will take care of Prefix.
Use CE_JOIN_VIEW for directly
fetching data from Attribute
View.

Testing of Procedure via SQL Console:


 To test the Procedure, Click on Procedure name in Content and select the SQL Console as shown
below,

 Empty SQL console will appear as shown below,

 Use the syntax of call procedure for testing the procedure.


 Output Parameter should be NULL if initially it does not have any value. It is important to pass
"NULL" since during the call of procedure it will be empty and get filled after execution of
procedure.

 Click on execute button to get the output of procedure as shown below,

7. Implement Attribute View via Native SQL in ABAP


 We are calling Attribute View AT_INNER_JOIN_KNA1_ADDRESS (created in Attribute View step 1
Inner Join Example) in ABAP via Native SQL.
SQLScript
Statement for
fetching data

Get Database
Connection for SQL

Create the SQL


Statement

Execute your SQL


Statement in HANA

Mapping of Internal
Table and Procedure
Output Table
Filling the Internal Table
with Procedure Output
Data

Output of Report:

8. Implement Attribute View via Open SQL using External View


 We are converting Attribute View AT_INNER_JOIN_KNA1_ADDRESS (created in Attribute View
step 1 Inner Join Example) to External View in ABAP Development and then using it in Open SQL
statement.
 Go to ABAP Development Perspective in HANA by selecting on below "ABAP" icon,
 Click on package where you want to store the new external view in ABAP. In our case, it is saved
in $TMP Package as shown below,

 Select Radio button of "External View" as shown below,


Choose the This is the name of
External Custom View created
View and in SAP and hence it
mention the should begin with "Z"
HANA view
you want to
convert.

 You can use the shortcut for getting the Full name of HANA view as shown below,
 If you are using Transport Number then mention it in below step,
 Use Synchronize Button, if you want to sync views from HANA Studio to ABAP.
View is still not active in SAP. It
needs to be activated in SAP
HANA ABAP Perspective so that it
becomes Active in SAP.

 Click on below Activation Button to active the view in ABAP,


 Now, we can use External View "ZAT_KNA1_EXT_VW" in our ABAP code using Open SQL as
shown below,
Data is selected
from External View
via Open SQL
Analytic Views
 Analytic views are special views in SAP HANA that are used to calculate and analyze key figures
(Measure).
 It is based on concept of OLAP (Online Analytical Processing).
 It can be regarded as a "CUBE".
 In other words, FACT table (Data Foundation) joined against modeled Dimension (Attribute
Views).
 Analytic views can contain two types of columns namely
i. Attributes (or Column):
Attributes or Columns can be Private, Navigation or Calculated as mentioned below,

 Private Attribute:
These are columns selected from Data Foundation (FACT table) and appear in
final output.

 Navigation Attributes:
These are columns selected from Attribute Views in Star or Logical Join Node
and appear in final output.

 Calculated Column:
It is the new column that is created with extra conditions from existing columns
but it is not considered as MEASURES.

ii. Measures:
Measures are simple, calculated or restricted as mentioned below,
 Simple:
These are columns that can be quantified using existing columns. No need for
creating new columns.

 Calculated:
These are new columns that are created using "Column Type" as "MEASURE".
COUNTER is special case of CALCULATED MEASURE. Counters are used to obtain
the count of distinct values for given set of attributes.

 Restricted:
It helps you restrict MEASURE values based on Attribute Restriction.
In other words, Add filter or expression on Attribute (or column) and assign it to
MEASURE.
It follows same aggregation as related MEASURE column.

 Analytic views do not store data. Instead,


a. Data is read from the joined database tables.
b. Joins and calculated measures are evaluated at run time.
c. Master data are stored in system tables.

Data Flow

a. Data Foundation:
 It is used to create a fact table by adding and joining the tables.
 In other words, you can add columns, create column filters and create JOINS if more than one
table.
 If there are more than one table in the data foundation node, specify the central table (FACT
table) from which the modeler must derive the measures.
 MEASURES can be identified from one table alone.

b. Star Join or Logical Join View:


 It is used to join attribute views to fact tables in logical join node. Self-joins are not supported.

c. Semantic View:
 It is used to classify the columns and calculated columns as attribute and measures.
 You can also create variables/input parameters and assign variables to the columns in the
semantics node.
i. Input Parameters:
 It helps you parameterize views and execute them based on the values you
provide at query runtime.
 It is used in PLACEHOLDER clause of the SQL statement.
 Example:
SELECT "PRODUCT",
"REGION",
SUM ("SALES_AMOUNT") AS "SALES_AMOUNT"
FROM "SYS_BIC"."Package Name/View Name"
('PLACEHOLDER' = ($$DISCOUNT$$,'15')
Group by "PRODUCT","REGION";

ii. Variables:
 Variables are bound to a specific attributes.
 They are used to filter the results.
 Variables are interpreted as the "WHERE" Clause of the SQL statement.
 Example:
SELECT "PRODUCT",
"REGION",
SUM ("SALES_AMOUNT") AS "SALES_AMOUNT" Variable used is
FROM "SYS_BIC"."Package Name/View Name" LV_REGION.
WHERE ("REGION" = :LV_REGION)
Group by "PRODUCT","REGION";

1. Analytic View with Central Entity Scenario

Business Scenario:
 User wants to get sales per material for a given range of sales order.
 Get material and quantity from VBAP tables and sum it up as per material no and display the
output.

 In content folder, right click on the package where you intend to create the view and select the
required view as shown below,
 Enter the view name and label.

 Click on Data Foundation and go through the path of Catalog => Schema => Tables as shown
below,
 Filter on VBAP table, drag and drop it to Data Foundation. Follow same process for VBAK as well.
 In case, you add more than one table in Data Foundation, it is necessary to decide which table
will be the Central Entity.
Hint: Always use the Central Entity as the table which will have the MEASURES.
 In our case, "NETWR" is the measure and it belongs to table VBAP so Central Entity should be
VBAP.

 Once "Central Entity" is done, create Join between the Data Foundation tables and select the
required fields which should be part of final FACT table as shown below,
Creating Joins
between Tables
Below is screenshot of selected fields of FACT table,
If possible, always
validate your Join
Conditions.

 Now that FACT table is ready, go ahead and add the required Attribute View to "Logical Join"(or
Star Join) by selecting it from below path,
 As shown below, we now have Data Foundation and Attribute View in Details section of "Star
Join".
 Star Join consist of
 Fields from Attribute Views.
 Selected Columns from Data Foundation.
 Calculated Columns.
 Restricted Columns.
 Input Parameters.
 Below mentioned output section of Star Join plays an important role in Analytic View,

 Create Join condition between Data Foundation's selected fields and Attribute view fields as
shown below,
 Always validate your join by clicking on "Validate Join" button as shown below,
 It's mandatory that Analytic View must have at least one MEASURE field so click on Semantics
section and define the columns as either Attribute or Measure.
 In our example, NETWR will be Measure and remaining display fields will be Attribute as shown
below,
 Since it is possible to declare variables which are used in WHERE clause when fetching data from
Analytic view, please declare a suitable variable for VBELN (Sales Order) as shown below,
 Click on "Create Variable" and mention the details in below popup screen.
Value Help from View and its
Attribute Column

Where Clause Column Name


which can be used in SELECT
Statement

 Now Save and Activate the View and execute in HANA Studio as shown below,
 Enter the required data and execute as shown below,

Output:

Comma
Separator
2. Currency Conversion from USD to INR in Analytic View
 There are 2 ways for Currency Conversion which are mentioned below,

a) Saving the Currency Conversion Value in Original Column (NETWR)


 We will use the existing example of Sales per Material and convert the measure (NETWR) from
USD to INR.
 Click on Star Join and then click on MEASURE field from Output Section. In our example,
MEASURE field is NETWR and below is expected results,
 Semantic Type highlighted above determines whether conversion is possible or not.

 Click on the RED button as highlighted above, you will receive a pop-up for selecting different
Semantic Types. In our case, Currency Conversion is related to "Amount with Currency Code" so
select this option.
 Now, select Decimal Shift and Conversion checkboxes. Fill the required fields for conversion.
Here, you have an option either to hardcode values for conversion (which will never be case in
live system) or create "Input Parameter" for each field which will be know during execution as
shown below,
 Definition of Input Parameters such as GV_CLIENT,GV_UNIT,GV_EXCHANGE_TYPE and
GV_CONV_DATE is mentioned below,
 Now "Save and Activate" the view and execute the query. On execution, you will receive below
pop-up for Variables and Input Parameter,
 Fill them as per your requirement as shown below,

Output of Analytic View


 SQLScript for Analytic View is shown below,
b) Creating New Column for Currency Conversion and keeping the Original Column
 We will use the existing example of Sales per Material and convert the measure (NETWR) from
USD to INR. In this example, aim is to have Original Column value and its converted value as
well.
 Click on Star Join and then create new Calculated Column,

 Since we are performing conversion of MEASURE field (NETWR), we can select Column Type as
"Measure" and fill the required fields as shown below,
Name of the field whose
value needs to be converted
to Target Currency

 As per above screen, Aggregation should happen "After calculation is complete" as checkbox
"Calculate before Aggregation" is not selected.
 In expression, enter the field which contains original value (in our case NETWR).Now click on tab
"Semantics" highlighted in RED color in above screenshot,
 Select Decimal Shift and Conversion checkboxes; fill the required fields for conversion.
 Here, you have an option either to hardcode values for conversion (which will never be case in
live system) or create "Input Parameter" for each field which will be know during execution as
shown below,
 Now "Save and Activate" the view and execute the query. On execution, you will receive below
pop-up for Variables and Input Parameter,
 Fill them as per your requirement as shown below,

Output of Analytic View


 SQLScript for Analytic View is shown below,

3. Calling Analytic View using SQLScript in Procedure


 Follow same process for creation of Procedure as discussed earlier in Attribute View steps 6 (
Calling Attribute View using SQLScript in Procedure ) and 7 ( Calling Attribute View using CE
Operation in Procedure ) for fetching data from Analytic View - AN_SALES_TRAINING_ATEST.
Default Schema can be mapped in Quality /
Production system via Schema Mapping so don’t
hardcode it in SQLScript when fetching data from
SAP tables.

So don't use "SAPEH2"."VBAP" in SQLScript,


instead use "VBAP" and Default Schema /
Schema Mapping will take care of Prefix.

 Input structure and Output Table structure is shown below,


 Below is the code for fetching data from Analytic view and passing Dynamic PLACEHOLDERS and
Variables as shown below

Pass dynamic
PLACEHOLDER values
in Procedure.

 Below is just an example of passing hard coded values in PLACEHOLDER,


Pass hardcoded
PLACEHOLDER values in
Procedure.

Calling
Procedure
in SQL
Console  Save and Activate the Procedure and execute it in SQL Console as shown below,

Output of Procedure:

4. CE Operator with Scalar Variables in Procedure


NOTE:

 Please keep in mind the below comments mentioned for PLACEHOLDERS and VARIABLES when using CE
Operators.
 Create new procedure which can output same result as Analytic View - AN_SALES_TRAINING_ATEST
using CE Operator.

Default Schema can be mapped in Quality /


Production system via Schema Mapping so don’t
hardcode it in SQLScript when fetching data from
SAP tables.

So don't use "SAPEH2"."VBAP" in SQLScript,


instead use "VBAP" and Default Schema / Schema
Mapping will take care of Prefix.
Definition of
Scalar Variable

Table Name without Schema


Prefix (Important)

Use of variables
Testing Procedure in SQL Console:

Output:

5. CE Operator with Unit Conversion Example in Procedure


 Create new procedure which can output same result as Analytic View - AN_SALES_TRAINING_ATEST
using CE Operator along with Unit Conversion to INR currency.
Unit
Conversion
Logic

Testing Procedure in SQL Console:

Output:

6. CE Operator with Input Parameters in Procedure


 Create new procedure which can output same result as Analytic View - AN_SALES_TRAINING_ATEST
using CE Operator along with Input Parameters and CE_CALC function.
Input
Parameter in
Conversion

Use of
CE_CALC
Use of Input Parameter

Testing Procedure in SQL Console:

Output:
7. Calling Procedure in Native SQL with Scalar Input
 Consider calling Procedure defined in Analytic View steps 5 namely
PROCEDURE_AN_VW_CE_CONVERSION in ABAP.
Delete Local Temporary
Table in HANA

Create Local Temporary


Table in HANA

Call HANA
Procedure from
ABAP
Read data from HANA Temporary Table

 Selection Screen of the Report is shown below,

 Output of the report is shown below,


8. Calling Procedure in Native SQL with Tabular Input

Business Scenario:
Fetch data from KNB1 table based on list of Customer no entered on selection screen.

 Create a new Procedure as shown below,

 Below is the screenshot of Output and Input Tables,


 In this example, Input is of table type namely CUSTOMER_NO and we can't read data directly
from input table.
 We need to fetch data from it and then use it as normal table variable. Below is code for it,

SQLScript and its


equivalent CE
Operator Code
 Calling the above procedure in ABAP report using Native SQL.
Delete Input Temporary Table of HANA

Delete Output Temporary Table of HANA

Create Input Temporary Table of HANA

Create Output Temporary Table of HANA

We need to fill the


temporary input table
with actual values from
Now, selection screen for
temporary customer no
input table is
filled and
output table
is initialized
so go ahead
and call the Fetch data from Temporary Output Table which
required is filled after Procedure execution.
Procedure
 Selection Screen of Report has Customer no as input parameter as shown below,

Output of the report:


9. Database Procedure Proxy in ABAP
 In this example, we will be converting the Procedure "PROCEDURE_TABLE_INPUT_EXAMPLE" to
Database Procedure Proxy in ABAP so that we can directly call it in ABAP without the use of
Native SQL.
 Go to ABAP perspective and click on the package where you want to create the new Database
Proxy Procedure. In our case, it will be saved in package $TMP(temporary object) as shown
below,
Procedure name to
be created in ABAP
so begin with 'Z'.

This interface can be


checked in SE24 after
successfully activating
the procedure in
ABAP

Transport Request
Details
 Synchronize the procedure from HANA to ABAP and then activate it as shown below,
Synchronize
and Activate.

 You can check the newly created interface in SE24 as shown below,
Use of Interface (from SE24)
for referencing input and
output parameters of
Procedure

Calling of Proxy
Procedure in ABAP

 Selection Screen of Report has Customer no as input parameter as shown below,


Output of the report:

Calculation View
 They are used to create your own data foundation using database tables, attribute views and
analytic views to address a complex business requirement.
 A calculation view is based on a calculation model that consists of Nodes and Operations.
 Nodes are any type of tables or views.
 Operations that can be performs on nodes are
a. Join
b. Projection
c. Aggregation
d. Union
e. Rank.
 There are 2 ways in which you can implement Calculation view namely
 Graphical Way.
 SQLScript Implementation.

 Follow below process for creating Calculation View,


Type, Data Category
and With Star Join
are the most
important properties
of Calculation View

Calculation View with Star Join

 It does not allow base column tables, Attribute Views or Analytic views to be added at data
foundation. All tables must be changed to Dimension Calculation views to use in Star Join. In
other words, create Calculation View of Data Category "Dimension" for tables or view which
needs to be added in Star Join.
 FACT tables have no such restriction in Calculation View with Star Join.
 Below is example of how to create Dimension Calculation View,
Dimension Calculation
View => Data Category as
Dimension

1. CA Graphical View => Cube

Business Scenario:
 To display Sales Data of VBAK and VBAP tables with summation at NETWR per material and
KWMENG per material for a sales order.

 Here, we create a Calculation View with Data Category as "CUBE" and not selecting the "With
Star Join" as shown below,
Default Node is
Aggregation for such
Calculation View

 First create two Projection nodes and then drag and drop tables VBAK and VBAP in Projection as
shown below,
Projection of VBAK Projection of VBAP
Table Table

Drag and Drop


VBAK and VBAP
tables from
Catalog

 Select output fields from each Projection Nodes of VBAK and VBAP tables as shown below,
 Next step is to create a join on projections of VBAK and VBAP. So create join node as shown
below,
Empty Join
Node

 Now add the projections of VBAK and VBAP to Join Node as shown below,

Click on VBAK_PROJ and drag and


drop the arrow towards
VBAK_VBAP_JOIN. Follow same
process for VBAP_PROJ. Now
both Projections of VBAK and
VBAP are added to Join Node
Join Node is filled with
projection data.

 Now, create join between the selected projections of VBAK and VBAP as shown below,
 Now select the fields in join node which will be visible to higher nodes as shown below,

 Click on VBAK_VBAP_JOIN node and drag and drop the arrow towards the Default Aggregation
Node as shown below,

 Select the columns from Aggregation Node which needs to be part of final output of Calculation
View as shown below,
 Since it is Aggregation Node, we need to add at least one column as "Aggregated Column" as
shown below,
Aggregated
Columns or
MEASURES

 Go to View Properties and select proper values for below fields


 Default Client
 Default Schema
 Apply Privileges

Don't use "Schema"."Table Name"


Cross while fetching data. Instead make use
Client as of Default Schema so that you can
it is make use of Schema Mapping for
training Quality / Production System and your Schema
system code works in other systems. determines
the source of
data for
tables.

 Save the view at this point.


 Define variables to restrict the no of records in output. In our case, we are creating variables for
Sales Order No and Client field as shown below,
 Go to "Parameters / Variables" Tab and click on "+" sign as shown below,
 Save and Activate the View and then go for Data Preview as shown below,
 Enter values for variables defined in Sales_Order_No and Client fields as shown below,

Output of the Calculation View:

a) Implementation via Procedure


 Here, we are implementing Calculation View "CA_VW_CUBE_EXAMPLE" (created from
Calculation View step 1)in Procedure as shown below,
 Below are the details of its Input and Output Structures,

 Now, enter the required code for fetching data from Calculation View
"CA_VW_CUBE_EXAMPLE" as shown below,
Input Parameters
of Procedure

Testing of Procedure:

 Call the procedure in SQL console and enter values mentioned below,

Output:

b) Implementation via External View


 Here, we are implementing Calculation View "CA_VW_CUBE_EXAMPLE" (created from
Calculation View step 1) using External View as shown below,
Custom View Name
in ABAP

View Type for External View

 You can enter your Transport Number here if applicable. In our case, it is temporary object and
hence no transport request.
 Activate your external view using below button,

 The External View "ZCA_VW_CUBE_EX" can be seen in SE11 as shown below,


 Next step is to create a report which will use the above external view for data fetching.
External View can be
used as source of data in
Open SQL Select
Statement

Selection Screen of Report:


Output:

2. CA Graphical View => Dimension


 This type of Calculation view is used when you want default node to be Projection.
 In other words, you want output to be projections of existing Tables, Views.
 Mostly used when you want to add tables or views in "With Star Join" of Calculation View as
shown below,

 Here, we will be using VBAP table and project few of its fields as output as shown below,
HANA View Name

Important fields for


Dimension Calculation View

 Default Node is Projection as shown below,

 Drag and drop VBAP table from required schema into Projection Node as show below,
 Select Output fields from VBAP table

 Save the changes at this point in Calculation View.


 Click on Semantics and then go to "Parameters / Variables tab.
 Click on "+" sign and then create variables for Sales Order No and Client as shown below,
 After adding variables, it is visible in "Columns" Tab as shown below,
 Now go to "View Properties" and enter proper values for
 Default Client.
 Default Schema.
 Apply Privileges.

 Save and activate your view.

Testing of Procedure:

 Now execute the view and enter valid values for Client and Sales Order no fields as shown
below,
Output:

a) Implementation via Procedure and Single Value Inputs for Sales Order and Client
 Create a new Procedure to implement CA view (CA_VW_DIMENSION_EXAMPLE) as shown
below,
 Its Input and Output Structure.
 Fetching data from CA View "CA_VW_DIMENSION_EXAMPLE" as show below,

Scalar Input
Parameters

 Testing of Procedure:
 Call the Procedure CA_VW_DIMENSION_EXAMPLE in SQL Console as shown below,

Output:
b) Implementation via Procedure and Dynamic Where Clause
 In this example, we will be passing dynamic where clause so that we can pass "SELECT-
OPTIONS" from ABAP to HANA Procedure.

 Create a single field input parameter which should be type string as shown below,

This will ensure that Input Parameter is of


type "STRING" so that we can pass any
number of characters in where clause.
 Using APPLY_FILTER helps you with dynamic where clause and it does not lead to performance
issue.

Dynamic Where Clause

 Next step is to create Database Procedure Proxy.


Below are the screenshot of creating Database Procedure Proxy,
 After synchronization, activate your proxy procedure as shown below,

 After activation of the Proxy Procedure, call the procedure in report.


But, in our case, we need to make sure that "SELECTION-OPTIONS" are converted to string and
then passed to Proxy Procedure.
 Please follow the below steps for converting "SELECT-OPTIONS" to String,
Get reference for SELECT-OPTION
field S_MANDT

Converting Where Clause to String and


replacing S_MANDT with "MANDT" by
using value LV_MANDT.

Get reference for SELECT-OPTION


field S_VBELN

Converting Where Clause to String and


replacing S_VBELN with "VBELN" by
using value LV_VBELN.
Below is an example of
LV_WHERE_CLAUASE_ALL
value in debugging mode

Selection Screen of Report:


Output:
3. CA Graphical View => Star Join
 We are trying to replicate an example of Analytic View of Sales per Material in Calculation View.
Here, intention is to use Star Join in Calculation View.
 So we use the option of Star Join when creating Calculation View as shown below,
 Dimension Table Rule:
It does not allow base column tables, Attribute
Views or Analytic views to be added at Star Join.
All tables except FACT Table need to be changed
to Dimension Calculation views before using them
directly in Star Join.
 Fact Table Rule:
All Fact tables can be added and can use default
nodes in Calculation View.

Default Node is
Star Join.
Add VBAK and VBAP
tables and then use
projection node

 Select the fields from each projection of VBAK and VBAP as shown below,
 Next step is to create Join between projection of VBAK and VBAP as shown below,
Creating Join
between
Projections of
VBAK and VBAP

Field
selection
from each
Projection
view
Data Foundation is
added in Star Join
in this step.

Selecting fields from Data


Foundations

 Next step is addition of other tables or Attribute View or Analytic View in Star Join. But, as per
rule, you can't directly use them in Star Join. Instead they need to be converted into Dimension
Calculation View and then you can add them in Star Join.
 In our example, we want to add Attribute View "AT_MATERIAL_TRAINING_ATEST" in Star Join.
So, first step is to convert the Attribute View into Dimension Calculation View and then use it in
Star Join.
 Below are the steps for converting Attribute View to Dimension Calculation View as shown
below,

Important field for


Dimension Calculation View

 Addition of Attribute View "AT_MATERIAL_TRAINING_ATEST" as shown below,

 Field selection from Projection Node,


 Below is the screenshot of Semantic => Column Tab,

 Save and activate the new Dimension Calculation View as shown below,

 Now, we can add the newly created Dimension Calculation View


"CA_DIMENSION_FOR_STAR_JOIN" in Star Join as shown below,
Calculation View with Data
Category as "Dimension"

 Create Join between Data Foundation and CA_DIMENSION_FOR_STAR_JOIN as shown below,


 Next step is to select the output fields from Star Join.

 Below is screenshot of Semantic Node => Columns Tab.


 Now, we can create Variables for Sales Order no and Client fields to restrict the output as shown
below,
 Always ensure you have selected the correct values for below fields in Semantic Node=>View
Properties Tab,
 Default Client
 Default Schema
 Apply Privileges

 Execute the view and enter required values as shown below,

Output of the View:


4. CA Graphical View => Union
 Here, we are trying to create Sales per Material but using Union Node in Calculation View.
 We can repeat below steps from CA Graphical View => Star Join,
 Create Projection for VBAK and VBAP.
 Use Union instead of Join Node.
 Use Aggregation instead of Star Join.
Default Node is
Aggregation Node

Projection Node
for VBAK and
VBAP
 Click on Union Node to get the below screen,

 We need to define the mapping for target fields using union. We have 2 options namely,
 Auto Map by Name => It will automatically map each field by its name.
 Manually Drag and Drop the fields to Target Pattern.
Click on auto mapping or you
can drag and drop required
fields to Target.
Add the Union and then
select the required fields.

Set as
MEASURE
 Save the changes at this point and create the variables for sales order no and client fields.
 Execute the view and enter the required values as shown below,

Output of the view:


Results from VBAK table

Results from VBAP table

5. CA Graphical View => Variable Mapping


 Here, we trying to create Calculation view which is using Analytic View with Variables and Input
Parameters. So, we need to map the variables and input parameters of Analytic view with
Calculation view using Variable Mapping.
 In our example, we are using analytic view of sales (AN_SALES_TRAINING_ATEST) as shown
below,
Default Node is
Projection Node
Addition of
Analytic View

Warning as Variables
and Input Parameter
are not mapped

 After selecting the output fields, Select Input Parameters and right click on it and choose
Manage Mappings as shown below,

 We have 2 options for mapping,


 Auto Mapping
 Manual Mapping by Drag and Drop fields to Calculation View Variables and Parameters

Drag and Drop here for


Auto Mapping Manual Mapping

 End results from Mapping is shown below,

 You can see that variables / Input Parameters are added in Semantic => Parameters / Variables
of Calculation View after Mapping is completed as shown below,
 Create Variables for Calculation View as shown below,
 Execute the view and enter the required fields as shown below,

Output of the View:

6. CA Graphical View => SQLScript


 Here, we create Calculation View of type SQLScript so that default node is Script.
 This will help us write SQLScript code in Calculation view.
 It is similar to working on Procedures.
 Create a new calculation view and select its type as SQL Script as shown below,
Default Node is Script View

 In our example, we want to display the output based on Sales Order Type as shown below,
MEASURE

 Below is the screenshot of Semantic => Columns Tab,

 Next step is to create Sales Order No as Variables as shown below,


Default Schema is
source of data during
select query.

 Execute the view and enter the required values as shown below,

Output of the View:


ABAP Managed Database Procedure (AMDP)
 ABAP Managed Database Procedures are a framework for managing and calling stored
procedures or database procedures in AS ABAP.
 An ABAP Managed Database Procedure (or AMDP procedure) is a procedure written in a
database-specific language (Native SQL, SQL Script and L) implemented in an AMDP method of
an AMDP class.
 The most important advantage of AMDP is that it is not dependent on HANA Studio. In other
words, Transport Request is taken care from ABAP side and follows the normal process of
release strategy.

1. AMDP Process Overview:

a. Step 1 => Declare your AMDP Class


 Open ABAP Perspective as shown below,

 Create a new class by using the path Package Name => New => ABAP Class as shown below,
 Enter the Class Name and its details as shown below,

ABAP Package
Name

Custom Class Name


ABAP Transport Request

 By default class definition created as shown below,

b. Step 2 => Declare your AMDP Methods


 Add statement "INTERFACES IF_AMDP_MARKER_HDB" after "PUBLIC SECTION".
 Create a method with Pass by Value Parameters as shown below,

First step is to use Interface


"IF_AMDP_MARKER_DATABA
SE_TYPE". In our example, it is
using database type as HDB.

Method which has


to be implemented
as AMDP must use
"PASS BY VALUE"
parameters.

c. Step 3 => Implement your AMDP Methods


 Now, we are in process of defining the method which will be implemented as AMDP
method as shown below,

By adding DATABASE
PROCEDURE statement in
method implementation
we ensures that it is
AMDP method

 Save and activate the class.


Save the Active the Class
Class after saving it
 Same class will be available in SE24 after activation as shown below,

Pass by Value

 The newly created class is now available in path Source Library -> Classes of the package
where it was saved as shown below,

d. Step 4 => Consume AMDP Methods in ABAP


 Create a custom report to call AMDP method in ABAP as shown below,
Calling AMDP
Method

 Selection Screen of report is shown below,

 Add the required customer on selection screen.


Output of the report:

2. Calling an AMDP Procedure from SQLScript


 The called database procedure must be specified after the addition USING of the
statement METHOD.
This method is
 Example of calling AMDP in another AMDP method is shown below,
AMDP Method

Calling of
AMDP
Method

 Create a new class following the same process mentioned in AMDP Process Overview topic.
Below is the code for the class where AMDP is called inside AMDP,
AMDP Method

AMDP Method

Calling AMDP
Method
inside AMDP
Method

Output of AMDP is used for


further selection of data

 Now next step is to consume the above AMDP method in ABAP report as shown below,
Calling AMDP
Method

 Execute the report and entered the required customer no on selection screen as shown below,

Output of the report


3. Calling an SQLScript Procedure from AMDP
 You can use the normal process of ADBC for calling Procedure in AMDP.
 Example of calling Procedure in AMDP method as shown below,
METHOD increase_price BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT.
Call "/1BCAMDP/ABAP_DOCU_DEMO_INCPRICE"( INC => :INCPRICE );
ENDMETHOD. Called Procedure
via ADBC

4. AMDP, SQL Script with Tabular CHANGING Parameter


 Below is the AMDP class which has 2 methods both having Changing Parameters as shown
below,

Changing
Parameter in
Methods

 Below is implementation of method "GET_CARRIERS" in SQLScript,


"CARRIERS" is used
"CARRIERS" is as Input Parameter
used as Output
Parameter

Same rule
 Now, method "CALL_GET_CARRIERS" internally calls the method "GET_CARRIERS". applies as
 Below is syntax of calling it, calling AMDP
methods
Mentioning
inside AMDP
"_IN_" is
required if
calling AMDP
with Changing
Parameter's in Changing Parameter = Same Parameter as
other methods. Input as well as Output.

 You can refer below link for more documents and examples of AMDP,
http://help.sap.com/abapdocu_740/en/index.htm?file=abenamdp.htm

Core Data Service (CDS)


 CDS will new way to create views, tables and structures in HANA.
 Below is overview of CDS scenario,
ABAP CDS in ABAP Dictionary
 The ABAP Core Data Services (ABAP CDS) are the implementation of the general CDS concept for
AS ABAP. ABAP CDS makes it possible to define semantic data models on the central database of
the application server.
 On AS ABAP, these models can be defined independently of the database system. The entities of
these models provide enhanced access functions when compared with existing database tables
and views defined in ABAP Dictionary, making it possible to optimize Open SQL-based
applications.
 This is particularly clear when an AS ABAP uses a SAP HANA database, since its in-memory
characteristics can be implemented in an optimum manner.
 The data models are defined using the data definition language (DDL) and data control language
(DCL) provided in the ABAP CDS.

ABAP CDS - Language Elements

 For creating CDS views, follow below steps.


 Go to ABAP perspective.
 Select your required package where you want to save your CDS View.
 Right click on the selected package and use the path New => Other ABAP Repository
Object as shown below,
 In below pop-up search for DDL,
 Select the option DDL Source and click on Next button as shown below,

 In the next popup, enter the name of the CDS view name as shown below,
CDS View Name
 In next popup, select the Transport Request in which you want to save the CDS view and click on
Finish button as shown below,
 Consider creating simple example of inner join between VBAK and VBAP table as shown below,
View name which
can seen in SE11

 Save and activate the view as shown below,

 After activation, view can be checked in SE11 as shown below,

Join condition for MANDT


appears in SE11 due to statement
@ClientDependent: true
 Now you can use Open SQL statement for fetching data from this view. But while fetching data
don’t use the SE11 view name, instead use the name of HANA Entity (HANA DDL Source).
 In our case, it is ZV_EXAMPLE_1_CDS. Below is the screenshot of ABAP report using the above
created view,
For using ABAP 7.40; please select Fixed
point arithmetic and Unicode Checks
Active
Data fetching
from CDS View

Report output:

Below sections summarize the language elements of the DDL and DCL of the ABAP CDS,

 Data Definition Language (DDL)


 CDS Views
 CDS View Enhancements
 Data Control Language (DCL) => Used for Authorizations.
 CDS Roles
 CDS Access Policies
1. CDS Views
 Used to create views in ABAP. Below is the list of Keywords used in its syntax,

Keywords and Additions

Language Element Meaning


DEFINE VIEW ... AS Defines a CDS view
WITH PARAMETERS Defines input parameters of a CDS view
SELECT [DISTINCT] ... FROM SELECT statement of a CDS view
INNER JOIN ... ON Inner join in a SELECT statement
LEFT|RIGHT OUTER JOIN ... ON Outer join in a SELECT statement
Defines an association for a path expression in
ASSOCIATION ... TO ... AS ... ON a SELECT statement
1:00 Attribute of a path expression
INNER ... WHERE Attribute of a path expression
LEFT OUTER ... WHERE Attribute of a path expression
KEY ... AS Element of a SELECT list
$EXTENSION.* Elements of an enhancement in a SELECT list
WHERE ... WHERE clause of a SELECT statement
GROUP BY ... GROUP-BY clause of a SELECT statement
HAVING ... HAVING clause of a SELECT statement
UNION ALL ... UNION clause of a SELECT statement

Expressions

Operators Meaning
MAX, MIN, AVG, SUM, COUNT Aggregate expressions in a SELECT statement
+, -, *, / Arithmetic expressions in a SELECT statement
CASE, WHEN, THEN, ELSE, END Case distinctions in a SELECT statement
CAST Casting expression in a SELECT statement
=, <>, <, >, <=, >=, BETWEEN, LIKE, IS
NULL, NOT, AND, OR Relational expressions in a SELECT statement

 Define View in ABAP ABAP View name


 Syntax found in SE11

@AbapCatalog.sqlViewName: 'CDS_DB_VIEW'
...
[DEFINE] VIEW cds_entity
Name of CDS Entity
[name_list]
Column name of final output [parameter_list] Input Parameters for the view
AS select_statement [;]
Select statement
a. Example 1: Simple Select Statement
ABAP View name
found in SE11
@AbapCatalog.sqlViewName: 'ZV_ATEST_01'
Define View ZV_ATEST_01_CDS
Name of CDS Entity
As select from VBAP
{
Key VBAP.MANDT,
Key VBAP.VBELN,
Key VBAP.POSNR,
VBAP.MATNR
};

b. Example 2: Name List

We can provide
@AbapCatalog.sqlViewName: 'ZV_ATEST_02' column name here
Define View ZV_ATEST_02_CDS
(client, sales_order_no, item_no, material)
As select from VBAP
{
Key VBAP.MANDT,
Key VBAP.VBELN,
Key VBAP.POSNR,
VBAP.MATNR
};

Restriction on Name List:


 No name list can be used if the SELECT list is specified with * or if the element list contains the
entry $EXTENSION.* or in EXTEND_VIEW.

c. Example 3: Parameter List

Input Parameters
@AbapCatalog.sqlViewName: 'ZV_ATEST_02' for the view
Define View ZV_ATEST_02_CDS
With parameters P_VBELN: ABAP.CHAR (10),
P_POSNR : ABAP.NUMC (6)
As select from VBAP
{
Key VBAP.MANDT,
Key VBAP.VBELN,
Key VBAP.POSNR,
VBAP.MATNR
}
WHERE VBELN = :P_VBELN
Two different ways
AND POSNR = $PARAMETERS.P_POSNR
to address input
parameters
Restriction on Parameter List:
 We can use it as operand in below places,
i. Element in the select list.
ii. Operand of an arithmetic expression.
iii. Operand "operand" directly after case in a case distinction.
iv. Right side of an expression in
 Where Clause or Having Clause.
 On condition in an ABAP join or an association.
 In a filter condition of a path expression.

2. CDS View Enhancements

Keywords and Additions

Language Element Meaning


Enhancement of a CDS view with an CDS view
EXTEND VIEW ... WITH enhancement

 Extend View:
 Syntax:
@AbapCatalog.sqlViewAppendName: 'CDS_APPEND_VIEW'
...
EXTEND VIEW cds_entity WITH cds_view_extension
{
select_list_extension
} [;]
 Example : Extend Existing View
@AbapCatalog.sqlViewAppendName: 'ZV_ATEST_01_EXT'

EXTEND VIEW ZV_ATEST_01_CDS Name of existing entity which


WITH ZV_ATEST_01_EXT_CDS needs to be extended
{
VBAP.NETWR
VBAP.KWMENG
}; Extension entity name

Restriction on Extend View:


 Can't enhance views with explicit name list, group by clause and with UNION clause for
union sets.
3. CDS Roles

Keywords and Additions

Language Element Meaning


DEFINE ROLE ... GRANT SELECT ON Defines a CDS role
WHERE, AND, OR WHERE clause in the definition of a CDS role
... = ASPECT pfcg_auth ... Condition for mapping roles
... =|<>|<|>|<=|>=|LIKE|IS NULL
ASPECT ... Condition for assignment roles
... =|<>|<|>|<=|>=|LIKE|IS NULL
... Literal condition

 Refer http://help.sap.com/abapdocu_740/en/index.htm?file=abencds_annotations.htm for


examples of CDS ROLES.

4. CDS Access Policies

Keywords and Additions

Language Element Meaning


DEFINE ACCESSPOLICY Defines a CDS access policy
DEFINE ASPECT ... AS Defines a CDS aspect
SELECT FROM SELECT statement of an CDS aspect
WHERE $user IN WHERE clause of the SELECT statement of an CDS aspect

 Refer http://help.sap.com/abapdocu_740/en/index.htm?file=abencds_annotations.htm for


examples of CDS Access Policies.

ABAP 7.40 and above release


1. Escape Character for Host Variables

ABAP data objects used in Open SQL statements (usually variables) are now interpreted as host
variables.

From Release 7.40, SP05, host variables can and should be prefixed with the escape character @.
Host variables without the escape character are obsolete.

If the escape character is used in front of a name of an Open SQL statement, the syntax check is
performed in a strict mode, which handles the statement more strictly than the regular syntax check.

The escape character can only be used in Unicode programs, in which the program property fixed point
arithmetic is activated.
EXAMPLE:

SELECT VBELN ,
POSNR ,
MATNR
FROM VBAP
INTO TABLE @LIT_VBAP
WHERE VBELN = @P_VBELN.

2. String Templates
The purpose of a string template is to create a new character string out of literal texts and embedded
expressions.
A string template is defined by using the | (pipe) symbol at the beginning and end of a template.

Description Before 7.40 After 7.40


String Template DATA: lv_character_string TYPE string. DATA: lv_character_string TYPE string.
Normal Assignment lv_character_string = `This is a literal text. `. lv_character_string = |This is a literal text.|.

The added value of a string template becomes clear when combining literal texts with embedded
expressions and control characters.
Embedded expressions are defined within a string template with curly brackets { expression }. Note that
a space between bracket and expression is obligatory.

An expression can be a data object (variable), a functional method, a predefined function or a


calculation expression.
Examples:

Before ABAP 7.40

After ABAP 7.40

Output:
3. Chaining Operator
 The Chaining Operator && can be used to create one character string out of multiple other
strings and string templates.
 The use of the chaining operator is to replace CONCATENATE statement.
 In this example, a number text, a space, an existing character string and a new string template
are concatenated into a new character string.

lv_string = 'Text literal'(002) && |{amount_field NUMBER = USER }|.

4. Inline Declaration
 You can now directly define variables, field symbols or internal table will using them.

Description Before 7.40 After 7.40


Data Declaration in Normal Scenario DATA: LV_TEXT TYPE STRING. DATA(TEXT) = 'ABC'.
and in Call Method
LV_TEXT = 'ABC'.

Field Symbol Declaration DATA: <LFS_LINE> TYPE -------- LOOP AT ITAB ASSIGNING FIELD-SYMBOL(<LFS_LINE>).
-----------
LOOP AT ITAB ASSIGNING <LFS_LINE>. ENDLOOP.
-----------
ENDLOOP.

Select Into Table Declaration (ONLY DATA: ITAB TYPE TABLE OF VBAK, DATA: LV_VBELN TYPE VBAK-VBELN.
POSSIBLE IN ABAP 7.50 RELEASE) LV_VBELN TYPE VBAK-VBELN.
SELECT *
SELECT * FROM VBAK
FROM VBAK INTO TABLE @DATA(ITAB)
INTO TABLE ITAB WHERE VBELN = @LV_VBELN.
WHERE VBELN = LV_VBELN.

Select Single Into Declaration(ONLY PARAMETERS: P_VBELN TYPE VBAK-VBELN. PARAMETERS: P_VBELN TYPE VBAK-VBELN.
POSSIBLE IN ABAP 7.50 RELEASE)
DATA: LV_VBELN TYPE VBAK-VBELN, SELECT SINGLE VBELN,
LV_AUART TYPE VBAK-AUART. AUART
FROM VBAK
SELECT SINGLE VBELN AUART INTO @DATA(LWA_VBAK)
FROM VBAK WHERE VBELN = @P_VBELN.
INTO ( LV_VBLEN, LV_AUART) IF SY-SUBRC = 0.
WHERE VBELN = P_VBELN. WRITE : / LWA_VBAK-VBELN , LWA_VBAK-AUART.
IF SY-SUBRC = 0. ENDIF.
WRITE : / LV_VBELN , LV_AUART.
ENDIF.
5. Table Expression
 Table expression is a new way to read data from internal table.

Description Before 7.40 After 7.40


Index access READ TABLE lit_vbak INTO lwa_vbak INDEX 5. LWA_VBAK = LIT_VBAK [ 5 ].
Index access using a
secondary index READ TABLE itab INDEX idx USING KEY key INTO lwa. LWA = itab [ KEY key INDEX idx ].
Access using a free key READ TABLE LIT_VBAK INTO LWA_VBAK LWA_VBAK = LIT_VBAK [ VBELN = P_VBELN
WITH KEY VBELN = P_VBELN AUART = P_AUART ].
AUART = P_AUART.
Key access using a table SYNTAX: SYNTAX:
key
READ TABLE itab WITH TABLE KEY key COMPONENTS col1 = ... lwa = itab [KEY key col1 = ... col2 = ...]. OR
col2 = ... INTO lwa. lwa = itab [KEY key COMPONENTS col1 = ... col2 = ...].

Example: Example:

TYPES: BEGIN OF TY_VBAP, LWA_VBAP = LIT_VBAP [ KEY MAT_PLANT


VBELN TYPE VBAP-VBELN, MATNR = P_MATNR
POSNR TYPE VBAP-POSNR, WERKS = P_WERKS ].
MATNR TYPE VBAP-MATNR,
WERKS TYPE VBAP-WERKS, OR
END OF TY_VBAP.
LWA_VBAP = LIT_VBAP [ KEY MAT_PLANT
DATA: LIT_VBAP TYPE STANDARD TABLE OF TY_VBAP COMPONENTS MATNR = P_MATNR
WITH KEY VBELN POSNR WERKS = P_WERKS ].
WITH NON-UNIQUE SORTED KEY
MAT_PLANT
COMPONENTS MATNR WERKS,
LWA_VBAP TYPE TY_VBAP.

READ TABLE LIT_VBAP WITH TABLE KEY MAT_PLANT


COMPONENTS MATNR = P_MATNR
WERKS = P_WERKS
INTO LWA_VBAP.
Does Record Exist? IF LINE_EXISTS(LIT_VBAK[ VBELN = P_VBELN
AUART = P_AUART ] ).

"Record Found.

READ TABLE lit_vbak WITH KEY vbeln = p_vbeln ELSE.


auart = p_auart
TRANSPORTING NO FIELDS. "Record not Found"
IF SY-SUBRC = 0.
……………… ENDIF.
ENDIF.
Get Table Index DATA(IDX) = LINE_INDEX( LIT_VBAK[ VBELN = P_VBELN
AUART = P_AUART ] ).
IF IDX = 0.
DATA IDX TYPE SY-TABIX. "Record NOT Found.
READ TABLE …………. TRANSPORTING NO FIELDS.
IF SY-SUBRC = 0. ELSE.
IDX = SY-TABIX.
ENDIF. " IDX will have the index no.
ENDIF.

 If the specified row is not found, a handle able expression of the


class CX_SY_ITAB_LINE_NOT_FOUND is raised in all operand positions, except when
 When used in function line_exists.
 When used in function line_index.

 Example:
TRY.
LWA_VBAK = LIT_VBAK[VBELN = '1'].
………………
CATCH CX_SY_ITAB_LINE_NOT_FOUND.
……………….
ENDTRY.
 There will be a short dump if you use an inline expression that references a non-existent record.
SAP says you should therefore assign a field symbol and check sy-subrc.
ASSIGN LIT_ITAB[ 1 ] to FIELD-SYMBOL(<LFS_ITAB>).
IF sy-subrc = 0.
...
ENDIF.
 Example:
DATA: itab TYPE TABLE OF I,
lwa_tab TYPE I.
lwa_tab = 3.
Append lwa_tab to itab.
lwa_tab = 5.
Append lwa_tab to itab.
"Bad example
itab[table_line = 3] =itab[ table_line = 3 ] * itab[ table_line = 3 ].
"Good example
ASSIGN itab[ table_line = 5 ] TO FIELD-SYMBOL(<fs>).
<fs> = <fs> * <fs>.
 Example of Index:
Index Table Expression

No SY-SUBRC check is possible,


instead use
CX_SY_ITAB_LINE_NOT_FOUND
exception check.

Selection Screen:

OUTPUT:

 Example of Access using Free Key:


Reading table using free key access
key.

Use of String Templates

Selection Screen:

OUTPUT:

 Example using Table Key:


Reading data using table
key

Selection Screen:

Output:
 Example of Record exist in Table:

Checking if record exists in internal table

Selection Screen:

Output:

 Example of Line Index:


Selection Screen:

Output:
6. Conversion Operator
 Syntax:

CONV dtype(...) OR CONV #(...)

dtype => Type you want to convert to.


# => compiler must use the context to decide the type to convert to.

 Example: Conversion from CHARACTER to STRING and finally to XTRING

Before 7.40:

After 7:40:

OR
7. Value Operator
 The value operator VALUE is used to fill complex data objects with values in operand positions,
create initial values of any data type, or control the results of table expressions.
 Syntax:

Structures: VALUE dtype( comp1 = a1 comp2 = a2 ... ) OR


VALUE #( comp1 = a1 comp2 = a2 ... )

Tables: VALUE dtype( (comp1 = a1 comp2 = a2) (comp1 = a3 comp2 = a4) ... ) ) OR
VALUE #( (comp1 = a1 comp2 = a2 ) (comp1 = a3 comp2 = a4) ... ))

 Example of Table(unstructured):

Filling Unstructured Internal Table

This is one way to check sy-subrc


when accessing table entry.

Output:
Description Before 7.40 After 7.40
Value TYPES: BEGIN OF TY_STRUCT, TYPES: BEGIN OF TY_STRUCT,
Operator FIRST(4) TYPE C, FIRST(4) TYPE C,
Structure SEC(4) TYPE C, SEC(4) TYPE C,
Example LAST(4) TYPE C, LAST(4) TYPE C,
END OF TY_STRUCT. END OF TY_STRUCT.

DATA: LWA_STRUCT TYPE TY_STRUCT. DATA: LWA_STRUCT TYPE TY_STRUCT.

LWA_STRUCT-FIRST = 'ONE' . LWA_STRUCT = VALUE #( FIRST = 'ONE' SEC = 'TWO' LAST = 'THREE' ).
LWA_STRUCT-SEC = 'TWO'.
LWA_STRUCT-LAST = 'THREE' . CL_DEMO_OUTPUT=>DISPLAY( LWA_STRUCT ).

CL_DEMO_OUTPUT=>DISPLAY( LWA_STRUCT ).

Value TYPES : BEGIN OF TY_STRUCT, TYPES : BEGIN OF TY_STRUCT,


Operator FIRST(4) TYPE C, FIRST(4) TYPE C,
Table SEC(4) TYPE C, SEC(4) TYPE C,
Example LAST(4) TYPE C, LAST(4) TYPE C,
END OF TY_STRUCT. END OF TY_STRUCT.

DATA: LWA_STRUCT TYPE TY_STRUCT, DATA: LIT_STRUCT TYPE TABLE OF TY_STRUCT.


LIT_STRUCT TYPE TABLE OF TY_STRUCT.
* Appending entries in internal table
LWA_STRUCT-FIRST = 'ONE' .
LWA_STRUCT-SEC = 'TWO'. LIT_STRUCT = VALUE #( ( FIRST = 'ONE' SEC = 'TWO' LAST = 'THREE' )
LWA_STRUCT-LAST = 'THREE' . ( FIRST = '1' SEC = '2' LAST = '3' ) ).

APPEND LWA_STRUCT TO LIT_STRUCT. CL_DEMO_OUTPUT=>DISPLAY( LIT_STRUCT ).

LWA_STRUCT-FIRST = '1' .
LWA_STRUCT-SEC = '2'.
LWA_STRUCT-LAST = '3' .

APPEND LWA_STRUCT TO LIT_STRUCT.

CL_DEMO_OUTPUT=>DISPLAY( LIT_STRUCT ).

8. New Operator
 A constructor expression with the instance operator NEW creates an anonymous data object or
an instance of a class. The result is a reference variable that points to the new object.
 Syntax:
NEW type(…….)

Description Before 7.40 After 7.40


NEW Operator DATA: LO_REF TYPE REF TO CL_XML_DOCUMENT. DATA(LO_REF) = NEW CL_XML_DOCUMENT( ).

CREATE OBJECT LO_REF.


9. For Operator
 FOR is the Iteration Expression. An iteration expression is to perform the iteration on the table.
The FOR can be used with Constructor Operators – like NEW, VALUE.
 Syntax:
a. ... FOR wa|<fs> IN itab [INDEX INTO idx] [ cond] [let_exp] ...

Description Before 7.40 After 7.40


For TYPES: BEGIN OF ty_vendor, TYPES: BEGIN OF ty_vendor,
Operator vendor TYPE char10, vendor TYPE char10,
IN .. city TYPE char30, city TYPE char30,
WHERE… route TYPE char10, route TYPE char10,
END OF ty_vendor. END OF ty_vendor.

DATA : t_vendors TYPE SORTED TABLE OF ty_vendor WITH TYPES: tt_vendors TYPE SORTED TABLE OF ty_vendor
UNIQUE KEY vendor, WITH UNIQUE KEY vendor,
lit_citys TYPE STANDARD TABLE OF char30 WITH EMPTY KEY, tt_citys TYPE STANDARD TABLE OF char30 WITH EMPTY
lwa_citys LIKE LINE OF lit_citys, KEY.
lwa_vendor LIKE LINE OF t_vendors.
DATA(t_vendors) = VALUE tt_vendors(
lwa_vendor-vendor = 'A0001'. ( vendor = 'A0001' city = 'MH' route = 'R0007' )
lwa_vendor-city = 'MH'. ( vendor = 'A0002' city = 'TM' route = 'R0008' )
lwa_vendor-route = 'R0007'. ( vendor = 'A0003' city = 'RS' route = 'R0007' )
append lwa_vendor to t_vendors. ( vendor = 'A0004' city = 'BA' route = 'R0004' ) ).

lwa_vendor-vendor = 'A0002'. * FOR Operator to get the column CITY


lwa_vendor-city = 'TM'. DATA(lit_citys) = VALUE tt_citys( FOR ls_cust IN t_vendors
lwa_vendor-route = 'R0008'. WHERE ( route = 'R0007' )
append lwa_vendor to t_vendors. ( ls_cust-city ) ).

lwa_vendor-vendor = 'A0003'. CL_DEMO_OUTPUT=>DISPLAY( lit_citys ).


lwa_vendor-city = 'RS'.
lwa_vendor-route = 'R0007'.
append lwa_vendor to t_vendors.

lwa_vendor-vendor = 'A0004'.
lwa_vendor-city = 'BA'.
lwa_vendor-route = 'R0004'.
append lwa_vendor to t_vendors.

LOOP AT t_vendors INTO lwa_vendor WHERE route ='R0007'.

lwa_citys = lwa_vendor-city.
APPEND lwa_citys to lit_citys.

ENDLOOP.

CL_DEMO_OUTPUT=>DISPLAY( lit_citys ).

OUTPUT:

b. ... FOR ….. [THEN expression] UNTIL|WHILE log_expression ...

Description Before 7.40 After 7.40


For Operator TYPES: BEGIN OF line, TYPES: BEGIN OF line,
UNTIL(ONLY col1 TYPE i, col1 TYPE i,
POSSIBLE IN col2 TYPE i, col2 TYPE i,
ABAP 7.50 col3 TYPE i, col3 TYPE i,
RELEASE) END OF line. END OF line.

DATA : itab TYPE STANDARD TABLE OF line WITH EMPTY KEY, TYPES : itab TYPE STANDARD TABLE OF line WITH EMPTY KEY.
wa LIKE LINE OF itab.
DATA(itab) = VALUE itab(
wa-col1 = 11. FOR j = 11 THEN j + 10 UNTIL j > 40
wa-col2 = 12. ( col1 = j col2 = j + 1 col3 = j + 2 ) ).
wa-col3 = 13.
APPEND wa TO itab.
CL_DEMO_OUTPUT=>DISPLAY( itab ).
wa-col1 = 21.
wa-col2 = 22.
wa-col3 = 23. OUTPUT :
APPEND wa TO itab.
COL1 COL2 COL3
wa-col1 = 31. 11 12 13
wa-col2 = 32. 21 22 23
wa-col3 = 33. 31 32 33
APPEND wa TO itab.

CL_DEMO_OUTPUT=>DISPLAY( itab ).

For Operator TYPES: BEGIN OF line, TYPES: BEGIN OF line,


WHILE(ONLY col1 TYPE i, col1 TYPE i,
POSSIBLE IN col2 TYPE i, col2 TYPE i,
ABAP 7.50 col3 TYPE i, col3 TYPE i,
RELEASE) END OF line. END OF line.

DATA : itab TYPE STANDARD TABLE OF line WITH EMPTY KEY, TYPES : itab TYPE STANDARD TABLE OF line WITH EMPTY KEY.
wa LIKE LINE OF itab.
itab = VALUE #( FOR j = 1 WHILE j <= 3 ( col1 = j col2 = j + 1
wa-col1 = 1. col3 = j + 2 ) ).
wa-col2 = 2.
wa-col3 = 3. CL_DEMO_OUTPUT=>DISPLAY( itab ).
APPEND wa TO itab.
OUTPUT:
wa-col1 = 2.
wa-col2 = 3.
wa-col3 = 4. COL1 COL2 COL3
APPEND wa TO itab. 1 2 3
2 3 4
wa-col1 = 3. 3 4 5
wa-col2 = 4.
wa-col3 = 5.
APPEND wa TO itab.

CL_DEMO_OUTPUT=>DISPLAY( itab ).

10. Filter in ABAP 7.50


The new FILTER operator enables two kinds of filtering an internal table.
SYNTAX:

... FILTER type( itab [EXCEPT] [IN ftab] [USING KEY keyname]
WHERE c1 op f1 [AND c2 op f2 [...]] ) ...

FILTER with single values

REPORT demo_filter_value_condition.

CLASS demo DEFINITION.


PUBLIC SECTION.
CLASS-METHODS main.
ENDCLASS.

CLASS demo IMPLEMENTATION.


METHOD main.
DATA carrid TYPE spfli-carrid VALUE 'LH'.
cl_demo_input=>add_field( CHANGING field = carrid ).
DATA cityfrom TYPE spfli-cityfrom VALUE 'Frankfurt'.
cl_demo_input=>request( CHANGING field = cityfrom ).

DATA spfli_tab TYPE STANDARD TABLE OF spfli


WITH EMPTY KEY
WITH NON-UNIQUE SORTED KEY carr_city
COMPONENTS carrid cityfrom.

SELECT *
FROM spfli
INTO TABLE @spfli_tab.

DATA(extract) =
FILTER #( spfli_tab USING KEY carr_city
WHERE carrid = CONV #( to_upper( carrid ) ) AND
cityfrom = CONV #( to_upper( cityfrom ) ) ).

cl_demo_output=>display( extract ).

DATA(rest) =
FILTER #( spfli_tab EXCEPT USING KEY carr_city
WHERE carrid = CONV #( to_upper( carrid ) ) AND
cityfrom = CONV #( to_upper( cityfrom ) ) ).

ASSERT lines( extract ) + lines( rest ) = lines( spfli_tab ).

ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
demo=>main( ).
Those rows are filtered from an internal table spfli_tab filled with flight data that have a specific value in
the columns carrid and cityfrom and the result is assigned to an internal table extract. A suitable
secondary key carr_city is defined for the internal table here.

A further internal table, rest, is given the same table filtering, but the addition EXCEPT is specified. The
assertion statements ASSERT demonstrates that rest contains all rows from spfli_tab that are not
in extract.

FILTER with filter table

REPORT demo_filter_table.

CLASS demo DEFINITION.


PUBLIC SECTION.
CLASS-DATA:
cityfrom TYPE spfli-cityfrom VALUE 'Frankfurt',
cityto TYPE spfli-cityto VALUE 'New York'.
CLASS-METHODS:
main,
init.
ENDCLASS.

CLASS demo IMPLEMENTATION.


METHOD main.
init( ).

TYPES: BEGIN OF filter,


cityfrom TYPE spfli-cityfrom,
cityto TYPE spfli-cityto,
END OF filter,
filter_tab TYPE HASHED TABLE OF filter
WITH UNIQUE KEY cityfrom cityto.

DATA(filter_tab) = VALUE filter_tab(


( cityfrom = cityfrom cityto = cityto )
( cityfrom = cityto cityto = cityfrom ) ).

SELECT carrid, connid, cityfrom, cityto


FROM spfli
ORDER BY carrid, connid, cityfrom, cityto
INTO TABLE @DATA(spfli_tab).

cl_demo_output=>display( FILTER #( spfli_tab IN filter_tab


WHERE cityfrom = cityfrom AND
cityto = cityto ) ).

ENDMETHOD.
METHOD init.
cl_demo_input=>add_field( CHANGING field = cityfrom ).
cl_demo_input=>request( CHANGING field = cityto ).
cityfrom = to_upper( cityfrom ).
cityto = to_upper( cityto ).
IF cityfrom = cityto.
LEAVE PROGRAM.
ENDIF.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
demo=>main( ).

Those rows are filtered out of an internal table spfli_tab filled with flight data that have specific
values in the columns cityfrom and cityto.

The filter is applied using a filter table of the type filter_tab constructed using VALUE filled with
input values. The result is all the outbound and return flights for the cities in question.

11. Casting Operator

The casting operator CAST is a constructor operator that executes an up or down cast for reference variables with
the type specified in type.

... CAST dtype|class|interface|#( ... ) ...

You use CAST for a down cast where you needed helper variables before in order to cast with ?= to a requested
reference type.
You use CAST for an up cast, e,g, with an inline declaration, in order to construct a more general type.
You can write a component selector -> directly behind CAST type( ... ).

Example from RTTI

Common example where a down cast is needed.

Before release 7.40

DATA structdescr TYPE REF TO cl_abap_structdescr.


structdescr ?= cl_abap_typedescr=>describe_by_name( 'T100' ).

DATA components TYPE abap_compdescr_tab.


components = structdescr->components.

With release 7.40


Cast Down from Super Class CL_ABAP_TYPEDESCR
to CL_ABAP_STRUCTDESCR

Output:

Example with up cast

The static type of the reference variable iref declared inline should be the interface not the class.

INTERFACE if.
...
ENDINTERFACE.

CLASS cl DEFINITION CREATE PRIVATE.


PUBLIC SECTION.
INTERFACES if.
CLASS-METHODS factory RETURNING value(ref) TYPE REF TO cl.
...
ENDCLASS.

CLASS cl IMPLEMENTATION.
METHOD factory.
ref = NEW #( ).
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA(iref) = CAST if( cl=>factory( ) ).
Example with data objects

A constructor expression with CAST followed by -> is an LHS-expression, you can assign values to it.

TYPES: BEGIN OF t_struc,


col1 TYPE i,
col2 TYPE i,
END OF t_struc.

DATA dref TYPE REF TO data.


DATA struc TYPE t_struc.

dref = NEW t_struc( ).

CAST t_struc( dref )->col1 = struc-col1.

12. Condition Operators


COND:

SYNTAX:

... COND dtype|#( WHEN log_exp1 THEN result1


[ WHEN log_exp2 THEN result2 ]
...
[ ELSE results ] ) ...

constructs a result of the specified type that depends on logical expressions.

Example for COND

OUTPUT:

SWITCH
... SWITCH dtype|#( operand
WHEN const1 THEN result1
[ WHEN const2 THEN result2 ]
...
[ ELSE result ] ) ...

constructs a result of the specified type that depends on a case differentiation.


With other words: IF and CASE as expressions in operand positions!

Example for SWITCH

OR

13. Is Instance of
The new predicate expression IS INSTANCE OF can be used to detect the dynamic type of an object
reference variable. This makes it possible to check the feasibility of a down cast before it is executed.

In the below example, a check is done to determine if variable PARAM is a table, a structure or referring
to a data element.
14. Move-Corresponding

Syntax :
Variant for Structures

MOVE-CORRESPONDING [EXACT] struc1 TO struc2


[EXPANDING NESTED TABLES].
Example:

TYPES: BEGIN OF line1,


col1 TYPE i,
col2 TYPE i,
END OF line1,
BEGIN OF line2,
col2 TYPE i,
col3 TYPE i,
END OF line2.

DATA: BEGIN OF struc1,


comp1 TYPE c LENGTH 1 VALUE 'U',
BEGIN OF struci,
comp1 TYPE c LENGTH 1 VALUE 'V',
BEGIN OF comp2,
col1 TYPE c LENGTH 1 VALUE 'X',
col2 TYPE c LENGTH 1 VALUE 'Y',
END OF comp2,
END OF struci,
itab TYPE TABLE OF line1 WITH EMPTY KEY,
END OF struc1.

DATA: BEGIN OF struc2,


BEGIN OF struci,
comp1 TYPE string,
comp2 TYPE string,
comp3 TYPE string,
END OF struci,
itab TYPE TABLE OF line2 WITH EMPTY KEY,
END OF struc2.

struc1-itab = VALUE #(
( col1 = 11 col2 = 12 )
( col1 = 21 col2 = 22 ) ).

MOVE-CORRESPONDING struc1 TO struc2.


MOVE-CORRESPONDING struc1 TO struc2 EXPANDING NESTED TABLES.

Output:

MOVE-CORRESPONDING struc1 TO struc2


MOVE-CORRESPONDING struc1 TO struc2
EXPANDING NESTED TABLES

Variant for Internal Tables

MOVE-CORRESPONDING [EXACT] itab1 TO itab2


[EXPANDING NESTED TABLES] [KEEPING TARGET LINES].

The statement MOVE-CORRESPONDING finds the identically named


components col2 and col3 in itab1 and itab2 and the assignments work as follows:

 MOVE-CORRESPONDING

The original content of itab2 is deleted. After the assignment, the columns col2 and col3 have
the same content as in itab1, whereas col4remains initial.

 MOVE-CORRESPONDING KEEPING TARGET LINES

The original content of itab2 is preserved. Three new rows are added in which the
columns col2 and col3 have the same content as in itab1, whereas col4 remains initial .

 MOVE-CORRESPONDING EXPANDING NESTED TABLES

The original content of itab2 is deleted. After the assignment, the column col2 has the same
content as in itab1 and col4 remains initial. The tabular component col3 is resolved and the
identically named component col2 found there. The original content of itab2-col3 is deleted.
After the assignment, the column col2 has the same content as in itab1-col3, whereas the
column col3 remains initial.

 MOVE-CORRESPONDING EXPANDING NESTED TABLES KEEPING TARGET LINES

The original content of itab2 is preserved. Three new rows are added, to which the same applies
as to the results of the previous assignment.
15. CL_ABAP_CORRESPONDING - SYSTEM CLASS in ABAP 7.50

The system class CL_ABAP_CORRESPONDING enables assignments of components between structures or between
internal tables with dynamically specified mapping rules.

The factory method CREATE of a class must be used to create a mapping object before the class can be used:

DATA(mapper) = cl_abap_corresponding=>create( source = struct|itab


destination = struct|itab
mapping = mapping_tab ).

Structures struct or internal table's itab of the assigned data types must be passed to the
parameters source and destination.

An internal table of the type CL_ABAP_CORRESPONDING=>MAPPING_TABLE, containing the mapping rule, must be
passed to the parameter mapping. If an initial mapping table is passed, only the identically named components are
assigned. The mapping table has the following components:

 LEVEL

Level of the components in the structure or row structure. The value 0 stands for the top level.

 KIND

Mapping type. The possible values are:

o CL_ABAP_CORRESPONDING=>MAPPING_COMPONENT (1) (The components specified in this row are


mapped to each other.)

o CL_ABAP_CORRESPONDING=>MAPPING_EXCEPT_COMPONENT (2) (The component of the source


structure specified in this row is excluded from the mapping of identically named components.)

o CL_ABAP_CORRESPONDING=>MAPPING_EXCEPT_ALL (3) (All components of the current source


structure are excluded from the mapping of identically name components.)

 SRCNAME

Component of the source structure.

 DSTNAME

Component of the target (destination) structure.

The rows of the internal table must be constructed so that they produce a mapping rule in the correct order.
Components of the source structure for which no mapping is defined and that were not excluded are assigned to
identically named components of the target structure.
The method EXECUTE of a mapping object can be used to perform any number of assignments between structures
or internal tables src and dst whose data type matches the source type or target type specified when the object
was created:

mapper->execute( EXPORTING source = src


CHANGING destination = dst ).

The assignment is performed component by component

 between the components specified in the mapping rule

 between the remaining identically named components at the same level (if not excluded in the mapping
rule).

In assignments between structures, components of the target structure to which no components of the source
structure are assigned keep their previous value, like the statement MOVE-CORRESPONDING but unlike the
operator CORRESPONDING without the addition BASE.

Any nested internal tables are always resolved, as when the addition EXPANDING NESTED TABLES is specified
in MOVE-CORRESPONDING or the addition DEEP for the operator CORRESPONDING. In assignments between
internal tables, the target table is always initialized first.

There is no matching addition for the addition KEEPING TARGET LINES in MOVE-
CORRESPONDING or BASE in CORRESPONDING.

Source and target must not be the same otherwise the runtime error CORRESPONDING_SELF can occur. Incorrect
parameters passed to the methods of the class CL_ABAP_CORRESPONDING raised exceptions of the
class CX_CORR_DYN_ERROR.

Example:

Uses the class CL_ABAP_CORRESPONDING for assignments of components to a simple structure. The mapping rule
dictates that the components a3are assigned to b1 and a1 to b3. The component a2 is ignored since there are no
identically named components in the target structure and b2 keeps its value. a4 and a5 in the target structure also
keep their values, however, even though the source structure contains identically named components. This is
because the value of CL_ABAP_CORRESPONDING=>MAPPING_EXCEPT_ALL is specified for the mapping type for all
non-specified components. The executable example for simple structures enables interactive input of the
component names that are mapped to each other.

DATA:
BEGIN OF struct1,
a1 TYPE string VALUE 'a1',
a2 TYPE string VALUE 'a2',
a3 TYPE string VALUE 'a3',
a4 TYPE string VALUE 'a4',
a5 TYPE string VALUE 'a5',
END OF struct1,
BEGIN OF struct2,
b1 TYPE string VALUE 'b1',
b2 TYPE string VALUE 'b2',
b3 TYPE string VALUE 'b3',
a4 TYPE string VALUE 'b4',
a5 TYPE string VALUE 'b5',
END OF struct2.

DATA(mapper) =
cl_abap_corresponding=>create(
source = struct1
destination = struct2
mapping = VALUE cl_abap_corresponding=>mapping_table(
( level = 0 kind = 1 srcname = 'a1' dstname = 'b3' )
( level = 0 kind = 1 srcname = 'a3' dstname = 'b1' )
( level = 0 kind = 3 ) ) ).

mapper->execute( EXPORTING source = struct1


CHANGING destination = struct2 ).
CATCH cx_corr_dyn_error INTO DATA(exc).
cl_demo_output=>display( exc->get_text( ) ).
ENDTRY.
cl_demo_output=>display( struct2 ).

16. Corresponding

Syntax
Basic Form

... { CORRESPONDING type( [DEEP] [BASE ( base )] struct|itab ) }


| { CORRESPONDING type( [BASE ( base )] struct|itab [ mapping] ) } ...

Lookup Table

... CORRESPONDING type( itab FROM lookup_tab


USING [KEY key_name] s1 = t1 s2 = t2 ...
[mapping] ) ...

17. REF Operator


The reference operator REF constructs a data reference at operand positions.

... REF dtype|#( dobj ) ...

results in a data reference pointing to dobj with the static type specified by type. With other
words, REF is the short form for GET REFERENCE OF dobj INTO.

Description Before 7.40 After 7.40


REF DATA: LT_RESULT TYPE TABLE OF VBAK, DATA: LT_RESULT TYPE TABLE OF VBAK.
Operator LR_RESULT TYPE REF TO DATA.
DATA(LR_RESULT) = REF #(LT_RESULT).
GET REFERENCE OF LT_RESULT INTO LR_RESULT.
18. LET expression

Syntax

... LET {var1 = rhs1}|{<fs1> = wrexpr1}


{var2 = rhs2}|{<fs2> = wrexpr2} ... IN ...

A LET expression defines variables var1, var2 ... or field symbols <fs1>, <fs2>, ... as local auxiliary fields in
an expression and assigned values to them.

When declared, the auxiliary fields can be used in the operand positions of the expression. There is no
way of accessing an auxiliary field statically outside its expression.

The documentation of an expression specifies whether it contains a LET expression and in which
positions. Any LET expressions in an expression or sub expression are evaluated first.

Example:

Reading table via Index


Internal Table DATES is filled
with 3 records.

Value of ISODATE is found


using LET expression.

OUTPUT:

19. Lossless Operator EXACT

The lossless operator EXACT is a constructor operator that executes either a lossless calculation or a
lossless assignment.

... EXACT dtype|#( arith_exp ) ...

arith_exp is an arithmetic expression that is calculated lossless with calculation type decfloat34 and the
result is converted to the specified type.
... EXACT dtype|#( arg ) ...

arg is not an arithmetic expression and its value is assigned to the result of the specified type according
to the rules for lossless assignments.

Lossless calculations

Lossless calculations were introduced for decimal floating point numbers in Release 7.02 with the
addition EXACT to COMPUTE. This addition (better the whole statement COMPUTE) became obsolete
now.

A lossless calculation must not perform any rounding. If it does, an exception occurs.

OUTPUT:

Lossless assignments
Lossless assignments were introduced for conversions in Release 7.02 with the addition EXACT to MOVE.
This addition (better the whole statement MOVE) became obsolete now.
A lossless assignment is an assignment where
 the value of the source is valid for its type
 there are no data losses during the assignment
 the converted value of the target is valid for its type

OUTPUT:

20. MESHES

The meshes are special structures whose components are internal tables, which can be linked to each other
using associations. Associations are evaluated by specifying mesh paths in suitable expressions and
statements.

Data Types for Meshes

Mesh types can be created using the following new variant of the TYPES statement:

TYPES BEGIN OF MESH


...
TYPES snode ... ASSOCIATION _assoc
TO tnode ON tcomp1 = scomp1 [AND ...].
...
TYPES END OF MESH

Meshes are instances of these types and can be used in suitable expressions and statements.

Processing Meshes

These relationships (defined using associations) between mesh nodes in a mesh can be evaluated in mesh
paths. These mesh paths can be used in the following expressions and statements:

 ... mesh_path ...

 LOOP AT mesh_path

 FOR ... IN mesh_path

 INSERT ... INTO ... mesh_path

 MODIFY ... mesh_path

 DELETE ... mesh_path

 SET ASSOCIATION mesh_path

EXAMPLE:

REPORT demo_mesh_expressions_flights.

CLASS demo DEFINITION.


PUBLIC SECTION.
CLASS-METHODS:
main,
class_constructor.
PRIVATE SECTION.
TYPES:
t_scarr TYPE HASHED TABLE OF scarr
WITH UNIQUE KEY carrid,
t_spfli TYPE HASHED TABLE OF spfli
WITH UNIQUE KEY carrid connid ,
t_sflight TYPE HASHED TABLE OF sflight
WITH UNIQUE KEY carrid connid fldate,
t_sairport TYPE HASHED TABLE OF sairport
WITH UNIQUE KEY id,

BEGIN OF MESH t_flights,


scarr TYPE t_scarr ASSOCIATION _spfli TO spfli
ON carrid = carrid,
spfli TYPE t_spfli ASSOCIATION _sflight TO sflight
ON carrid = carrid AND
connid = connid
ASSOCIATION _sairport TO sairport
ON id = airpfrom,
sflight TYPE t_sflight,
sairport TYPE t_sairport,
END OF MESH t_flights.
CLASS-DATA:
flights TYPE t_flights,
in TYPE REF TO if_demo_input,
out TYPE REF TO if_demo_output,
name TYPE scarr-carrname VALUE 'Lufthansa',
id TYPE spfli-carrid VALUE 'LH',
connection TYPE spfli-connid VALUE '0400',
date TYPE sflight-fldate.
CLASS-METHODS:
input.
ENDCLASS.

CLASS demo IMPLEMENTATION.


METHOD main.
input( ).

TRY.

out->begin_section(
'Forward Association scarr\_spfli' ).
DATA(spfli_wa) =
flights-scarr\_spfli[ flights-scarr[ carrname = name ]
connid = connection ].
out->write( spfli_wa ).

out->next_section(
'Inverse Association spfli\^_spfli~scarr' ).
DATA(scarr_wa) =
flights-spfli\^_spfli~scarr[
flights-spfli[ carrid = ID connid = CONNECTION ] ].
out->write( scarr_wa ).

out->next_section(
'Chained Association scarr\_spfli\_sflight' ).
DATA(sflight_wa) =
flights-scarr\_spfli[ flights-scarr[ carrname = name ]
connid = connection
]\_sflight[ fldate = date ].
out->write( sflight_wa ).

out->next_section(
'Addressing Component' ).
DATA(price) =
flights-scarr\_spfli[ flights-scarr[ carrname = name ]
connid = connection
]\_sflight[ fldate = date ]-price.
out->write( price ).

out->next_section(
'Assigning to Field Symbol' ).
ASSIGN
flights-scarr\_spfli[ flights-scarr[ carrname = NAME ]
connid = CONNECTION
]\_sflight[ fldate = DATE ]
TO FIELD-SYMBOL(<sflight_wa>).
IF sy-subrc = 0.
out->write( 'Field symbol OK' ).
ENDIF.

out->next_section(
'Write Access and Check Existence' ).
flights-scarr\_spfli[ flights-scarr[ carrname = NAME ]
connid = CONNECTION
]\_sflight[ fldate = DATE
]-price = price - 10.
IF line_exists(
flights-scarr\_spfli[ flights-scarr[ carrname = name ]
connid = connection
]\_sflight[ fldate = date
price = price - 10 ] ).
out->write( 'Line found!' ).
ENDIF.
CATCH cx_sy_itab_line_not_found.
out->write( 'Exception!' ).
ENDTRY.
out->display( ).
ENDMETHOD.
METHOD class_constructor.
in = cl_demo_input=>new( ).
out = cl_demo_output=>new( ).

SELECT *
FROM scarr
INTO TABLE @flights-scarr.
SELECT *
FROM spfli
INTO TABLE @flights-spfli.
SELECT *
FROM sflight
INTO TABLE @flights-sflight.
SELECT *
FROM sairport
INTO TABLE @flights-sairport.

ENDMETHOD.
METHOD input.
TRY.
date = flights-sflight[ carrid = id
connid = connection ]-fldate.
CATCH cx_sy_itab_line_not_found.
LEAVE PROGRAM.
ENDTRY.
in->add_field( CHANGING field = name
)->add_field( CHANGING field = connection
)->add_field( CHANGING field = id
)->add_field( CHANGING field = date
)->request( ).
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
demo=>main( ).
OUTPUT:
The following mesh paths are used as mesh path expressions:

 Mesh path with forward association as an initial association on the right side of an assignment. The source
in the square brackets is a table expression, plus a condition.

flights-scarr\_spfli[ flights-scarr[ carrname = name ]


connid = connection ]

 Mesh path with inverse association as an initial association on the right side of an assignment. The source
in the square brackets is a table expression.

flights-spfli\^_spfli~scarr[ flights-spfli[ carrid = ID


connid = CONNECTION ] ]

 Mesh path with path extension after the initial association on the right side of an assignment.

flights-scarr\_spfli[ flights-scarr[ carrname = name ]


connid = connection
]\_sflight[ fldate = date ]

The mesh path with path extension is also used to demonstrate the addressing of a component using the structure
component selector, assignments to a field symbol, reads, and usage in the predicate function line_exists.

21. Open SQL in Release 7.40

Comma-Separated Lists

In Open SQL, all operands in lists can now be separated by commas and this is also the recommended
way of separating them from Release 7.40, SP05.

Comma-separated lists are now also possible in Unicode programs where the program attribute fixed
point arithmetic is activated:
This makes blank-separated lists obsolete.

SQL Expressions

From Release 7.40, SP05, SQL expressions can be specified in a comma-separated SELECT list.

The result of an expression of this type (whose operands can be the names of columns or host variables)
is determined by the database system and passed to the application server in the appropriate column of
the results set.

EXAMPLE:

REPORT demo_sql_expr_arith.

CLASS demo DEFINITION.


PUBLIC SECTION.
CLASS-METHODS main.
ENDCLASS.

CLASS demo IMPLEMENTATION.


METHOD main.
DATA wa TYPE demo_expressions.

DELETE FROM demo_expressions.


DATA(rnd) = cl_abap_random_int=>create(
seed = CONV i( sy-uzeit ) min = 1 max = 100 ).
DO 10 TIMES.
wa-id = |{ sy-index - 1 }|.
wa-num1 = rnd->get_next( ).
wa-num2 = rnd->get_next( ).
INSERT demo_expressions FROM @wa.
ENDDO.
DATA(offset) = 10000.
SELECT id, num1, num2,
cast( num1 AS fltp ) / cast( num2 AS fltp ) AS ratio,
div( num1, num2 ) AS div,
mod( num1, num2 ) AS mod,
@offset + abs( num1 - num2 ) AS sum
FROM demo_expressions
ORDER BY SUM DESCENDING
INTO TABLE @DATA(results).

cl_demo_output=>display( results ).
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
demo=>main( ).

OUTPUT:

Syntax for coalesce

... coalesce( arg1, arg2 ) ...

The coalesce function in Open SQL returns the value of the argument arg1 (if this is not the null value);
otherwise it returns the value of the argument arg2.

EXAMPLE:

REPORT demo_sql_expr_coalesce NO STANDARD PAGE HEADING.

CLASS demo DEFINITION.


PUBLIC SECTION.
CLASS-METHODS: class_constructor,
main.
PRIVATE SECTION.
CLASS-DATA: wa1 TYPE demo_join1,
wa2 TYPE demo_join2,
out TYPE REF TO if_demo_output.
CLASS-DATA BEGIN OF wa.
INCLUDE STRUCTURE wa1 AS wa1 RENAMING WITH SUFFIX 1.
INCLUDE STRUCTURE wa2 AS wa2 RENAMING WITH SUFFIX 2.
CLASS-DATA END OF wa.
ENDCLASS.

CLASS demo IMPLEMENTATION.


METHOD main.
DATA itab LIKE TABLE OF wa WITH EMPTY KEY.
out = cl_demo_output=>new(
)->begin_section( `OUTER JOIN with Coalesce` ).
SELECT t1~a AS a1, t1~b as b1, t1~c AS c1, t1~d as d1,
coalesce( t2~d, '--' ) AS d2,
coalesce( t2~e, '--' ) as e2,
coalesce( t2~f, '--' ) AS f2,
coalesce( t2~g, '--' ) as g2,
coalesce( t2~h, '--' ) AS h2
FROM demo_join1 AS t1
LEFT OUTER JOIN demo_join2 AS t2 ON t2~d = t1~d
ORDER BY t1~d
INTO CORRESPONDING FIELDS OF TABLE @itab.
out->display( itab ).
ENDMETHOD.
METHOD class_constructor.
DATA: itab1 LIKE TABLE OF wa1,
itab2 LIKE TABLE OF wa2.
itab1 = VALUE #( ( a = 'a1' b = 'b1' c = 'c1' d = 'uu' )
( a = 'a2' b = 'b2' c = 'c2' d = 'uu' )
( a = 'a3' b = 'b3' c = 'c3' d = 'vv' )
( a = 'a4' b = 'b4' c = 'c4' d = 'ww' )
).
itab2 = VALUE #( ( d = 'uu' e = 'e1' f = 'f1' g = 'g1' h = 'h1' )
( d = 'ww' e = 'e2' f = 'f2' g = 'g2' h = 'h2' )
( d = 'xx' e = 'e3' f = 'f3' g = 'g3' h = 'h3' )
).
DELETE FROM demo_join1.
INSERT demo_join1 FROM TABLE @itab1.
DELETE FROM demo_join2.
INSERT demo_join2 FROM TABLE @itab2.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
demo=>main( ).

OUTPUT:
Switching Automatic Client Handling
The new addition USING CLIENT clnt switches automatic client handling to the client specified in clnt.
It can be specified in all Open SQL statements as an alternative to CLIENT SPECIFIED.

Rule Changes for Joins


 From Release 7.40, SP05, it is no longer the case that all comparisons of the ON condition must
contain a column from a database table or view on the right side as an operand.

 From Release 7.40, SP05, the right side of a join expression is no longer restricted to single
tables or views. The right side can itself be a (parenthesized) join expression whose results set is
then evaluated.

 In Release 7.40, SP05 and higher, LEFT OUTER JOIN and RIGHT OUTER JOIN can be used., ,

 From Release 7.40, SP05, fields from the right side in the WHERE condition of the
current SELECT statement can be specified in LEFT OUTER JOIN. Fields from the left side can be
specified in RIGHT OUTER JOIN.

Evaluating INTO CORRESPONDING

If all required components are statically identifiable, the assignment of the fields in the
addition CORRESPONDING after INTO is now determined when the program is generated and is not
delayed until runtime.

The addition INTO CORRESPONDING now affects the results set defined in the SELECT list. If one or more
names match, all the columns for which there are no name matches are removed from the results set. If
there are no name matches, none of the columns are removed from the results set.

Access to CDS Views


SELECT can be used to access CDS views, which have been defined with the DDL of the ABAP CDS by
using DEFINE VIEW.

Examples

SELECT id, num1, num2,


cast( num1 AS fltp ) / cast( num2 AS fltp ) AS ratio,
div( num1, num2 ) AS div,
mod( num1, num2 ) AS mod,
@offset + abs( num1 - num2 ) AS sum
FROM demo_expressions
INTO CORRESPONDING FIELDS OF TABLE @results
ORDER BY SUM DESCENDING.

SELECT id, CASE char1


WHEN 'aaaaa' THEN ( char1 && char2 )
WHEN 'xxxxx' THEN ( char2 && char1 )
ELSE @else
END AS text
FROM demo_expressions
INTO CORRESPONDING FIELDS OF TABLE @results.

You might also like