CDS tutorial and interview questions
SAP CDS
Part#1. SAP CDS views Demystification
Introduction:
CDS stands for Core Data Services. This is the new programming paradigm within new SAP environment specifically S/4HANA systems. CDS views can be created without HANA DB as well but I will focus on an S/4 system with a HANA DB as that is the future road map of SAP .
HANA is an in-memory database which enables high speed data processing. With this awesome feature, SAP has tried to put all the logic calculations back into the database instead of the application server as it was done prior to HANA. So CDS views are the new programming design concepts which can achieve Code-to-Data paradigm which actually means Code push down into the database for processing. CDS is an enhancement to standard SQL technology which runs within ABAP layer which means that the design time objects are created in the ABAP layer and can be transported by regular Transport mechanism with a TR number assigned to each object. The Design Time object is created in database i.e. the HANA DB which enables Code-to-Data shift.
As I mentioned, CDS is an enhancement to standard SQL language, it has all SQL features as below;
- DDL – Data Definition Language. Used to CREATE Table, MODIFY Table etc.
- DQL – Data Query Language. Used to READ data.
- DCL – Data Control Language. Used to configure ‘SECURITY’
- Expression Language – Mathematical calculations, conditions Case..Endcase etc.
Part#2. Create a Basic CDS view
Whenver a CDS view is created and activated, these 2 objects gets generated. As I mentioned in the introduction, this enables Code-to-Data paradigm shift.
- DDIC SQL view – It is a Design Time Object and can be seen in tcode- SE11
- HANA View – It is a run time object and gets created in HANA DB
BASIC CDS VIEW:
For all the view I create, I will use FLIGHT demo tables and data to showcase the CDS technology.
- Create an ABAP project within Eclipse by logging in to S4 HANA system.
- Right click on your username under Local Objects and choose New->Other ABAP Repository Objects. Core Data Services->Data Definition.
A simple view will be created. All the statements starting with ‘@’ at the start of the view are called ‘ANNOTATIONS’ and they play a very important role in design and development of the CDS view. They are the ‘Building Blocks’ behind the CDS views configuration. They also define how the CDS view will behave in different scenarios. I will talk about different kind and mostly used annotations.
Now let’s talk about the default annotations while creating the Basic view
- @AbapCatalog.sqlViewName: ‘sql_view_name’.
Within first annotation, provide the SQL view name. This is the DDIC SQL view which gets generated once the CDS view is activated and can be seen in tcode SE11. This name must be of less than or equal to 16 characters as per DDIC SE11 view name limitations. Also, the CDS view name and the SQL view name can NOT be same. So choose a logical name, probably something similar to the CDS view name to keep it consistent.
- @AbapCatalog.compiler.compareFilter: true:
This annotation defines the behavior of the filtering the data i.e. this first compare the filter conditions and if they match then only the data is fetched. If the CDS view has join conditions, they are executed only after the filter conditions are matched. In DDIC views data if first fetched and then filtered.
- @AbapCatalog.preserveKey: true
Another important annotation of CDS views. As you know all the DB tables in SAP do have Keys defined and the CDS Views are always created on top of those DB tables. Now any DB table can have multiple keys defined and you might not want those keys to be the key fields of your view. So if you set this annotation as true, the only fields you define as Key Fields within your CDS view by adding word ‘Key’ in front of those fields will be the Key fields for the CDS view and the DDIC SQL view which gets generated.
If you set this as ‘False’ the DB table key fields will be defined as Key fields for the views as well, regardless of you adding word ‘Key’ in front of fewer fields.
- @AccessControl.authorizationCheck: #NOT_REQUIRED
This annotation is used to add ‘Security’ piece to the CDS view. When CDS view is ready to be rolled out to a bigger audience within or outside the organization, it is very important to restrict the data based on the authority. We will look into creation of authorization objects in the later part. For now let’s keep it #NOT_REQUIRED
- @EndUserText.label: ‘CDS View type #BASIC’
This annotation is used to apply business labels other than labels attached in the DB tables, to the fields within the CDS view. This annotation will override the DB table business label and provides what you specify with this annotation.
Let’s add the fields to the CDS view by right click. You can either choose to insert all fields or one by one;
Add the below fields to the CDS view;
I made the field ‘Client’ or ‘MANDT’ disabled due to the reason that this CDS view is created in the ABAP system and the client is handled by the system itself. Now activate the CDS view.
As mentioned before, 2 more objects get created when the CDS view is activated? A DDIC SQL view is created and a HANA view is created;
-Goto Tcode SE11 and check the DDIC SQL view;
-Check the HANA view in Eclipse or HANA Studio platform as below;
You can also check the ‘CREATE’ statement generated by the system.
To summarize, we created a basic CDS view and looked at the default annotations which are already configured when a CDS view is created. Also, we saw the different run time and design time objects which gets created with the view activation.
Part#3. CDS View with Expressions and Session Variables
This is the 3rd blog post on the CDS detailed explanations after the Introduction post. Refer to the Introduction and blog post indexes here:
https://blogs.sap.com/2019/10/21/part1.-sap-cds-views-demystification/
As you saw in the previous blog post, in the Basic CDS view the data has been read with a simple ‘Select’ statement. So how about some business logic calculations? Can we have some Mathematical Expressions configured in the CDS view? Yes, absolutely, let’s create a simple CDS view with an Expression to calculate the available seats in business class from table SFLIGHT;
Check the output below. Column Seats_Avlbl is the result of a mathematical expression configured within CDS view.
=> ‘WHERE’ CLAUSE AND SESSION VARIABLES:
Let’s check how to add a ‘WHERE’ clause to filter the data and how to make use of ‘Session Variables’. Similar to ABAP session variables like sy-datum for current Date, sy-uzeit for current Time etc. , CDS views editor also has session variables which can provide these values. See below the syntax for Client, system_date, system_language, user can be determined within ‘WHERE ‘ clause.
Select ‘system_date’ to compare ‘Current Date’ with Flight Date.
@AbapCatalog.sqlViewName: 'ZSQL_VIEW_EXPRSN'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'CDS view with Expression'
define view ZCDS_VIEW_EXPRESSION as select from sflight
{
key carrid,
connid,
seatsmax_b,
seatsocc_b,
fldate,
(seatsmax_b - seatsocc_b) as Seats_Avlbl
}
where fldate <= $session.system_date
In summary, we saw how to add Expressions, Where Clause to the CDS view and how to use Session variables to get some system data.
Part#4. Consume CDS View in an ABAP Program
CDS view is also called a VDM i.e. Virtual Data Model as there is no data persistence happening. All the SQL like code written in a CDS view pick the data from Base tables directly or via other CDS view at RUNTIME . The actual data still remain in the SAP Base tables and CDS views remains a virtual data model. Now in a scenario, we have created a complex CDS view which has lot of business logic implemented into it and we want to use the data coming out of this CDS view in an ABAP program, can this be possible? Yes, it is possible via new ABAP syntax. Let’s look at it.
1. We will use the Basic CDS view we created before to be consumed via ABAP program;
@AbapCatalog.sqlViewName: 'ZSQL_BASIC_VIEW'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'CDS View type #BASIC'
define view ZCDS_BASIC_VIEW as select from sflight {
//sflight
--key mandt,
key carrid,
seatsmax_b,
seatsocc_b,
seatsmax_f,
seatsocc_f
}
2. Within ABAP perspective in Eclise or HANA Studio, right click on your user under Lcal Objects within an ABAP project to create an AABAP program
- Consume the CDS Basic view we created via this ABAP program. Note the new ABAP syntax used for this purpose.
*&---------------------------------------------------------------------*
*& Report zconsume_cds
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zconsume_cds.
Select * from ZCDS_BASIC_VIEW into table @data(lt_itab).
cl_demo_output=>display_data( lt_itab ).
2. Hit F8 or Execute the program to check the output.
In summary, there are lot of scenarios in projects where we write complex CDS views and we need to consume them into an ABAP program for different business needs. In this blog post, we looked at the new ABAP syntax to consume a CDS view.
Part#5. CDS View Extension
SAP provides multiple standard CDS view related to each functional module and also during a project implementation you will create tons of CDS custom views. Since the CDS views are just virtual data models, you will want to reuse the view created in one project or for one object to another project/object. Let’s assume you created a CDS view with 5 fields on TABLE A and for another scenario in a different project you need 8 fields from the same TABLE A. So instead of creating new CDS view from scratch, we can use the concept of CDS View extension and re-use the previous view we created and extend it with 3 new fields.
- Create a CDS view with Template ‘Extend View’
Below is the default view generated;
Now add the SQL view name and other properties;
- SQL View name: ZSQL_EXTEND_VIEW
- Let’s extend the view we created before: ZCDS_BASIC_VIEW. This could be a standard view as well. Any view which you would like to extend with new fields.
- Hit CTRL + SPACE to see the fields which you would like to extend with. This will use the datasource/table used in the view we are extending i.e. table SFLIGHT in our case.
Add the fields you would like to extend and ‘Activate’ the view.
Hit F8 and check the output. You can see that the 3 new fields are available in this view together with all other fields of the view we extended;
Hit F8 and check the output. You can see that the 3 new fields are available in this view together with all other fields of the view we extended;
In summary, we looked at the re-usability concept in this blog post, which is very important to reduce the development effort and to follow the Best SAP Practices as well. Instead of creating from scratch, it is highly important to know about SAP delivered standard CDS views to re-use them in your project to meet specific business requirements.
Part#6. Parameters in a CDS view
In the previous blog post, we saw simple examples of CDS views which are a type of a select statement and you could surely add ‘WHERE’ clause to filter the data. But this where clause is static with a non-parameterized view and may not fulfill the project requirements where a user interaction is required. So it is absolutely possible to add ‘Parameters’ to take user input and filter out the data from the CDS view accordingly;
- Create a new CDS view;
You can choose the parameter template for easy code;
This is what we get as the default structure of the CDS view with Parameters. Look at the ‘with parameters’ clause got added.
2. Add the SQL view name and table name. To the ‘with parameters’ clause, add the parameter name before colon and the data type after colon as mentioned above. For ‘Data Type’ you can either add the data element directly as we used to do in classic ABAP to declare a variable i.e. or you can add primitive data type like abap.<data ype>(<len>) e.g.: char(3) ;
Data Element – S_CURRCODE;
ABAP Premitive types – abap.char(3);
To use the parameters to filter out the data we need to apply a ‘WHERE’ clause and use the parameter with $Paramter keyword i.e. $Parameter.<parameter name> OR just the parameter name prefixed with a colon i.e. :<parameter name> . Let’s check how the CDS view look like now;
OR
- Active the CDS view now and hit F8 to execute. Checkout the user input pop up to enter the currency code as we configured in the CDS view;
- Add ‘AUD’ for Australian Dollar and hit ‘OK’. Check the output ?
- Now lets see how we can consume this CDS view with parameters in our ABAP program. What new code we need to write and how the parameters behave;
Create a new ABAP program ZCONSUME_CDS_PARAM and add code as below
*&---------------------------------------------------------------------*
*& Report zconsume_cds_param
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zconsume_cds_param.
data: lv_curr type S_CURRCODE.
cl_demo_input=>new( )->add_field( changing field = lv_curr )->request( ).
select * from ZCDS_VIEW_PARAM( in_curr = @lv_curr ) into table @data(lt_tab).
cl_demo_output=>display( lt_tab ).
The ‘Enter’ button here is automatic, we don’t need to write any code for this. Enter the currency value and hit Enter;
To summarize, in live projects 95% of analytics needs selection screens to get user input. This is also very important to reduce the amount of data hit by the CDS view which subsequently improves the CDS view performance to fetch only the required data out. In this blog post, we saw how to use the parameters to get the user input and fetch only the data needed for analytics.
Part#7. How to search for SAP standard CDS Views
SAP has delivered standard CDS views to create S4 Real Time Analytics and this is also called S4 or S4HANA Embedded Analytics. For attention of BW consultant, it is kind of similar to SAP standard BW content which is delivered by SAP for each module and can be leveraged to create complex analytics. As we can enhance the standard BW content to meet specific business needs, in similar manner SAP standard CDS views can also be enhanced or consumed to meet business requirements. Now the question is ‘How I can find this standard SAP content of delivered out of the box CDS views?’ ‘How would I know a CDS view is already delivered by SAP which has all the required fields OR there are couple of views which together have all the required fields to create this analytics for business and there is no need to create any CDS view from scratch’? So there are 2 best ways of looking for the SAP standard content, let’s look at them;
- The best and preferred way is SAP Help portal. Follow this;
- Go to: https://help.sap.com/viewer/product/SAP_S4HANA_ON-PREMISE/1909.000/en-US
- Open Product Assistance information;
- Follow this path;
- Under CDS Views, you can find information of all the SAP standard CDS views categorized in separate function modules OR Business Functions with all the related information of that view;
- Check out any one;
2. Another way which I also rely on is the ‘Query Browser’ app on ‘Fiori Launchpad’. Login to the Fiori launchpad to find the app. If you can not see this app, make sure you have this role assigned to your user: SAP_BR_EMPLOYEE. Search for ‘Query Browser’;
You must see this page on the ‘Query Browser’ app and this is the place to look for standard CDS views for different SAP functional modules.
in summary, we must not re-invent the wheel. It is very important to know about standard SAP delivered CDS view content and re-utilize it. So whatever business module you are working on, with the help of this blog post, you can find out the standard delivered content and utilize the views already developed by SAP. This drastically reduce the development effort and and business users will be happy to get the analytical reports faster than they expect.
Part#8. CDS Views – Joins and Associations
In the previous blog posts, you could see that the CDS views are an enhancement of SQL and at real time projects, we need to join multiple table together to convert data into a meaningful information. Let’ see how it works with CDS views.
JOINS: We can use below different type of Joins within CDS view;
- Inner Join
- Left Outer join
- Right outer join
I will not talk about all the joins, they behave exactly similar way as in simple SQL concepts. Let’s see an example of Inner Join code for syntax purose;
- Create a new CDS view with ‘JOIN’ template
Add the necessary components to complete the view. Join tables SFLIGHT and SPFLI. Add airport information from table SPFLI.
- Activate and execute the view to see the data;
We saw that how a CDS view fetched data from 2 tables with the help of a Join. Now let’s think about why are we creating these CDS views? What is the purpose?
CDS view are not directly accessed by the business users rather they will be consumed by either ABAP program, Fiori apps or BI front end tools. If you have created a CDS view with JOINS on 5 different tables then this JOIN conditions will be executed every time this CDS view is triggered. Even though the business user is looking at only fields from 2 tables but the CDS view will first run the Join conditions of all 5 tables and it doesn’t matter how many fields user is looking at. This is the SQL concept with Joins but results in delayed performance to fetch the data out of CDS view in case of user looking at just the partial data. To overcome this problem, SAP did an enhancement to this SQL way of getting data and beautifully developed the concept of ‘ASSOCIATIONS’. With Associations, data will be fetched only when user want to see it. Let’s see how it works;
ASSOCIATIONS:
ASSOCIATIONS are kind of Joins to fetch data from multiple tables on Join Conditions but these are ‘JOINS ON-DEMAND’ i.e. they will only be triggered when user would access the required data which needs the Association of tables. For example, your CDS view has 4 Associations configured and user is fetching data for only 2 tables, the ASSOICATION on other 2 tables will not be triggered and the system would return the results quickly, so it enables really high turn-around time as compared to regular SQL JOINS.
Associations are defined with ‘Cardinality’. Syntax : association[<cardinality>]
Cardinality concept is not new and holds the same concept with CDS views as well. There are 4 types of Cardinality possible based on the data and relationship in the tables joined;
- 0..1
- 0..n or 0..*
- 1..0
- 1..n or 1..*
NOTE: If you are confused on what kind of association I should configure in my CDS view then you can apply a rule of thumb: ‘always use this : association[1]. This will always trigger an OUTER join and will work in all the cases.
Let’s create a CDS view with ASSOCIATION concept.
- Create View with Association template;
- Below is the default structure you will get. As you can see the association cardinality is defined as ‘Association[1]’. You can keep it as it is, if you are not sure what association you have to assign.
- Check the default Association name as _association_name. This can be any name of your choice but SAP has created a naming convention standard to start this name with an underscore(_) and it is always good to follow SAP standard best practices.
- Add the required data elements to complete the view. Lets take the same example we did with JOIN view.
-EXPOSED Association
Right click and select ‘Show SQL CREATE Statement;
As you can see, NO Join is created;
- We can add separate fields in the CDS view as well like a join and that is called Ad-Hoc Association Concept. In this scenario a join will be performed beforehand.
-AD-HOC Association:
Check the SQL CREATE statement. Note that a ‘LEFT OUTER MANY TO ONE JOIN’ is created. The join created because we selected individual fields instead of exposing the whole Association and it is LEFT OUTER MANY TO ONE i.e. *..1 due to the fact that we configured cardinality like ASSOCIATION[1].
As we saw above the ASSOCIATION concept with EXPOSED and AD-HOC Associations. Now lets activate the view with Exposed Association and see how it performs a join at RUN Time.
Activate this view and hit F8 to execute;
Execute and look at highlighted – CDS View name and CARRID data AA and AZ. Also note that NO data from table SPFLI is displayed as NO join is yet performed.
Now if you want to see further Airport information for CARRID ‘AA’ from table SPFLI. right click on any row with CARRID ‘AA’ and choose ‘Follow Association’. Another pop-up window will opn, click the Association type;
Check data: Join is now performed ON-DEMAND and data only for CARRID ‘AA’ is displayed based on Association Key.
In summary, Association concept is one of the wonderful things I liked about CDS views. So intelligently, SAP developed this to save the effort in reading only the information which is required for the analytics purpose. You can feel the real difference after designing a very complex CDS view with a combination of multiple table and other CDS views. The very complex CDS view still performance great when Associations are used. In this blog post, we saw the Association concept together with Exposed and Ad-Hoc associations.
Part#9. CDS View – OData Service : Publishing to the outer world
PUBLISHING CDS View to the Outer World over internet with OData Service and consume via FIORI app.
It is very easy to publish a CDS view with OData Service. To do it we just have to use one annotation ‘@OData.publish: true’ which will further create an OData Service and we must register it within SAP system via GUI interface. Once registered, CDS view is ready to be consumed in any application within or outside SAP environment. We will look at how we can consume it in a simple Master-Details CDS view app.
Let’s create a new view with tables ‘VBAK – Sales Header’ and VBAP – Sales Items’. We will use the concept of ‘Association’ again.
Create the CDS view as below and activate. You can choose any tables of your choice.
- Now add the OData annotation and activate again
- Hover over the mouse pointer on the yellow icon showed up in front of @OData annotation. It will show the service name which gets created and indicates that service is not yet active. Copy the service name to register and activate. This is a mandatory one-time activity we need to perform so that our CDS view can be published with OData. Notice that the service name generated by the system is almost like your CDS view name with _CDS
- Login to SAP GUI interface to register the service. You can hot CTRL+6 to login within ADT or login separately via SAP Logon pad.
- Goto tcode /n/IWFND/MAINT_SERVICE and clock ‘Add Service’ button.
- Choose ‘LOCAL’ as System Alias and pass the service name we copied from CDS view to ‘External Service Name’. Hit Enter. Select the Service and click ‘Add Selected Services’.
- Now pass the ‘package’ to transport OR select ‘Local’ if no transport is required. Hit ‘Continue’;
- Service is now created.
->To check if Service is registered, Go back screen and filter it.
->Select the Service and click on Call Browser;
->A browser window will open and you have to enter your SAP credentials( uname/pwd ). You can see the service code. Note the CDS View/Entity name and the Asslciation Table name ‘VBAP’ also appears.
-> To check if OData service returns the data, copy the CDS view name and add it to the link in the browser.
FROM:
TO:
Note that the data displayed is only from table VBAK – Sales Header. NO Join is yet performed and NO data from table VBAP – Sales Item is displayed yet. Check the highlighted link in blue, this is the link to the table VBAP to display data On-Demand as we have applied the concept of ‘ASSOCIATIONS’ within the CDS view. Copy and paste this link in the browser window by replacing it with the CDS view name as below;
-Replace <IP address> with you IP in below URLs
To:
Check that the data from Sales Item table VBAP is now displayed;
- CDS view and OData Service is now ready and next we will plug this in to a FIORI app and we need to do a little configuration via SAP Web IDE. SAP Web IDE personal edition is free from SAP, you can download from here: https://tools.hana.ondemand.com/#sapui5 and unzip the file on your machine. It will create an eclipse folder.
- Launch SAP Web IDE;
- Go to eclipse folder and double click ‘Orion.exe’ file to start the Web IDE server.
- Once started, go to web browser and launch : http://localhost:8080/webide/index.html
- Right click on Workspace->New->Project from Template
- Click on ‘SAP Fiori Master-Detail Application and hit ‘Next’
- Enter necessary information and hit ‘Next’;
- Choose your S/4 system and system might ask uname/pwd if you are logging in first time. Check that all the OData services are displayed.
NOTE: If your S4 system is not available as you can see above, you have to configure the destination file if you have not done yet. Follow these steps;
- Go to this path in your SAP Web IDE folder;
C:\SAP Web IDE\eclipse\config_master\service.destinations\destinations
- Maintain the system file with below config;
Name=S4D
Type=HTTP
Description=S4D – AWS1809
URL=http://<IP address>:8080
ProxyType=Internet
Authentication=NoAuthentication
WebIDEUsage=odata_abap,odata_gen,ui5_execute_abap,dev_abap
WebIDESystem=S4D
WebIDEEnabled=true
TrustAll=true
sap-client=600
- Next to URL: you can either use IP or the system name. Make sure the port is correct too, it could be different in your system.
- Make sure this file has no extension. You can check like this:
If you see any extension, delete it and save. So after selecting the S/4 system, you can select the CDS View OData service form the list and take it from here to create Fiori App.
The CDS view now is available to feed the data to the Fiori App. We will see another end to end example in a separate blog post to plug CDS into FIORI app.
In summary, FIORI is the new web way of working with SAP systems via ‘apps’. All the Operational or Analytical reports will be configured into FIORI screens as apps, to be triggered with a click. In this blog post, we saw what all we need to integrate a CDS view into FIORI framework and how to resolve issues during integration.
Part#10. CDS Views – @VDM Annotation
Before we start developing any CDS view, it is highly important to understand the purpose of it. Why it is being created? Who and where this CDS view is going to be consumed – Is it for Analytics tools? Is it for FIORI app? Is it just to be consumed by other CDS views? Once we understand all these elements, it would help to standardize the view development and that’s when we can define the specific Annotations within the view. We must apply the annotations which make sense to the CDS view. Though adding annotations which are not required may not impact anything but would surely make it confusing when other developers or project support team will deal with those views.
At a glance below type of Annotations are used while configuring CDS views;
-@OData, @UI – Used for FIORI applications.
-@Analytics – Used to consume CDS view into Analytical tools like Bex, Lumira, Webi, Analysis for Office.
-@ObjectModel – Used for Transactional applications using BOPF
-@Semantics – Used for S4HANA Embedded Analytics
You can find detailed information on all type of Annotations here; https://help.sap.com/viewer/cc0c305d2fab47bd808adcad3ca7ee9d/7.5.9/en-US/630ce9b386b84e80bfade96779fbaeec.html
@VDM:
To standardize the CDS view technical development, SAP came up with the Best Practices with @VDM annotation. This is to standardize the development process and if religiously followed in the organization, it will very easy to maintain these technical artifacts with no issues and confusions. Looking at this annotations, one can figure out everything about the CDS view. This annotation has absolutely NO impact on the behavior or output of the CDS view rather it just show below features;
- What kind of data the CDS view expose.
- What is the category of the CDS view.
@VDM annotation is further broken down into the type of views. There are 4 type of CDS views can be developed;
-BASIC
Basic CDS views are developed to expose the Master Data like Customer Master, Material MAster, Business Partner etc. They consume the physical SAP tables to read data. They are also called INTERFACE views and for naming standards SAP use ‘I’ in between of the view name : *_I_*
-COMPOSITE:
These views are configures as an Association of Master data sets OR Master data and Transactional data. They can consume Basic Views or other Composite views to read data. For naming standards, SAP use ‘CO’ in between of the view name: *_CO_*
-CONSUMPTION
These views are created as the last layer of CDS analytical Model. These are the final views ready for consumption by the UI tools – Bex, Lumira, Webi, Analysis for Office etc. to be accessed by business users in the from of a report. These views can consume all other Basic or Composite Views to read data and create a final data set to be fed into the UI tools for reports based on business requirements. For naming standards, SAP start the view name with ‘C’: C_*
-PRIVATE
These views are private to SAP and must not be Used or Created by anyone other than SAP. SAP can change their configuration without any notice to the customers. For naming standards, SAP start the view name with ‘P’: P_*
NOTE: When you look at the SAP standard views, now with above naming standards how easy it is to identify the purpose and behavior of each of the view. You can easily know in which bucket the view fall into and how you can use it in your data model.
We can not use VDM annotations with Non S4HANA systems. This needs HANA DB as a pre-requisite.
With @VDM annotation, if you apply all the standard procedures in the CDS view creation, It will be fairly easy for other developers who will see you code to understand the nature and purpose of the CDS view you have created. This is one of the very important annotation for Quality Control and must be forced in an organization to achieve the Best Development Practices/Standards.
- Let’s create a VDM based CDS view to showcase how this looks;
- Create a new view with ASSOCIATION template.
- Copy the code from our previous Association view to save time.
3. Add the VDM and Analytics annotations;
@VDM:{viewType: #BASIC} :
This annotation defines the type of the CDS view. As mentioned above the type BASIC view are mostly used for Master Data and denotes that it is a BASIC Interface CDS view.
@Analytics:{dataExtraction:{enabled: true}, dataCategory: #DIMENSION}
This annotation defines if this CDS view is consumable by the Analytical applications. For attention of BW folks, we can create a custom datasource out of a CDS view by using this annotation. I will explain this in detail later. This annotations tells that we can extract data out of ECC system to BW for example and the Data Category ‘DIMENSION’ defines that it is a Dimension data which could be a Master data set and later this can be combined with the Fact Table or CDS view type #CUBE.
Activate and execute this CDS view. There will be no difference you can see in the output with or without VDM or Analytics annotations. While we will configure BW Data Source from a CDS view then it will be very helpful.
In summary, before starting to develop any CDS view, we must understand the whole life cycle of the data this view is going to deliver. It is a must to understand who is the consumer of this data coming out of this CDS view and then use the required annotations accordingly. Follow best SAP development practices and make the code look clean, easy to understand and best in performance.
Part#11.End to End Data Modeling and Reporting with CDS views
Let’s create a very simple data model on SAP’s demo data with FLIGHT module, just to showcase how an end to end business scenarios might look like. To create any analytics data model we need DIMENSION Data which are the Master Data sets and FACT data which is a Transaction Data Set. Below are the related tables, 3 Dimension/Master tables and 1 Fact table.
Dimension Tables:
- SCUSTOM for Customer information.
- SCARR for Airline information
- SPFLI for Connection information.
Fact Table:
- SBOOK : Flight Bookings information
NOTE: For Time Dimension we can use SAP standard Basic Interface view I_CalendarDate and for Country and Country text we can use I_Country.
- Create the first view for Airline information : ZCDS_VIEW_AIRLN
CDS View:
Note these annotations;
@VDM:{viewType: #BASIC} : As already mentioned, this annotation tells that this is a Basic Interface view which delivers Master Data – Airline Information in this scenario.
@Semantics.currencyCode: true – This annotation tells system that field ‘currcode’ is treated as Currency field.
@Analytics: dataCategory: #DIMENSION – shows this is Dimension data.
Output:
2. Create second view for Connection information: ZCDS_VIEW_CONN
Note: Check the keyword $Projection. Instead of source table name or alias, we can use $Projection as well which will take care of Association. The thing to note is with $Project, you can only use the fields which you have listed in the CDS view i.e. if the table has 20 fields but in your CDS view you want only 5 fields and you have listed them in the view, you can use only one of these 5 fields with $Projection. You are free to use table name or alias, this is just what SAP is using for standard views and comes under best practices.
Output: check the output and association;
3. Create a view for Customer information : ZCDS_VIEW_CUST
Output: check the Association jump to Country and Country Text via standard view I_Country.
4. Create a COMPOSITE view to combine all the Dimension views created above with Transaction or Fact data.
@AbapCatalog.sqlViewName: 'ZSQL_VIEW_FLBOOK'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Flight Booking Information'
@VDM : {viewType: #COMPOSITE}
@Analytics: {dataCategory: #CUBE, dataExtraction: {enabled: true}}
define view ZCDS_VIEW_FLBOOK as select from sbook
association [1] to I_CalendarDate as _CalendarDate on $projection.FlightDate = _CalendarDate.CalendarDate
association [1] to ZCDS_VIEW_AIRLINE as _Airline on $projection.Airline = _Airline.Airline
association [1] to zcds_view_conn as _Connection on $projection.Airline = _Connection.Airline
and $projection.FlightConnection = _Connection.FlConnectNumber
association [1] to ZCDS_VIEW_CUST as _Customer on $projection.Customer = _Customer.Customer
{
/** DIMENSIONS **/
key carrid as Airline,
key connid as FlightConnection,
key fldate as FlightDate,
key bookid as BookNumber,
key customid as Customer,
key agencynum as TravelAgency,
_CalendarDate.CalendarYear,
_CalendarDate.CalendarMonth,
_Customer.country as CustomerCountry,
_Customer.city as CustomerCity,
/** MEASURES **/
@EndUserText.label: 'Booking Price'
@DefaultAggregation: #SUM
@Semantics.amount.currencyCode: 'Currency'
forcuram as BookingPrice,
@EndUserText.label: 'Currency'
@Semantics.currencyCode: true
forcurkey as Currency,
@EndUserText.label: 'Luggage Weight'
@DefaultAggregation: #SUM
@Semantics.quantity.unitOfMeasure: 'WeightUOM'
luggweight as WeightOfLuggage,
@EndUserText.label: 'Weight Unit'
@Semantics.unitOfMeasure: true
wunit as WeightUOM,
// Associations
_Airline,
_CalendarDate,
_CalendarDate._CalendarMonth,
_CalendarDate._CalendarYear,
_Connection,
_Customer,
_Customer._Country as _CustomerCountry
}
Look at the few annotations used above;
@VDM : {viewType: #COMPOSITE}
This annotation describes that this is a COMPOSITE view which is an association of Master data and Transaction data. This is an SAP Best Practice to configure this annotation to follow the development standards.
@Analytics: dataCategory: #CUBE
In the above CDS view the dataCategory annotation is set to #CUBE which would define this CDS view as a data Cube. All other Dimension table are associated with this cube to built the final Reports. On thing to note is once a CDS view is created as #CUBE, no Dimension view can consume it. Only views which can consume a Cube view should be of type cube themselves. Only CDS view of type CUBE can be consumed in S/4HANA Analytics layer. It is mandatory to define at least one measures in the CDS view of type CUBE, else the view will not get activated and throw an error.
@DefaultAggregation: #SUM
This annotation is very important in the design of a CUBE like structure which we would see shortly. The system will be able to know these are actually Key Figures only when we use this annotation. As a result system will put them into the right bucket ‘Key Figures’ in the cube.
@EndUserText.label: ‘Weight of Luggage’
This annotation can be used to give a required business labels to the fields instead of using standard table field names.
The above view is like a CUBE where combined Dimension data with Fact data. Now we need a final view which will be ready for the consumption by UI tools and finally by business users in the from of Reports/Dashboards. This view will be like a Query on top of the previous CUBE view.
Let’s create the final view as below;
@AbapCatalog.sqlViewName: 'ZSQL_VIEW_FRPRT'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Flight Details Report'
@OData.publish: true
@VDM: {viewType: #CONSUMPTION}
@Analytics.query: true
define view ZCDS_VIEW_FREPORT as select from ZCDS_VIEW_FLBOOK
{
//ZCDS_VIEW_FLBOOK
key Airline,
key FlightConnection,
key FlightDate,
key BookNumber,
key Customer,
--key TravelAgency,
CalendarYear,
CalendarMonth,
CustomerCountry,
CustomerCity,
WeightOfLuggage,
WeightUOM,
BookingPrice,
Currency,
/* Associations */
//ZCDS_VIEW_FLBOOK
_Airline,
_CalendarDate,
_CalendarMonth,
_CalendarYear,
_Connection,
_Customer,
_CustomerCountry
}
Note the below annotations;
@VDM: {viewType: #CONSUMPTION}
This annotation describes that this view is the final view ready to Consumed. No Joins or Associations are performed here and this is made to behave like a query via below annotation.
@Analytics.query: true
This annotation actually SET this view to be consumption ready by different UI tools.It is mandatory to use this annotation if our intend is to create final analytical reports on this view via SAP front end tools – Bex, Webi, Lumira, SAC – SAP Analytics Cloud etc.
CONSUMING CDS VIEW INTO SAP UI TOOLS:
Now we will see how to consume the final View which also has a VDM ViewType CONSUMPTION means it is ready to be consumed.
- There are 2 tools in SAP S4HANA where this view can be consumed.
- RSRTS_ODP_DIS
- RSRT
RSRTS_ODP_DIS:
This tcode display the structure of the Cube we created with CDS views. If you remember, we created a CDS view of VDM type CUBE : ZCDS_VIEW_FLBOOK and the DDIC SQL view name is : ZSQL_VIEW_FLBOOK.
->Run T-code RSRTS_ODP_DIS
-Choose ODP Context as ‘ABAP Core Data Services
-For ODP Name, enter the DDIC SQL View name followed by ‘2C’
-Execute
What you will see now is a ‘Transient Provider’ system created. Note the structure, it is exactly like a BW cube. If you are a BW consultant, you can relate well. If not, just look at the nodes ‘KEY’, ‘DATA’, ‘UNIT’, and ‘KEY FIGURE’ and the fields underneath. This happens due to the different annotations we used while creating the CDS view, especially datacategory: #CUBE. If you don’t put this annotation, this will NOT work at all.
-Click on button ‘Standard Query’
-Now you can actually place data elements into rows and columns like a report.
-Since it is kind of a virtual cube now, you can also pull it into Bex Query Designer to create a Bex Query which can be configured with more advanced features and can be consumed into SAP Front end tools like Lumira, Webi, Analysis for MS Excel.
-> Open Bex Query Designer;
-Hit ‘Create’ and search for the view 2CZSQL_VIEW_FLBOOK and open
Now within Bex designer, you can create a regular report with all the advanced Bex features like Rows, Columns, Restricted/Calculated Key figures, Cell definitions, Exceptions, Conditions etc. and can be consumed into all Analytics tools like Webi, Lumira, Analysis for Office etc.
RSRT:
For simple CDS view with few Mathematical expression which we have already configured in the CDS view itself, we need not to really configure them into Bex Query designer for user consumption, rather we can directly have business users to access those via t-code RSRT. To enable the business user to access a CDS view as type of an analytical report, we need to create the final view which is ready for user consumption. This view will read the COMPOSITE view we created above. This view needs to be created of type CONSUMPTION and we need to add another annotation which will make this view as a query: @Analytics.query: true
Note the annotations :
@VDM: {viewType: #CONSUMPTION}
@Analytics.query: true
@AbapCatalog.sqlViewName: 'ZSQL_VIEW_FRPRT'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Flight Details Report'
@VDM: {viewType: #CONSUMPTION}
@Analytics.query: true
define view ZCDS_VIEW_FREPORT as select from ZCDS_VIEW_FLBOOK
{
//ZCDS_VIEW_FLBOOK
key Airline,
key FlightConnection,
key FlightDate,
key BookNumber,
key Customer,
--key TravelAgency,
CalendarYear,
CalendarMonth,
CustomerCountry,
CustomerCity,
WeightOfLuggage,
WeightUOM,
BookingPrice,
Currency,
/* Associations */
//ZCDS_VIEW_FLBOOK
_Airline,
_CalendarDate,
_CalendarMonth,
_CalendarYear,
_Connection,
_Customer,
_CustomerCountry
}
Now run T-code: RSRT and enter the name of the view followed by 2C and hit ‘Execute’
You can see the Key Figures already added as columns. Business users can now add Rows based on the analytics requirement they have.
In case a business user would want to have a default view with some Rows/Columns already added into the report when he/she execute it via RSRT. That can also be enabled via another annotations. Lets try that as well;
Check the annotation: @AnalyticsDetails.query.axis: #ROWS
You have different options here like Bex Designer;
Look at the whole code with ROWS and COLUMNS config.
@AbapCatalog.sqlViewName: 'ZSQL_VIEW_FRPRT'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Flight Details Report'
@VDM: {viewType: #CONSUMPTION}
@Analytics.query: true
define view ZCDS_VIEW_FREPORT as select from ZCDS_VIEW_FLBOOK
{
//ZCDS_VIEW_FLBOOK
key Airline,
key FlightConnection,
key FlightDate,
key BookNumber,
key Customer,
--key TravelAgency,
@AnalyticsDetails.query.axis: #ROWS
CalendarYear,
@AnalyticsDetails.query.axis: #ROWS
CalendarMonth,
@AnalyticsDetails.query.axis: #ROWS
CustomerCountry,
@AnalyticsDetails.query.axis: #ROWS
CustomerCity,
@AnalyticsDetails.query.axis: #COLUMNS
WeightOfLuggage,
WeightUOM,
@AnalyticsDetails.query.axis: #COLUMNS
BookingPrice,
Currency,
/* Associations */
//ZCDS_VIEW_FLBOOK
_Airline,
_CalendarDate,
_CalendarMonth,
_CalendarYear,
_Connection,
_Customer,
_CustomerCountry
}
Now check this query again in RSRT, see how awesome it is ?.. check the default rows & columns added.
Now if you are an ABAP expert, you might be thinking how to add a Selection Screen to this report and if you are a BW guy, you might be thinking how to add ‘Characteristic Restriction’ to filter the data. This is absolutely possible in a CDS view with use of one another annotation: @Consumption.filter.selectionType: There are different options to choose from, see below. Let’s add a selection parameter for Country with a ‘Single Selection’
Try running this query again with tcode: RSRT. Check the selection box shows up on the top. Enter US and execute.
Parameter as Mandatory Selection:
If you want to make the parameter as a mandatory selection; you can add another clause in the annotation :
Now if you try to run without passing any value, you can see an error message;
—All above we saw how to consume CDS view into SAP Analytics tools. Now we will see how to consume the same view into FIORI—
CONSUME CDS VIEW INTO ANALYSIS FOR OFFICE:
As I mentioned, a CDS view can be consumed into Analysis for Office to enable ad-hoc analysis by the business users. Let’s look how we can do it;
- Open Analysis for office and connect to the S4HANA system;
- Search for the CDS view of VDM type ‘COMPOSITE’ and dataCategory ‘CUBE’ we created above;
Data is ready now to do ad-hoc analysis;
CONSUME CDS VIEW INTO FIORI APPLICATION:
As we already saw in one of the previous blog that to consume a CDS view we need an OData service. So let’s first configure an OData service in the CDS view.
- Configure OData Service – This can be done by adding an annotation. Activate the view;
2. Copy the service name by hovering over mouse pointer on the yellow icon that show up after adding OData annotation;
3. Register the Service.
Goto code /n/IWFND/MAINT_SERVICE, click on ‘Add Service’ button;
4. Choose System Alias – ‘LOCAL’ and the external Service name which we just created by
OData. Hit Enter.
5. Select the service and hit ‘Add Selected Service’ button to register the service. This is only One Time Activity.
6. Choose LOCAL for Package Selection and execute;
7. Service is registered.
8. Start Web IDE to create a FIORI app on top of the CDS
9. New-Project from Template;
10. Choose ‘List Report Application’;
11. Add the required details and click ‘Next;
12. Connect to Server;
13. Choose the registered service name;
14. Select all the annotations;
15. For Data Binding, select the CDS view name and hit ‘Finish’
16. Now execute the FIORI application;
17. You can see a FIORI tile created;
18. Double click on FIORI tile and enter your credentials;
19. Enter ‘US’ in the mandatory parameter for Country Selection and hot ‘Go’. Since we did not yet selected columns to be displayed, we will see this message;
20. Click on ‘Setting’ button to add columns;
21. Look at the wonderful report generated. This is the new reporting methodology followed in S4 environment. There are many great features as well.
22. Users can enable more filters by themselves, I like this feature too much. No code required. Click on Adapt Filter->More Filters. Select the ones you need;
23. Check these filters are now available to filter out data;
In summary, we looked at the complete end to end cycle of an analytics requirements. In your projects, you would find a similar development but can be very complex based on what business users would want to see as the final reports.
ABAP CDS View on HANA – Learn how to create them
ABAP CDS view is used to define semantic data models on the standard database tables or dictionary views. A CDS view is defined with the statement DEFINE VIEW. In this ABAP on HANA tutorial, you will learn how to create ABAP CDS View on HANA. The abbreviation for CDS is Core Data Services. To know about ABAP CDS click here.
Prerequisites
- You have installed Eclipse IDE( Kepler/Juno version )on your local machine. Click here to know more about it.
- You have installed ABAP Development Tools in Eclipse IDE.
- You have access to ABAP Netweaver 7.4 on HANA.
- You have created ABAP Project in eclipse to connect to ABAP Netweaver 7.4 system. Click here to know how to create ABAP Project.
Step-by-Step Procedure
1. Choose the package in which you want to create CDS Views. Right-click on the package → New → Other ABAP Repository Object.

2. In the New ABAP Repository Object window, search for DDL source object by typing in search field.Select the DDL Source and hit Next.

3. In the New DDL Source window, enter Name and Description of the CDS View and hit Finish.

4. A new CDS view editor opens up like below.

5. Here we are going to retrieve the data from the table SNWD_PD using ABAP CDS View.Look at the DDL source we need to replace few values
- Replace data_source_name with table name “SNWD_PD” from which you want to get the data.
- Provide new value for @AbapCatalog.sqlViewName as “ZV_DEMO_01” .
6. Now the DDL source looks like below.

7. Lets look at the syntax for the CDS View.
Syntax
@AbapCatalog.sqlViewName: ‘CDS_DB_VIEW’
[@view_annot1]
[@view_annot2] …
[DEFINE] VIEW cds_entity [name_list] [parameter_list] AS select_statement [;]
In the first part of the syntax we declare annotations.
Annotation “@AbapCatalog.sqlViewName” is mandatory when creating CDS views, by which it creates a view in the Data Dictionary.
- cds_entity – is the name of the view.
- name_list – list of field names displayed in the output when we run the CDS view.
- parameter_list – list of input parameters to the CDS view.
- select_statement – is the select statement to be provided from table.
Full syntax documentation is available here.
8. Lets get back to our CDS view, here we are retrieving PRODUCT_ID, TYPE_CODE and CATEGORY from the table SNWD_PD. All the table fields will be entered inside the curly braces { } in DDL source editor like below. Now the code look like below.
@AbapCatalog.sqlViewName: 'ZV_DEMO_01' @ClientDependent: true @AbapCatalog.compiler.CompareFilter: true @EndUserText.label: 'Demo' define view Zcds_Demo_Example1 as select from snwd_pd { product_id, type_code, category }
To access all field from the table.
@AbapCatalog.sqlViewName: 'ZV_DEMO_01' @ClientDependent: true @AbapCatalog.compiler.CompareFilter: true @EndUserText.label: 'Demo' define view Zcds_Demo_Example1 as select from snwd_pd { * }
9. Do a syntax check by clicking on the syntax button in the toolbar and active the DDL Source.
10. Now a new ABAP DDL Source object will be created and available under the ABAP DDL Sources folder and also new dictionary view will be created along with it under the Views folder.
11. Right click on the newly created DDL source object and choose Open Data Preview to view the data.
12. You will see the output like below with data retrieving from the CDS view.
You have successfully created an ABAP CDS View on HANA. In our next tutorial we will know how to use these ABAP CDS view in ABAP programs/reports and also will have deep dive into full features of ABAP CDS views.
How to call ABAP CDS Views in ABAP report on S/4 HANA
The abbreviation for CDS is Core Data Services.To know about ABAP CDS click here.
Prerequisites
- You have installed Eclipse IDE( Kepler/Juno version )on your local machine.
- You have installed ABAP Development Tools in Eclipse IDE.
- You have access to ABAP Netweaver 7.4 on HANA.
- You have created ABAP Project in eclipse to connect to ABAP Netweaver 7.4 system.Click here to know how to create ABAP Project.
- You have already created ABAP CDS View.
Step-by-Step Procedure
1. Create an ABAP program/report.
2. In the New ABAP Program window, enter Name and Description and hit Next.
3. In the Selection of Transport Request window, choose the transport request. As we are saving the program in $TMP package in our case no transport request is required.Click on Finish.
4. To call an ABAP CDS view you can use Open SQL statements to get the data.Sample ABAP code snippet to call a CDS will look like below.
Syntax: SELECT * FROM <cds_view_name>.
SELECT * FROM ZCDS_DEMO_EXAMPLE1
INTO TABLE @DATA(lt_data).
But in this demo example we will use the CDS View to create an ABAP ALV report.Copy and paste the below code in the ABAP program.
************************************************
* OPEN SQL statement to access the CDS View *
************************************************
SELECT * FROM ZCDS_DEMO_EXAMPLE1 INTO TABLE @DATA(lt_data).
************************************************
* CDS View in ABAP ALV Report *
************************************************
DATA: lo_alv TYPE REF TO if_salv_gui_table_ida.
cl_salv_gui_table_ida=>create(
EXPORTING
iv_table_name = 'ZV_DEMO_01' "Name of CDS View name
RECEIVING
ro_alv_gui_table_ida = lo_alv
).
* CATCH cx_salv_db_connection. "
* CATCH cx_salv_db_table_not_supported. "
* CATCH cx_salv_ida_contract_violation. "
* Display ALV
lo_alv->FULLSCREEN( )->display( )
5. Lets look at the code, we have used CDS view name created in our previous tutorial to the ALV with IDA class CL_SALV_GUI_TABLE_IDA as a data source to the ALV. Save and activate the ABAP program.
6. Execute the ABAP report and you should see the ALV output like below.
You successfully learned how to call ABAP CDS Views in ABAP report on HANA.
How to use JOINS in ABAP CDS Views on HANA
The abbreviation for CDS is Core Data Services.To know more about ABAP CDS Views click here.
As an ABAP developer, we all know about JOINS and how to use them in our ABAP program which are running on traditional databases.
But our hands are tied up and we are refrained to use these JOINS due to performance issues in traditional databases. As an when SAP introduced HANA database no more restrictions in using them and we are free to use as many as JOINS on different tables. Thanks to SAP HANA.
In this tutorials we will see different types of JOINS available and we will learn how to use JOINS in ABAP CDS Views on HANA.
So lets have a look on how to use JOINS in ABAP CDS Views on HANA.
In this demo example we are using EPM tables SNWD_SO(EPM: Sales Order Header Table), SNWD_SO_I(EPM: Sales Order Item Table) and SNWD_PD(EPM: Product Data Table).
Step-by-Step Procedure
1. Choose the package in which you want to create CDS Views.Right click on the package → New → Other ABAP Repository Object.
2. In the New ABAP Repository Object window, search for DDL source object by typing in search field.Select the DDL Source and hit Next.
3. In the New DDL Source window, enter Name and Description of the CDS View and hit Finish.
4. A new CDS view editor opens up like below.
Different Types of JOINS
1. INNER JOIN or just JOIN
Selects all entries which exists in both tables which meet ON condition.
Below is the sample ABAP CDS views in which INNER JOIN is used among 3 tables to get the so_id, so_item_pos, product_id, amount and currency_code. Copy and paste the below code into DDL source
@AbapCatalog.sqlViewName: 'ZV_DEMO_01' @ClientDependent: true @AbapCatalog.compiler.CompareFilter: true @EndUserText.label: 'Demo' define view Zcds_Demo_Example1 as select from snwd_so join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key inner join snwd_pd on snwd_so_i.product_guid = snwd_pd.node_key { snwd_so.so_id, snwd_so_i.so_item_pos, snwd_pd.product_id, snwd_so_i.net_amount, snwd_so_i.currency_code }
2. LEFT OUTER JOIN
Selects all records from the left table matching with the right table which meet ON condition. If no record found in second table those record fields are null.
@AbapCatalog.sqlViewName: 'Z_CDS_OUTJOIN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Joins in ABAP CDS Views' define view Z_Cds_Joins as select from snwd_so left outer join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key { snwd_so.so_id, snwd_so.billing_status, snwd_so.delivery_status, snwd_so.op_id, snwd_so_i.so_item_pos, snwd_so_i.net_amount, snwd_so_i.currency_code }
3. RIGHT OUTER JOIN
Selects all records from the right table matching with the left table which meet ON condition. If no record found in left table those record fields are null.
@AbapCatalog.sqlViewName: 'Z_CDS_OUTJOIN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Joins in ABAP CDS Views' define view Z_Cds_Joins as select from snwd_so right outer join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key { snwd_so.so_id, snwd_so.billing_status, snwd_so.delivery_status, snwd_so.op_id, snwd_so_i.so_item_pos, snwd_so_i.net_amount, snwd_so_i.currency_code }
You have successfully learned how to use INNER JOIN in ABAP CDS Views on HANA. In the same way you can use left Outer Join and Right Outer Join.
How to create ABAP CDS Views with Parameters
In this ABAP for HANA tutorial, you will learn How to create ABAP CDS Views with parameters in ABAP for HANA. Input parameters are used to restrict the data from CDS Views. Please click here to access all tutorials related to ABAP CDS Views. Lets get started.
Prerequisites
- You have access to minimum ABAP Netweaver 7.4 system.
- You have installed Eclipse IDE( Kepler/Juno version ) on your local machine.Click here to know more about.
- You have installed ABAP Development Tools in Eclipse IDE.
- You have created ABAP Project in eclipse to connect to ABAP Netweaver 7.4 system.Click here to know how to create ABAP Project.
- You have basic understanding of ABAP CDS Views.
Step-by-Step Procedure
1. Choose the package in which you want to create ABAP CDS Views. Right-click on the package → New → Other ABAP Repository Object.
2. In the New ABAP Repository Object window, search for DDL source object by typing in search field.Select the DDL Source and hit Next.
3. In the New DDL Source window, enter Name and Description of the CDS View and hit Finish.
4. A new ABAP CDS view editor opens up like below and paste the below code.
@AbapCatalog.sqlViewName: 'Z_CDS_PARAMS' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'CDS View with Parameters' define view Z_Cds_With_Params with parameters p_billing_status :SNWD_SO_CF_STATUS_CODE, p_delivery_status :SNWD_SO_OR_STATUS_CODE as select from snwd_so join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key{ snwd_so.so_id as orderno, snwd_so_i.so_item_pos as itemno, snwd_so_i.currency_code as currency, snwd_so_i.gross_amount as grossamount, snwd_so_i.net_amount as netamount, snwd_so_i.tax_amount as taxamount } where snwd_so.billing_status = :p_billing_status and snwd_so.delivery_status = $parameters.p_delivery_status;
5. Lets observe the code
Line 8-9: We can provide the parameters to the ABAP CDS Views by adding the syntax WITH PARAMETERS p1, p2… Data Dictionary ABAP data types can be used while defining the parameters to the ABAP CDS Views.
Line 19-20: We can use the parameters p1, p2.. in CDS Views using the syntax :p1 or $parameters:p1
6. Now we will see how to call the ABAP CDS views with input parameters in an ABAP program using Open SQL statement. Create an ABAP program in eclipse ADT or SE38 transaction. Below is the code snippet to call the ABAP CDS Views with input parameters.
*-----------------------------------------------------------------* * Use Open SQL statement to get the data from the ABAP CDS views * * with Input Parameters * *-----------------------------------------------------------------* SELECT orderno, itemno, currency, grossamount, netamount, bill_status FROM z_cds_params( p_billing_status = 'P', p_delivery_status = 'D' ) INTO TABLE @DATA(lt_result). * Display cl_demo_output=>display( lt_result ).
Input parameters can be used in different places in the SELECT of the ABAP CDS view. Below are ABAP CDS views examples in different forms.
1Parameters used in SELECT list
In the below CDS view parameter “p_billing_status” is used in the SELECT list
@AbapCatalog.sqlViewName: 'z_cds_params' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'cds view with parameters' define view z_cds_with_params with parameters p_billing_status :snwd_so_cf_status_code, p_delivery_status :snwd_so_or_status_code as select from snwd_so join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key{ snwd_so.so_id as orderno, snwd_so_i.so_item_pos as itemno, snwd_so_i.currency_code as currency, snwd_so_i.gross_amount as grossamount, snwd_so_i.net_amount as netamount, snwd_so_i.tax_amount as taxamount, //Parameters used in SELECT list :p_billing_status as billing_status } where snwd_so.billing_status = :p_billing_status and snwd_so.delivery_status = $parameters.p_delivery_status;
2Parameters used in Arithmetic Expressions
In below CDS view code parameter “p_discount_percentage” is used in the arithmetic expressions to calculate the discount amount.
@AbapCatalog.sqlViewName: 'z_cds_params' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'cds view with parameters' define view z_cds_with_params with parameters p_billing_status :snwd_so_cf_status_code, p_discount_percentage :int4 as select from snwd_so join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key{ snwd_so.so_id as orderno, snwd_so_i.so_item_pos as itemno, snwd_so_i.currency_code as currency, snwd_so_i.gross_amount as grossamount, snwd_so_i.net_amount as netamount, // Parameter used in Arthimetic expressions (snwd_so_i.net_amount * :p_discount_percentage) as discount_amt } where snwd_so.billing_status = :p_billing_status;
3Parameters used in CASE statement
In the below CDS view code the input parameter “p_billing_status” is used in CASE distinction.
@AbapCatalog.sqlViewName: 'z_cds_params' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'cds view with parameters' define view z_cds_with_params with parameters p_billing_status :snwd_so_cf_status_code as select from snwd_so join snwd_so_i on snwd_so.node_key = snwd_so_i.parent_key{ snwd_so.so_id as orderno, snwd_so_i.so_item_pos as itemno, snwd_so_i.currency_code as currency, snwd_so_i.gross_amount as grossamount, snwd_so_i.net_amount as netamount, // Parameter used in CASE distinction case :p_billing_status when 'P' then 'Paid' else 'Un Paid' end as bill_status } where snwd_so.billing_status = :p_billing_status;
Aggregate Expressions in ABAP CDS Views
To access all ABAP CDS Views tutorials click here. Lets get started.
Prerequisites
- You have installed Eclipse IDE( Mars Version )on your local machine.Click here to know more about.
- You have installed ABAP Development Tools in Eclipse IDE.
- You have access to minimum ABAP Netweaver 7.4 on HANA.
- You have created ABAP Project in eclipse to connect to ABAP Netweaver 7.4 system.Click here to know how to create ABAP Project.
Below is the list of aggregation expressions used in ABAP CDS views.
1. SUM
@AbapCatalog.sqlViewName: 'ZCDS_AGGR' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Aggregations' define view Z_Cds_Agg_sum as select from snwd_stock join snwd_pd on snwd_stock.product_guid = snwd_pd.node_key { key snwd_pd.product_id, snwd_pd.category, // Aggregate function "SUM" sum(snwd_stock.quantity) as total_stock } group by snwd_pd.category, snwd_pd.product_id
In the above example ABAP CDS view selects the total stock of the product by using the aggregate function SUM and GROUP BY product and category.
2. MAX
@AbapCatalog.sqlViewName: 'ZCDS_AGGR' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Aggregations' define view Z_Cds_Agg_max as select from snwd_so join snwd_bpa on snwd_so.buyer_guid = snwd_bpa.node_key { key snwd_bpa.bp_id, snwd_bpa.company_name, // Aggregate function "MAX" max(snwd_so.gross_amount) as max_sales_amt } group by snwd_bpa.bp_id, snwd_bpa.company_name
In the above example ABAP CDS view selects the maximum sales amount generated by the customer by using the aggregate function MAX and GROUP BY business partner.
3. MIN
@AbapCatalog.sqlViewName: 'ZCDS_AGGR' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Aggregations' define view Z_Cds_Agg_min as select from snwd_so join snwd_bpa on snwd_so.buyer_guid = snwd_bpa.node_key { key snwd_bpa.bp_id, snwd_bpa.company_name, // Aggregate function "MIN" min(snwd_so.gross_amount) as min_sales_amt } group by snwd_bpa.bp_id, snwd_bpa.company_name
In the above example ABAP CDS view selects the minimum sales amount generated by the customer by using the aggregate function MIN and GROUP BY business partner.
4. COUNT( * )
@AbapCatalog.sqlViewName: 'ZCDS_AGGR2' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Aggregations' define view Z_Cds_Agg as select from snwd_so join snwd_bpa on snwd_so.buyer_guid = snwd_bpa.node_key { key snwd_bpa.bp_id, snwd_bpa.company_name, // Aggregate expression COUNT( * ) count(*) as min_sales_amt } group by snwd_bpa.bp_id, snwd_bpa.company_name
In the above example ABAP CDS view selects the total number of sales order created against the business partner by using the aggregate function COUNT( * ) and GROUP BY business partner.
5. COUNT( DISTINCT )
@AbapCatalog.sqlViewName: 'ZCDS_AGGR_4' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Aggregate Expressions' define view Zcds_Agg_C as select from snwd_so_i join snwd_pd on snwd_so_i.product_guid = snwd_pd.node_key { key snwd_pd.product_id, // Aggregate Expression - COUNT( DISTINCT ) count( distinct snwd_so_i.node_key) as orders_count } group by snwd_pd.product_id
In the above example ABAP CDS view selects the total number of sales order created against the product by using the aggregate function COUNT( DISTINCT ) and GROUP BY product id.
Points to be remembered
- Every aggregate expressions used need an alternative element name defined using AS.
- Aggregate expressions should require GROUP BY clause.
- All non-aggregated fields used in CDS view should be specified in the GROUP BY clause.
Congrats! You have successfully learned different Aggregate Expressions in ABAP CDS Views.
How to use String Functions in ABAP CDS Views
Prerequisites
- You have installed Eclipse IDE( Mars Version )on your local machine.Click here to know more about.
- You have installed ABAP Development Tools in Eclipse IDE.
- You have access to minimum ABAP Netweaver 7.4 on HANA.
- You have created ABAP Project in eclipse to connect to ABAP Netweaver 7.4 system.Click here to know how to create ABAP Project.
String Functions in ABAP CDS Views
Below is the list of frequently used string functions in ABAP CDS views.
1CONCAT(arg1, arg2)
CONCAT(arg1, agr2) string function can be used to concatenate two character strings.
@AbapCatalog.sqlViewName: 'ZCDS_STR_FUN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'String Functions' define view Zcds_Sql_Func as select from kna1 { // CONCATENATE name1 & name2 CONCAT( kna1.name1, kna1.name2 ) as full_name }
2CONCAT_WITH_SPACE(arg1, arg2, spaces)
This string function is used to concatenate two character strings with space. The number of blanks between the arguments arg1 and arg2 is specified in spaces.
@AbapCatalog.sqlViewName: 'ZCDS_STR_FUN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'String Functions' define view Zcds_Sql_Func as select from kna1 { // CONCATENATE name1 & name2 with 4 space CONCAT_WITH_SPACE( kna1.name1, kna1.name2, 4 ) as full_name }
3SUBSTRING(arg, pos, len)
To get sub string of arg from the position pos in the lenght len.
@AbapCatalog.sqlViewName: 'ZCDS_STR_FUN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'String Functions' define view Zcds_Sql_Func as select from kna1 { // To get substring for a given string SUBSTRING( kna1.name1, 2, 10) as name }
4LENGTH(arg)
It returns the no of characters in the string which is passed as a argument arg. It ignores trailing blanks.
@AbapCatalog.sqlViewName: 'ZCDS_STR_FUN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'String Functions' define view Zcds_Sql_Func as select from kna1 { // To get length for a given string LENGTH( kna1.name1 ) as name_length }
5LEFT(arg, len) & RIGHT(arg, len)
LEFT(arg, len) – It returns the left-side part of the string which is passed as argument arg of length len.
RIGHT(arg, len) – It returns the right-side part of the string which is passed as argument arg of length len.
Note: Trailing blanks are ignored
@AbapCatalog.sqlViewName: 'ZCDS_STR_FUN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'String Functions' define view Zcds_Sql_Func as select from kna1 { // To get length for a given string LEFT( kna1.name1, 3) as name_left, RIGHT( kna1.name1, 3) as name_right, kna1.name1 }
6LTRIM(arg, char) & RTRIM(arg, char)
LTRIM(arg, char) – It removes the trailing blanks and leading character which matches the parameter char.
RTRIM(arg, char) – It removes the trailing blanks and trailing character which matches the parameter char.
@AbapCatalog.sqlViewName: 'ZCDS_STR_FUN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'String Functions' define view Zcds_Sql_Func as select from kna1 { // Removes the trailing blanks and character LTRIM( kna1.name1, 'L') as name_lt, RTRIM( kna1.name1, 'T') as name_rt }
Congrats! You have successfully learned String Functions in ABAP CDS Views.Please stay tuned for more ABAP CDS view tutorials.
Comments
Post a Comment