Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
317 views
180 pages
Untitled
Uploaded by
DIvYesH KhaMbhaTi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Untitled For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
317 views
180 pages
Untitled
Uploaded by
DIvYesH KhaMbhaTi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Untitled For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Untitled For Later
You are on page 1
/ 180
Search
Fullscreen
S4D430 Building Views in Core Data Services ABAP (CDS ABAP) PARTICIPANT HANDBOOK INSTRUCTOR-LED TRAINING Course Version: 20 Course Duration: 3 Day(s) e-book Duration: 18 Hours 40 Minutes Material Number: 50151959SAP Copyrights, Trademarks and Disclaimers ©2020 SAP SE or an SAP affiliate company, All rights reserved, No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company. SAP and other SAP products and services mentioned herein as welll as their respective logos are trademarks or ragistered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Please seattp://aloball2.sap.com/corporate-en/legal/copyright/index. efor additional trademark information and notices: Some software praducts marketed by SAP SE and its distributors contain proprietary software components of other software vendors. National product specifications may vary. This course may have been machine translated and may contain grammatical errors or inaccuracies. ‘These materials are provided by SAP SE or an SAP affiliate company for informational purpases only, without representation or warranty of any kind, and SAP SE or its affiliated companies shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP SE or SAP affiliate company products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein shuld be construed as constituting an additional warranty. In particular, SAP SE or its affiliated companies have ne obligation to pursue any course of business outlined in this document or any related presentation, or to develop or release any functionality mentioned therein. This document, or any related presentation, and SAP SE's or its affiliated companies strategy and possible future developments, products, and/or platform directions and functionality are all subject to change and may be changed by SAP SE or its affiliated companies at any time for any reason without notice. The infrmation in this document is nat a commitment, promise, or legal obligation to deliver any material, cade, or functionality. All forward-looking statements are subject to various risks and uncertainties that could cause actual results to differ materially from expectatians. Readers are cautioned nat to place undue reliance on these forward-looking statements, which speak only as of their dates, and they should not be relied upon in making purchasing decisions. Scanian At igh recone TSARTypographic Conventions American English is the standard used in this handbook. ‘The following typographic conventions are also used. ©Copyright. all rights reserved YOR 440 @ Example text Example textContents 30 31 38 42 49 50 57 65 67 7 83 95 10 121 132 133 143 144 151 155 162 166 a. Course Overview Unit 1: Unit 2: Unit 3: Unit 4: Unit 5: Unit 6: Intraduction Lesson: Motivating CDS Views and Understanding the Background Lesson: Working with ABAP Development Tools (ADT) Lesson: Analyzing and Using A CDS View Basic SQL Features in CDS Views Lesson: Defining a Simple CDS View Lesson: Creating a CDS View with Inner Join, Projection, and Selection Lesson: Using ABAP Annotations in CDS Views More SOL Features in CDS Views Lesson: Using SQL Expressions in CDS Views Lesson: Using Built-in SQL Functions in CDS Views Lesson: Understanding Nested Views Lesson: Using Aggregations in CDS Views Lesson: Using Additional Join Types and UNION (ALL) Advanced Concepts Lesson: Defining CDS Views with Input Parameters Lesson: Building CDS Views with Associations Lesson: Enhancing a CDS View Lesson: Linking a CDS View with Authorization Rules Database-Specific Features of ABAP CDS Lesson: Understanding CDS Table Functions Consumption of CDS Views (Outlook) Lesson: Using @ CDS View as Data Source for ALV IDA Lesson: Using CDS Views as Replacement Objects Lesson: Generating OData Services from CDS Views Lesson: Understanding the Consumption of CDS Views in SAP Fiori Lesson: Understanding Analytics Based on CDS Views: Lesson: Understanding Virtual Data Madels with CDS Views ©Copyright. all rights reservedCourse Overview TARGET AUDIENCE This course is intended for the following audiences: ©Copyright. all rights reservedUNIT Lesson 1 Motivating CDS Views and Understanding the Background 2 Lesson 2 Working with ABAP Development Tools (ADT) 14 Lesson 3 ‘Analyzing and Using A CDS View 18 UNIT OBJECTIVES. + Know the Background for Core Data Services + Understand the Basics of CDS. + Work with ABAP Development Tools + Read a Data Definition + Use CDS-related Tools in ADT + Use Open SQL to Read From a CDS View Sconmnane A ighes rare 1 gayMotivating CDS Views and Understanding the Background Igeul LESSON OBJECTIVES. After completing this lesson, you will be able to: + Know the Background for Core Data Services + Understand the Basics of CDS. SQL Basics and ABAP's Classical Approach When it comes to accessing a Database Management System (DBMS) from within an application programming, the Structured Query Language (SQL} has esta! ied itself asa kind of first choice. SQL is largely standardized as ANS! SQL, but each vendor adds its own features, » Structured Query Language (SQL) ‘Access to dtabese management systems (OBMS) Largely standardized (S0L-92) ‘Thrwe sublanguages: DML, DDL, OG. + Data Manipulation Language (DML) Read and change data in DB tacies ‘Statements SELECT, INSERT, UPDATE, DELETE * Data Definition Language (DDL) Create and meintsin DB tables and views ‘Statements CREATE, ALTER, DROP, Data Gontrol Language (BCL) Deine authorizations and transaction conte ‘Statements GRANT, REVOKE, .. Figure 1: Reminder: SQL Overview SQL as a whole covers all kinds of tasks that might be relevant for an application program. There are three sublanguages of SQL: Data Manipulation Language (DML) Provides statements for reading and changing the content of database tables and comprises statements like SELECT, INSERT, UPDATE, and DELETE. Data Definition Language (DDL) Sconmnane A ighes rare 2 SyLesson: Motivating CDS Views and Understanding the Background Provides statements for creating database objects like tables and views and to maintain, their properties. Statements like CREATE TABLE, CREATE VIEW, ALTER TABLE, DROP TABLE belong to the DDL part of SQL, Data Control Language (DCL) Covers the aspects of data integrity and security. DCL allows the application ta define authorization rules and to bundle DML statements into transactions, better known to the AABAP developer as Logical Units of Work (LUW). DCL statements are, for example, GRANT and REVOKE. ABAP had always had a very special approach to SOL. ABAP's Classical Approach to SQL ” * DML in ABAP (Open SOL, ttegrste in programming language DB independent yntax B-independent behavior Reduced feature set compared to SOL-02 » DOLInABAP ABAP Dictionary (DB-independent toot Formbased edting of table cefiritons and views + DELIMABAP Net needed in ABAP ‘Authevization and transaction contra never on DB Havel [Always done in appication (ALUTHORITY-CHEGK, COMMIT WORK, ..) Figure 2: ABAP's Classical Approach to SQL In principle, only the DML part of SQL is available to an ABAP program at r@ytieneSQL the SQL variant that is built inte the ABAP language, only covers DML aspects. When ABAP developers want to define database tables and views, they are not supposed to issue DDL statements at runtime. They have to use the ABAP Dictionary tool, which provides form-based editors for table and view definitions {far example, repository objects ‘Transparent Table and Database View). During activation of these definitions, the system creates database-specifc DDL statements and sends them to the database. ‘The DCL part of standard SQL is not needed in ABAP. In the classical approach of ABAP, all tasks covered by this sublanguage are kept away from the database. The ABAP application logic is supposed to take care of authorization checks, locks, and transactions (LUWs). The Limitations of Classical Open SQL ‘The fact that Open SQL anly covers the DML part of SQL is not its only restriction. When we look at standard SQL, for example, the SQL-92 Standard, many DML features described there are missing from Open SQL. Sconmnane A ighes rare 3 SyUnit 2: Introduetion _@ Limitations in ABAP <7.4 SPOS Open SQL (before ABAP 7.4) [Ei fone 5 irons oF open Sot bee eens 7a Among the many limitations of conventional Open SOL, the missing support for expressions, either in the field list or in the WHERE clause, Was one of the most commonly missed features by application programmers. © General Restrictions No fied values No computed valves No CASE expressions No SOL funetins © Limited Support for Joins Only inner joins and left outer joins (Only Equi Join (join conation with operator Inveft outer join: No fies of right table m WHERE clause + More Limitations Na UNION & UNION ALL [Ey Fre & Sore uimsatons f Open SOL Beor Relea 780 605 ‘Two important reasons exist for these limitations: Open SOL wants to be database-independent, not only regarding syntax but — much more important — regarding the results. Open SQL has to be guaranteed that an Open SQL statement provides the same result on all databases. The easiest way to do this is to avoid those features of standard SQL where the database vendors have different opinions about what the result should look like, One example of this is arithmetic expressions where rounding rules are not the same on all databases. A basic performance rule of ABAP Programming has always been: Keep unnecessary load away from the database. The general assumption had been, that an application programmer, by fallowing this rule, would not make too much use of more sophisticated SQL features, even when they were available in Open SQL, The Limitations of ABAP Dictionary Views When it comes to the definition of Views in the ABAP Dictionary, the gap between ABAP and standard SQL used to be even bigger. Sconmnane A ighes rare + UyLesson: Motivating COS Views and Understanding the Background + DB-independent Definition of Database View Defined in ABAAP Dictionary frm based too!) (Created on database (CREATE VIEW statement) + Verytinitedsupport ofS features hi new Ep ‘Only simple projections (no calculated fields, no conversions, functions, ..) Cnc seer wer abe Only DB tables a8 sours (View-on-View not supported) + Som ABAP speciation Buffering caper evr center Swen a gy lr rpg Bore 5 aa teary vis ABAP Dictionary Views Jv Support on all DBNSS = v Join/Union, Projection, Selection « inner join & simple o-8 ‘selection only xX ‘Calculation expressions, aggregation, grouping not supported ee Nested views (on views) x not supported a Figure 6: Limitations of ABAP Dictionary Views ‘Again, the main reasons for these limitations was to keep the load away from the database, and to ensure that a query would return the same results on any databases. SAP HANA and the Need for Code-to-Data This all changed when, starting with Release 7.4, SAP HANA was fully supported by ABAP systems, Sconmnane A ighes rare > EyUnit 2: Introduetion _@ ao Tease )| SAP HANA takes advantage of ‘And changed the way of (o a) the latest technology developing and executing developments ‘applications 8 100% fn Memery comping No | Agaregatee ATP Lue vane bet ate nos ‘wl sneer al Column end rowstorage 7) Less Ince Ao 5-50x ,, Sxroreason Less Code ines ee a Acceleration a Mass data , orm fice, [jt ae Nt es Figure 7: The SAP HANA platform - More than just another database With SAP HANA, SAP combines the latest developments in hardware and software technology to provide a state-of-the-art in-memory database. However, SAP HANA is much more than a database. Several data analysis engines and a built- in application platform allow the execution of detailed data analyses and even application logic on the database layer itself, To benefit the most from SAP HANA’S capabilities, it is necessary to change the programming paradigm as well as the traditional application design. Application Programming Models a Figure B: Paradigm Changes in Appileatian Pragramming The basic approach of classic ABAP programming was: + Keep load from the database + Get all the data you need on the application server, and ABAP + Do your processing Sconmnane A ighes rare + GuyLesson: Motivating COS Views and Understanding the Background But to benefit the most from SAP HANA’s capabilities, especially from its use of parallelism and optimized data structures and transfer, it is better to do expensive calculations and aggregations on the database itself rather than transferring huge amounts of data onto the ABAP application server. This is a fundamental change to the ABAP programming paradigm. Now it becomes “logic to data", or "code-to-data" as it is frequently called, rather than "data to lot Classic Applications Data-Centric Applications UI Rendering UI Application Logic Service Logic Data-Centric Logic Database “Service Layer on Application Server or on SAP HANA itself (SAP HANA XSA) Figure 9: Transformation of Application Design The classical design of ABAP applications combined a powerful application server with a relatively dumb relational database and a similarly simple presentation layer. All the logic was located on the application server. The new application design, inspired by SAP HANA's improved capabilities, transfers part af the logic (called Data-Centric Logic in the figlansformation of Application Desigmto the database, On the other end, big parts of the logic (called UI Application Logic in the figure) move from the application server into smart clients. Only a middle part of the overall la Note: (Service Logic) remains on an application server. It is even possible to implement this remaining service layer on SAP HANA itself. This. approach is used by SAP HANA XSA. Sconmnane A ighes rare > EyUnit 2: Introduetion SAP HANA Core Data Services UI Rendering UI Application Logic Service Logic Data-Centric Logic Database SAP HANA Schema Figure 20; SAP HANA Native Applications and the Need for CDS With the dawn of SAP HANA and the possibility to develop applications directly on the database, not using an application server any more, the need arose to create a meta model repository directly on the database. As with the ABAP Dictionary on the application server, there should be more in the box for you than using native SQL's CREATE TABLE or CREATE VIEW — especially considering the need for enriching pure technical definitions with semantics. And that’s one of the main reasons far SAP's Core Data Services. {The Core Data Services (CDS) are a colection of domain-specific languages and services for defining and consuming semantically rich data models. DBL =] a @ Jou Dot Data Definitio Language " Query Language Data Control Language Model and retrieve data | [Consume CDS entities | [Define authorizations for on a semantic level ‘CDS views Fully transparent SQL higher than SQL extensions Modelled and declarative Extends native SQL ‘approach esas fr ronme Irgrates wih cass ‘authorization concepts Figure 11: Concept of Core Data Services (CDS) There are many technologies that introduce higher-level models on top of SQL to add semantics and ease consumption - for example, OData EDM madels, the Semantic Layer in the BI platform, JPA and enterprise objects in Java, or the business objects frameworks in ABAP. Those higher-level models share many commonalities, but are usually specific to their technology. This prevents their reuse across stacks and increases effort for application developers. Sconmnane A ighes rare + TyLesson: Motivating COS Views and Understanding the Background ‘To address this, SAP HANA introduced a set of domain-specific languages (OSL) and services ~ called Core Data Services — for defining and consuming semantically rich data models. ‘Amang these languages is an enhanced Data Definition Language (DDL) for defining semantically rich database tables/views (CDS entities) and user-defined types in the database. ‘Same of the enhancements are: Expressions Used for calculations and queries in the data made! Associations On a conceptual level, replacing joins with simple path expressions in queries Annotations To enrich the data madels with additional (domain specific) metadata ABAP Core Data Services UI Rendering UI Application Logic Seve Loa Data-Centric Logic Database Figure 12; Core Data Services an ABAP From the beginning, CDS was not designed for SAP HANA alone. Also the ABAP application server should be able to benefit from the enhanced capabilities that are offered by the DDL of CDS compared to the form-based ABAP Dictionary tool. Since the ABAP Dictionary with its capability of defining tables, views, and data types was already there. the natural way of introducing CDS on the ABAP application server was to add it to the ABAP Dictionary. An ADT-based source code editor allows you te create DDL sources. On activation, the CDS entities defined in such a DDL source become full ABAP Dictionary objects. They work as. ABAP types that can be named after a TYPE addition and they can be accessed in Open SQL. Sconmnane A ighes rare + BUYUnit 1: tntroduction © Database independent Use COS ABAP with any database supported by SAP « Advanced View Building (CDS views provide much more SL features than classical Dictionary Views + Annotations to add Semantic information ‘Aes end user tests, currency mys, bur setings, ‘Add semantic information for consumers (anaivtics, ODsta, SAP US, ..) + Implicit Authorization Checks Define authorzation rules for CDS Object «Associations instead of Joins Deine relations between CDS Object that wil be translate in joing + CDS Table Funetions: ‘Views based on scripted coding (Gurentty anly supported for SAP HANA) Figure 23: Some Basic Features of ABAP CDS Asa first step, the advanced view building capabilities of CDS have been implemented in ABAP CDS. With many, many tables already defined in the ABAP Dictionary, the DEFINE VIEW statement of ABAP CDS makes the full wealth of the CDS universe readily available to existing ABAP data models. ‘You can either define sophisticated new views or simply wrap an existing table in a COS view in order to enrich it semantically. For example, ABAP COS offers a new authorization cancept: based on roles defined with DEFINE ROLE in a DCL source code, In order to let an existing table participate in the new authorization concept, you can simply create a CDS view for that table that is connected to a role, Other examples are advanced joining of tables with assaciations of using specific annotations in order to connect existing tables to new technologies like OData or UI Sconmnane A ighes rare 1Lesson: Motivating COS Views and Understanding the Background ABAP Dictionary Views E> ABAP CDS Views v Support on all DBMSs ez ov Join/Union, Projection, Selection v e-g v inner join & simple inner Join, outer selection only join, union xX Calculation expressions, aggregation, grouping Jf not supported Oe x v not supported Figure 14: Advanced View Building with CDS ABAP (On a purely technical level, ABAP CDS Views provide the following additional capabilities compared to ABAP Dictionary Views: + Enhanced support for combining queries, such as UNION and OUTER joins + Support for calculations that use expressions in the column list and in selections «Aggregation and grouping in the data model + Nested views (View-on-View) Two Ways of Database Integration Even though the Care Data Services Specification is language and platform agnost ic, the CDS implementations are not. ABAP CDS HANA CDS + Same Semantic on all DBs + HANAcaly (HANA specific features available) + Initial Focus on View building + Initial Focus on Building Models + Integration into ABAP Dictionary {rom Sersten Figure 35: ABAP CDS versus HANA CDS. With HANA CDS and ABAP CDS we have two implementations based on the same specification, They are very similar but not 100% equal, This is mainly because the two implementations pursue different goals: Sconmnane A ighes rare PESADAUnit 1: tntroduction HANA CDS is located on the SAP HANA database directly and is meant to support the development of SAP HANA native applications (SAP HANA XS). It makes full use of features that are unique to SAP HANA. ABAP CDS is located on the Application Server ABAP. where it is fully integrated in the ABAP Dictionary and thus in the ABAP transport system, lifecycle management, etc. The goal of ‘ABAP CDS is to support the implementation of ABAP applications ~ independent of the database system. Therefore its initial focus is an view building, and not on building models from scratch ~ although this might become possible in the future. Conclusion: Due to the different requirements and platferms, the two CDS implemental feature sets and release cycles. A technical compatibility is nat guaranteed. Ins have different CDS-related Repository Objects = Data Definition (DDL Source) Defines @ COS View ar COS Table Function Display-anly in ABAP Workbench (as of Rel. 7.51) Eilitng requires the use oF ABAP Development Tests (ABAP in Exspee) = Recess Control (DCL Source) Defines authorization rules thet are automaticaly checked when @ program reads certain data Display-anly in ABAP Workdench (as of Ret 7.50) elit requires the use of ABAP Development Tools (ABAP in Eespe) + Matadata Extension (DDLX Source) Introduced with Rel. 7.51 ‘Adds or overuites semarte information of a CDS Wiew Display-only in ABAP Workeench Editing requires the use of ABAP Development Tools (ABAP in Exspse) Figure 16; COSwelated Repository Objects. With ABAP CDS, the following new repository object types were introduced: Data Definition + Also referred to as DDL Source (for Data Definition Language, named after the DDL part of SQL) + Contains the definition of either a CBS View or a CDS Table function Access Control + Also referred to as DCL Source (for Data Control Language, named after the DCL part of SOL) Sconmnane A ighes rare = SYLesson: Motivating CDS Views and Understanding the Background + Contains the definition of authorization rules that are automatically checked when a program accesses a certain CDS View or CDS table function Metadata Extension (DDLX Source) + New repository object in Rel. 7.51 + Contains additional or alternative semantic information for a CDS View Note: > Depending on the system release, you can display the source code of the new CDS-related repository objects in the classical ABAP workbench. However, t create or change the new repository objects, you have to use the respective editors in ABAP Development Tools (alse known as ABAP in Eclipse). ym LESSON SUMMARY You should now be able to: + Know the Background far Core Data Services + Understand the Basics of CDS. Sconmnane A ighes rare PECADWorking with ABAP Development Tools (ADT) ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Work with ABAP Development Tools Eclipse-Based ABAP Development ABAP Development Tools (ADT) is an alternative to the ABAP Workbench. ADT provides the following features: + A complete new ABAP development experience on top of the Eclipse platform + An open platform for developing new ABAP-related tools + Aset of open, language-Independent, and platform-independent APIs that developers can use to build new custom tools for the ABAP environment SAP GUI Client NW AS ABAP (7.31 $P4 or higher) Figure 17; ABAP Development Tools — Eclipse Based ABAP Development Benefits of Developing in Eclipse With ABAP Development Taols in Eclipse, you benefit from the usability, speed, and flexibility of Eclipse, while also benefitting from proven ABAP Workbench features. ABAP Development ‘Tools improves developer productivity by offering better refactoring functionality, code completion, auto-insertion, and code templates. It alsa includes an invaluable Quick Fix feature and is highly navigable. Sconmnane A ighes rare PECADLesson: Working with ABAP Development Tools (ADT) ABAP Development Tools allows you to connect te multiple ABAP systems and provides session failover, reducing the impact of lost connections. It also enables crass-platform development by integrating ABAP and non-ABAP development tools in a single, powerful integrated development envirenment (IDE) The architecture of ABAP Development Tools for SAP NetWeaver is designed to allow developers to use a single Eclipse client, installed locally, that connects to several ABAP back- end systems of different releases. This allows developers to control all activities in a central location and helps avoid time-consuming context switches. The client provides a set of standard Eclipse development taols, such as the project explorer for system browsing and search views. Getting Started with ADT * Eclipse is a framework * Tools for different languages as plugins * Each "Perspective" defines a set of tools —+ Choose Perspective "ABAP" for ABAP Development Figure 18: Selecting the Perspective se allows development in many different programming languages. To support this, Eclipse contains different combinations of tools, clecspectivels you have ADT installed, you can switch to the ABAP perspective. Chitisdow.. Open Perspective. Other...- ABAP in the menu bar or choose tOpen Perspectiveutton, Sconmnane A ighes rare = SYUnit 1: tntroduction @ LL Ee $08 eerie SPRINT a Mjse--0 Figure 19: Creating a Project When you use ADT, you log on to an SAP back-end system and work directly with Its repository objects. In this sense, the development process is exactly the same as when you use the ABAP Workbench; there is no manual check-out and check-in of the objects, An ABAP project serves asa container for the development objects that are stored Ina particular ABAP back-end system, and contains the logon parameters for the system logon — System, Client, User, and language. You must be logged on to the system to edit an object. Within the ABAP project, you can access any development object in the repository. In addition, to make it easier to manage objects you can set up Favorite packages for each project. Editing Repository Objects in ADT ee Neogene ce Pt - a Figure 20: Editing Repository Objects Sconmnane A ighes rare % SYLesson: Working with ABAP Development Tools (ADT) ‘TheProject Exploreprovides a hierarchical view of the repository, similar to the navigation area of the ABAP workbench. Under each project, you can maintain a list of favorite packages. By expanding the nodiystem Libraryyou see a list of all packages. ‘To open a specific repository object in its respective editor, double-click it. The editor is shawn on the right side of the ABAP perspective. For each new object, a new tab is added This simplifies the navigation between editors and objects. Different Types of Editors Native Eclipse Editors ohne eo Gee woKiw S|) + Eclipse features * Eclipse-like look & feel cath * Available tor some es Repository Objects (e.g. Programs, Classes a A Web Dynpro, etc. ) Integrated SAP GUI Editors a= ==) * Nonew features oe Tau eee cum coe me atuatoe pene + SAP GUI Look & Feel re * Used where no native editor is available = = e.g. Transactions, == ‘ Dictionary Objects, ‘Screens, etc. Figure 21: Native Edktors or integrated SAP GUI Editors There are two kinds of editors in ADT - there is a native Eclipse implementation and an SAP GUI based implementation. In the figure, Native Editors or Integrated SAP GUI Editors, you can see an example of each of the following types: + Editors for which there is a native Eclipse implementation For example, ABAP Editar + Editors that are displayed in an in-place SAP graphical user interface (GUI) For example, ABAP transaction editor with the classic SAP GUI visualization appearing within the Eclipse environment There is no requirement to use ADT for ABAP Development, and each developer is free to choose whether to use ADT or the classic ABAP Workbench. The functions and features of Eclipse and ADT lend themselves particularly well to object-oriented programming, such as built-in refactoring functions and support for unit testing. There are other tasks to which the ABAP Workbench is better suited — in particular working with module pools and screens. Sconmnane A ighes rare > SYUnit 1: tntroduction Documentation, Installation and Support for ABAP Development Tools m Get ABAP Development Tools from: Se SAP Software Download Center HOME AP TOOLS CLOUD TONS GATEWAFTODLS | + hitp:llservice. sap com!swdc ‘hia ators enon HP creer stagione AP Devslogaee Tosh fs? mcupon i mation ou at onsen ttnl Ke Ke + hitp:itocls.hana.ondemand.com Tutt sunsar atte sai tS wan Ete Also see SAP Community Network ” iieaihas eres iene ae apapiecnaee, winalghsiag! + Forte (42 ste ue on hunackrunacimt eclipse ‘Tecoma ae groves une ms se SUPE. CPER LICE A Figure 22; Further Information If you are locking for a local installation of ADT, you can choose from the following sources: Marketplace. + SAP Software Download Center (http://service.sap.com/swdc), a part of the SAP Service + SAP Development Tools for Eclipse Web site (http://tools.hana.ondemand.com). You can also find other products, such as the SAP HANA studio ar the tools for SAP UIS development on this site. + SAP Community Network pages (http://sen.sap.com/community/abap/eclipse and http/scn.sap.com/community/abap/hana). They provide documentation and support ‘on how to install the SAP Development Tools for Eclipse. Teal: LESSON SUMMARY ‘You should now be able to: + Work with ABAP Development Tools Sconmnane A ighes rare = Sy_ Analyzing and Using A CDS View LESSON OBJECTIVES After completing this lesson, you will be able to: + Read a Data Definition + Use CDS-related Tools in ADT + Use Open SQL to Read From a CDS view DDL Source, SQL View, and CDS View Generated) pon activation Figure 23: One DDL Source - Defines Two Objects A.CDS View is defined in a DDL Source, which is a new type of repository object. There is no editor for DDL sources in the classical ABAP workbench. This new type of repository object has to be analyzed and developed in ABAP Development Tools in Eclipse. Upon activation of DDL Source, two objects are created: the SQL View and the CDS View. Neither of them can be edited directly. ‘The SQL View is visible as an object in the ABAP Dictionary where it cannot be edited and only reveals a fraction of the information available in the DDL source. It serves as a representative of the database object. The CDS View carries more semantics than its SQL view. It is not created on the Database and itis not visible in the ABAP Dictionary. It can, however, be consumed via open SQL. The new Open SQL syntax intraduced with NW 7.40 SPS is required to access CDS Views. Sconmnane A ighes rare » SyUnit 1: tntroduction @AbapCatalog.sqlViewlame: "S4D430_CARR* define view $4D430_Carrier as select carrid, carrnane, currcode,, ura from searr Figure 24: SOL View and CDS View in DDL Source As with conventional database views, the simplest form of a CDS view is a projection ~ that is, a selection of fields from a single table. The language used is SQL Data Definition Language (DDL), but in an Open SQL form so that the view can be deployed on any database platform, As CDS views are part of Open SQL, natice also that there is no explicit client handling SQL View ... CDS View Repository Object (Dietionary) Not found in repository Represents “teal” database object + Not known to database + 16 an ABAP data type isan ABAP data type (structure, with client fei) (structure, without a client field) No additional semantics © Additional semantics (Annotations) Figure 25; Difference Between SOL View and CDS View ‘The name of the CDS entity is specified after the DEFINE VIEW statement. It is recommended, though not technically necessary, that the name of the DDL source and the name of the CDS view are identical, The name of the SQL View is specified after the Annotation @ABAPCatalog.sqlviewName. It has to be different from the name of the CDS entity. Like for any Dictionary view, the maximum length is 16 characters. Sconmnane A ighes rare ~ SyLesson: Analyzing and Using & CDS View Annotations G@AbapCatalog. sqlWiewName: 'S4043@_CARR @AbapCatalog. compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.1abel: ‘Demo: Simple Projection define view saDa3@_carrier as select carrid, GEndUserText.label: ‘Currency Code’ currcode, url @cEndUserText.label: ‘Homepage’ from searr Figure 26: Annotations ~ Some Basie Facts ACDS annotation (or annotation for short) enriches a definition in the ABAP CDS with metadata ‘An annotation is identified by a simple or structured name after @ leading character “@* or "Ox", Depending on its scope, an annatation can be found in different locations within the CDS Source View annotations Relate to the view itself and are placed before the define view statement, Element annotations Relate to elements in the field list and can be found before or after the element, Hints oO Element annotations after the element begin with leading characters "@< . SAP uses a set of predefined SAP annotations. Most of them are optional. But there is one @AbapCatalog.sqlViewName is mandatory in every CDS View definition. Sconmnane A ighes rare a SYUnit 1: tntroduction €DS-Related Tools in ADT mm « Display of SQL CREATE Statement + Active Annotations View » Dependency Analyzer + Data Preview Figure 27: COS-Related Tools in ADT ABAP Development Tools offers a variety of toals to analyze an existing DDL Source. These tools help to understand a CDS view definition ~ even when you do not yet know how to read the DDL Source itself. You find most of these tools if you right click the view name (either in the Project Explorer or in the DDL Source text} and go to subm@pen with Display SQL Create Statement Figure 28; Display SOL Create Statement When you activate a DDL Source, the development environment sends an SQL statement the database to create the SQL View. You can display this SQL CREATE statement as follows: 1, Right-click anywhere in the DDL Source. 2. ChooseShow SQL CREATE Statement ‘The SQL Create Statement is displayed in a dialog window (popup). Like with any native SQL statement, details of the CREATE statement will depend on the type of database used by the system, Sconmnane A ighes rare = EYLesson: Analyzing and Using CDS View Active Annotations View Figure 29; Active Annotations View (L) The Active Annotations view summarizes the semantic information of the CDS View and of its. view fields. This is not restricted to annotations alone, It also lists semantic information that is taken (inherited) from ather CDS Views or from DB table definitions and data elements. Open the Active Annotations view as follows: 1. Right-click DDL Source. (Either in the editor window or in the Project Explorer.) 2. ChooseOpen With. Active Annotations. The Active Annotal window. Ins view Is displayed in a dedicated tab in the tabstrip below the editor Sconmnane A ighes rare = EYUnit 2: Introduetion Flee Chm em Dio ten ace 1 Aten Girt GT ANP smn ap am cei inate iti a : =e a - quctinte na Ce came somo — as a ae =e : = one = = IES we nave aortas vw In the example above, you can see that field carrid of CDS View S44430_Carrier has a label “Airline”that is not defined in the corresponding DDL source. This label is taken (=inherited) from the source field in SCARR and originates from data element S_CARRID with which this source field is typed. Dependency Analyzer = a tersne a0 Se eerione ae Aa aL PEK Se in ut a0 mth enn ae + epee ne teat coven © Oe Tito saci Tesomsoanacc OM Theo (ion cari 3 ay em caren ‘SQL Dopendency Tree seLtean OmaaTine apts Da Oa es - se ar | ~ ee For more sophisticated ODL Sources, it can be quite difficult to find the actual source of the data. This becomes particularly true if a CDS View reads from several other objects and if Sconmnane A ighes rare = EyLesson: Analyzing and Using CDS View these other objects are not just database tables but CDS Views that again depend on other objects. ‘The Dependency Analyzer offers a simplified view by focusing on the dependancy tree and disregarding the rest. Open a given DDL Source in the Dependency Analyzer as follows 1. Right-click DDL Source. (Either in the editor window or in the Project Explorer.) 2. ChoaseQpen With. Dependency Analyzer. ‘The Dependency Analyzer opens in a new tab in the editor window. Data Preview Figure 32; Data Preview for CDS Views (1) The Data Preview too! allows you to analyze the data returned by a CDS View without the need to implement a SELECT statement yourself. In that sense, It is very similar to the Data Browser tool of the classical ABAP workbench (transaction code SE16). Open the Data Preview for a given DDL Source as follows 1. Right-click DDL Source. (Either in the editor window or in the Project Explarer.) 2. ChooseOpen With. Data Preview The Data Preview opens in a new tab in the editor window. Sconmnane A ighes rare = EyUnit 2: Introduetion [Fue SSOSC*~<“—~sSSSCS< r e nero ot bes tne meet the xencen nen oS Figure 33 Date Preview for CDS Views (2) ‘The Data Preview lists the first n entries of the specified view or table. N is set to 100 by default but you can increase or decrease this value manually (setting Max.Rows). The toolbar on the Raw Data tab offers additional functions: Add filter Opens a dialog to enter selection criteria Number of Entries Displays the total number of rows in the table/view that match the selection criteria SQL Consol Opens a new editor window with a SELECT statement for this view/table. You can edit this statement, execute it, and display the result to run a more sophisticated ad-hoc analysis of the data. Sconmnane A ighes rare = EYLesson: Analyzing and Using @ CDS View ‘A New Syntax for Open SQL mm Classical Syntax (Before NW 7.40 SPOS) SELECT carrid connid fldate SUM( paymenteum ) currency FROM sflight INTO TABLE gt_flights WHERE fldate > sy datum GROUP BY carrid connid fldate currency ORDER BY carrid connid. New Syntax Rules in NW 7.40 SELECT carrid, connid, fldate, SUM( paymentsum }, currency FROM s£light INTO TABLE Egt_flights WHERE fidate > @sy-datum GROUP BY carrid, connid, fldate, currency ORDER BY carrid, connid. Figure 34: New Open SQL Syntax in NW 7.40 AS of AS ABAP 7.40 SPOS, ABAP Open SQL offers a large variety of new features. In order to make this possible, it was necessary to re-design the Syntax af Open SQL. The new Syntax Rules as aff NW 7.40 are as follows: + Comma-separated calumn lists — to allow for sophisticated expressions + Mandatory escape character @ for ABAP data objects — to ensure a clear distinction between database objects (tables and table columns} and objects of the ABAP program (variables and constants). Regarding the usage of old syntax and new syntax, the following rules apply: + Ifan SOL statement uses the new syntax, it has to use it consistently. + An SQL statement may use the old syntax as long as it contains only features that were already available before NW 7.40 SPOS (compatibility mode). + Assoon as an SQL statement contains a single feature that was introduced in or after NW 7.40 SPOS, it has to follow the new syntax rules (strict mode). Note: D 2S views were introduced in NW 7.40 $F05. The new syntax is mandatory When using @ CDS View in a SELECT statement. Sconmnane A ighes rare > SyUnit 1: tntroduction Classical Sequence of Clauses SELECT carrid connid fidate SuM( paymentsum ) currency FROM s£light INTO TABLE gt_flights WHERE fidate > sy-datum GROUP BY carrid connid fidate currency ORDER BY carrid connid. New Syntax Rules in NW 7.50 seuect ROM sf1ight FIELDS carrid, connid, fidate, SUM( paymentsum ), currency WERE fldate > Oxy datum GROUP BY cazrid, connid, fldate, currency ORDER BY carrid, eonnia ITO TABLE egt_Elights. Figure 35; New Open SQL Syntax In NW 7.50 ‘AS ABAP 7.50 brought more new features to Open SQL and, along with those, additional changes to the syntax, Most importantly, the sequence of clauses was changed as follows: + Field list after FROM clause, introduced by new key word FIELDS — to allow for auto- completion when editing the field list + INTO clause at the very end of the statement — to support the UNION of several SELECT statements with one INTO clause Regarding the usage of this new syntax, the following rules apply: + An SQL statement may use the old sequence of clauses as long as it contains only that were available before NW 7.50 features + AS soon as an SQL statement contains a single feature that was intraduced in or after NW 7.50, it has ta use the new sequence of clauses (strict mode for NW 7.50) Note: » Some features of CDS were first introduced in NW 7.50. If the definitian of a View contains such a feature, any SELECT statement reading from this CDS has to use the new sequence of clauses. Sconmnane A ighes rare = SY cos iewLesson: Analyzing and Using @ CDS View One DDL Source - Two Objects to Read from Use of SQL View is ... Use of CDS View is + Not recommended! « Recommended! + Supported with classical » Only possible with and new syntax new syntax + Obsolete since NW 7.50 + Not fully supported before Rel. NW 7.50 {e.g.in joins with DB tables) Figure 36: One DDL Source - Two Objects to Read From ‘To use CDS in ABAP Open SQL, you can read either from the SQL View or from the CDS View. This might be a bit surprising because only the SQL View exists physically an the database. But if you read from the CDS View, the database interface will replace the name of the CDS View with the name of the corresponding SQL View when translating your Open SQL statement into a native SQL statement. This is the recommended way to access CDS views in ABAP. Alternatively, itis also possible to read from the SQL Wiew directly. This was never recommended and became obsolete with NW 7.50 Note: > In systems with release NW 7.40, CDS Views are not yet fully supported in Gpen SQL. Reading from the SQL View is then needed as a workaround. One exanpple is the join of a CDS View with a database table. This is possible in NW 7.50 or The workaround in NW 7.40 is a join of the corresponding SOL View with the} database table, LESSON SUMMARY ‘You should now be able to: + Read a Data Definition + Use CDS-related Tools in ADT + Use Open SQL to Read From a CDS View Sconmnane A ighes rare » SyLesson 1 UNIT 2 Defining a Simple CDS View Lesson 2 Creating @ CDS View with Inner Join, Projection, and Selection Lesson 3 Using ABAP Annotations in CDS Views UNIT OBJECTIVES. Create a DDL Source Understand the DDL Syntax Rules Define a CDS View That Reflects a Database View Use ABAP Annotations in CDS Views Work with Transiatable Texts in CDS. 31 az ©Copyright. all rights reservedDefining a Simple CDS View ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Create a DDL Source + Understand the DDL Syntax Rules Create a new DDL Source GM recickae Project See oe —— Fe ae — = a = eee = ae — eee a i —— a Figure 37; Create New DDL Source (1) To create a new DDL Source, proceed as follows: 1. Right-click on your project in the Project Explorer, 2. ChooseNew . ABAP Repository Object ... Sconmnane A ighes rare a SOYUnit 2: Basic SOL Features in CDS Views [Eh Fore Gen tew DOL owe 3. From the list, choos@ore Data Services Data Definitions Hint: Oo You can use the input field below Project to type a search term, e.g. “data"| 4, Chooseltext. 5, Enter the name of an (existing) package, and a name and description for the new DDL Source, Sconmnane A ighes rare = EyLesson: Defining a Simple CDS View Figure 39: Shosteut (If Package Already Cantains 8 DDL Source) If your package already contains a DDL Source, you can use the following shortcut: 1.1m the Project Explorer, expand subnettre Data Services. Data Definitionaf the favorite package. 2. Right-clickData Definitionand chooséNew Data Definition DDL Source Templates sci puna) thes fm raen gam ( — Figure 40: DDL Source Templates During ODL Source Creation When you create a new DDL, you can create a blank editor page. Alternatively, you can use one of several available templates as a starting point. Sconmnane A ighes rare = EyUnit 2: Basic SOL Features in CDS Views Usually, a respective dialog appears after you assigned the new DDL Source to your ABAP workbench request. But you can always return to the template selection later in the editing process. m oo lel . z CEB a gree ra Bia - i — eee ON @ etestawhonsoeteruman ‘Cetra Funct ih Porat i = ee os SS Beco seston — ooo i= so [Bowe 42: 201 Source templates During Eating To choose a template later, go to teenplatestab in the tabstrip below the editor window. Note: D> “evn deine your own templates inthe eator preferences. Goto Window Preferencesand search fotData Definition Templates” Sconmnane A ighes rare = EyLesson: Defining a Simple CDS View Syntax Rules Allowed Characters. Only ASCII-characters, + Keywords: ‘All uppercase, all lowercase, or lowercase with uppercase initial liter. No mined uppercase and lowercase. Allowed: SELECT, select, Select. Not allowed: SeLect, seleCT, + Literals: Numeric literals always in full, with decimal point if necessary. ‘Allowed: 1, 2.0, oF 0.5. Not allowed: .5, 1,3 Character literals enclased in single quotations marks (’. "UM, "00001" * Comments: Explicit end: enclosed by /* and */ Rest of ine; two forward slashes (i) ~ Separators: ‘Statements can be closed using @ semicolon (:). This is optional * Protected Words: Certain keywords cannot be used as self-defined names. Figure 42; General DDL Syntax Rules ‘The general syntax rules inside DDL Sources are as follows: Allowed Characters Only ASCiI-characters are allowed in data definitians. Keywords Keywords must be all uppercase, all lowercase, or in lowercase with an uppercase initial letter. Mixed uppercase and lowercase is not allowed. Literals Number literals must always be specified in full and a decimal point (.) used as a decimal separator if necessary. Character literals are enclosed in single quotations marks (') Comments. Two forward slashes (//) introduce a comment, which continues until the end of the line. Comments within lines or that span multiple lines are enclosed by the characters /* and *h Separators Statements can be closed using a semicolon (;}. This is optional because, far the moment, one piece of CDS source cade can currently anly contain a single statement. Protected Words Certain keywords are protected and cannot be used as self-defined names. Sconmnane A ighes rare = EYUnit 2: Basic SOL Features in CDS Views _@ Standard SQL ( After keyword SELECT ) @AbapCatalog-sqlViewlame: "S4D430_CARR™ define view $4043@_Carrier as select carrid, carrnane,, curreede,, url from scare CDS DDL Style ( After FROM-Clause, enclosed in ,{* and @AbapCatalog-sqlviewlame: "SaD436_CARR" define view S40830_Carrier as ect from scare { carrid, carrname, currcode, url ) Figure 43; Variants for Specifying the Element List When you define a CDS View, you have two options to specify the element list (that is the field list in the simplest case): after keyword SELECT, before keyword FROM. This corresponds to SQL standard syntax. 2, Enclosed in characters "{" and "}", after the FROM clause of the SELECT statement, This is specific to CDS Syntax and allows for improved auto-completion support, It is recommended that you use the second, CDS-specific syntax. Note: 2 Regarding auto-completion support, the CDS-specific syntax corresponds to| addition FIELDS in Open SQL. Naming Rules and Recommendations Regarding the names of DDL Source, CDS Entity, and SQL View, there are some hard rules enforced by the development tools, and mere recommendations that are intended to increase cleamess and readabi Sconmnane A ighes rare = EyLesson: Defining a Simple CDS View | DDL Source name: + Max. 30 Characters + Unique throughout the system (Customer namespace!) «Always Upper-Case ‘CDS View name: Max 30 Characters: Unique throughout the system (Customer namespace! ) Unique within ABAP Dictionary (global ABAP datatype) Not Case-sensitive Can be different from DDL Source name (not recommended!) ‘SQL View name: + Max 16 Characters (Standard Dictionary Object) + Unique throughout the system (Customer namespace!) + Unique within ABA Dictionary (global ABAP data type) « Not Case-sensitive (will be translated to Upper Case) + Different from CDS View name Figure 44; Naming Fules and Recommendations gem LESSON SUMMARY ‘You should now be able to: + Create a DDL Source + Understand the DDL Syntax Rules Sconmnane A ighes rare > EyCreating a CDS View with Inner Join, Projection, and Selection Igeul LESSON OBJECTIVES. After completing this lesson, you will be able to: + Define a CDS View That Reflects a Database View Inner Join in DDL Source | define view from spilt inner join scarr on apflicarrid, spEli.carrid, spfli.connid, scarr.carrnane scarr.curreede, spfli.cityfrom, spfli.cityto, airpfrom, ixpto , Figure 45: inner Join in DDL View Definition Sconmnane A ighes rare = SyLesson: Creating a COS View with Inner join, Projection, and Selection Aliases for Tables and Fields a inner join = earrid, connid,, eurreode as currency, cityfrom, cityto, xpfrom, airpto ) Figure 46; Aliases for Tables And Fields In the element list, addition AS defines an alternative element name. The alternative element name replaces the actual name of the element from the data source data_source, The view field is created under the alternative element name in the CDS database view. Accordingly, the alternative element name must comply with the rules for names of view fields of database views, as well as the general naming rules for names, which means that it must also meet the naming conventions for companent names of structures in ABAP Dictinary and cannot be a reserved component name. The reserved names that cannot be used are maintained in database table TRESE. Alternative element names can be used in the current CDS view to grant unique names for identically named elements fram different entities ef the data source. When the current CDS view is accessed, the alternative element names must be used instead of the actual name. Note: > Alternative element names cannot be used within the CDS view, with one exception: alternative element names can be specified directly or after Sprdjection in the ON condition of an association. Sconmnane A ighes rare » SyUnit 2: Basic SOL Features in CDS Views Key Definition catalog. prese: true define view $4439 Connection3 Key as select from spfli asc inner join searr as a on ¢.carrid = a.cuzrcode as currency, c.cityfrom, e.cityto, aizpézom, airpto, ) Figure 47; Key Definition KEY is used to define the current element as a key element of the current CDS entity. Any elements of a SELECT list can be defined as key elements that are placed without gaps at the start of the list, The key elements of the CDS entity are evaluated as follows if they are used as a data source of a SELECT statement in Qpen SOL: + By the addition ORDER BY PRIMARY KEY. In this case, the key elements must be defined at the start of the SELECT list without any gaps. + In implicit access control By default, the key elements of the CDS entity are used to document the semantics of the data model. The addition KEY is then ignored when the CDS view is activated and when other accesses are performed in program executions The default setting can be overridden using the view annotation AbapCatalog. preservekey: + If the value true is specified for this annotation, the key elements defined using KEY are also used as keys of the CDS database view. + If this annotation is not specified or specified with the value false, the key elements defined using KEY are ignored by the key of the CDS database view. Like in classic views, the key fields of the database view are derived implicitly fram the key fields of the basis tables and the join conditions. If this is not possible, all fields of the database view are key fields. Sconmnane A ighes rare wo SYLesson: Creating @ COS View with Inner Join, Projection, and Selection Selections define view $4438 Connection4 Selection as select from spfli asc inner join searr as a on ¢.carrid = a.carrid { key ¢.carrid, key c.connid, a.currcode as currency, c.cityfrom, e.cityto, airpfrom, airpto [where c.fitype > X))//exciude charter flights Figure 48; Selections Addition WHERE defines a condition for the results set of a CDS view. When the CDS view is accessed, the results set contains only the data from the data source data_source that meets the condition cond_expr specified after WHERE. Note: The fields evaluated the SELECT list, the condition do not need to be defined as elements of the CDS view in gem «LESSON SUMMARY ‘You should now be able to: + Define a CDS View That Reflects a Database View Sconmnane A ighes rare aUsing ABAP Annotations in CDS Views ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Use ABAP Annotations in CDS Views + Work with Translatable Texts in CDS ABAP Annotations for Views ry rere eo eter grin eee Por ie View Annotations, PxbapCatalog.2qiViewane BcLientDependent GendUserText label Element Annotations | @Senantics unitorweasure @EndUserText. label Parameter Annotations * GEnyironsentsaysteariela Gendusertext labo) Extension Annotations" abapcatalog.sqiViewappendiame Functon Annoatons” cL ient Dependent @enauserText abel "See details in the respective lessons "+ See the short outlook on those in the last unit Figure 49: Classification of SAP Annotations Dependent on the Evaluation, we distinguish two groups of annotations: ABAP Annotations and Framework-specific annotations. ABAP annotations ABAP annotations define technical and semantic attributes of a CDS object. They are usually evaluated for every CDS object when activated by the ABAP runtime environment. ABAP annotations can modify the behavior of Open SQL statements that access a CDS entity. One important example is how the client dependency of a CDS entity is defined using the associated ABAP annotation. Framework-specific annotations In most cases, the framework-specific annotations must be evaluated by the frameworks of the corresponding software components using a suitable API and are not relevant for activations and the ABAP runtime environment. Here, the names and values of these Sconmnane A ighes rare o OyLesson: Using ABAP Annotations in CDS Views framework-specific annotations must follow the rules of the relevant framework. For SAP components, these can be taken fram the tables of the Framevork-Specific Annotations document. Dependent on the Scope, we distinguish 5 graups of annotations: View Annotations Annotations for a CDS view, Placed in front of the DEFINE VIEW statement. Element annotations Annotations for an element of the SELECT list of a CDS view. Placed in front of ar after the element, Parameter annotations Annotations for a parameter of a CDS view, Placed In front of or after the parameter, Extension annotations Annotations for a CDS view extension, Placed in front of the EXTEND VIEW statement. Function annotations Annotations for a CDS table function. Placed in front of the DEFINE TABLE FUNCTION statement, 3 define view £44430 Annotations] Figure 50: Important ABAF View Annotations For CDS Views, the following important ABAP annotations exist: AbapCatalog.sqlViewName. Specifies the name of the CDS database view in the CDS view ClientHandling.type Defines the client dependency of the view. The default value is #INHERITED which specifies that the view is client-specific if at least one of its data sources is client-specific, ClientHandling.algorithm Determines further how implicit client handling is performed when accessing the client- specific view through Open SQL. Sconmnane A ighes rare = EyUnit 2: Basic SOL Features in CDS Views AccessControl.authorizationCheck Defines the implicit access contro! when Open SQL is used to access the CDS view. AbapCatalog.compiler.compareFilter Defines the evaluation of filter conditions in path expressions of the CDS view. AbapCatalog. buffering. <...> Define the buffering of the CDS view in SAP buffering. BAP Annotations far View Elements m ‘Semantics for Amount / Currency Code Semantics .amount .currencyCode price, @semantics currencyCede e eurgency, ‘Semantics for Quantity / UnitOfMeasure Semantics quant distance, y-undtofMeasure: DistancerD! Semantics unitOfMeasure: true distid AS DistancelD, Figure 51: Important ABAP Annotations for View Elements ‘The Semantics annotations are used to define the currency fields and quantity fields of CDS views and CDS table functions. Itis recommended to use
[email protected]
every amount field to a currency code fleld and annotatSemantics.quantity.unitOfMeasutrelink every quantity field to a unit field. Otherwise, a user of the CDS entity will have difficulties correctly interpreting and processing the values provided in these fields. Hint Oo Compare this to th€urrency/Quantity Feldtab that is available when edit transparent tables or structure types in the ABAP Dictionary tool Annotations@ Semantics. currencyCodand @Semantics. unitOfMeasuare optional for fields based on ABAP Dictionary typ@dKY andUNIT. Sconmnane A ighes rare "EAD ALesson: Using ABAP Annotations in CDS Views Syntax Variants for Annotations m Element Annotation before the Element GSemantics.amou price, eurzency, URRENCY' Element annotation after the Element price @
get_label_4_elenent ( ee | ‘The methods af global class CL_DD_DDL_ANNOTATION_ SERVICE read the texts as specified by an input parameter for the language, If no language is passed to the input parameter, the logon language is used as the default. Note: > Hfno text is found for the language, the secandary language in AS ABAP is ued. geal: LESSON SUMMARY You should now be able to: + Use ABAP Annotations in CDS Views + Work with Translatable Texts in CDS Scanian At igh recone « OyUNIT 3 Lesson 1 Using SOL Expressions in CDS Views 50 Lesson 2 Using Built-in SQL Functions in CDS Views ST Lesson 3 Understanding Nested Views 65 Lesson 4 Using Aggregation: 67 Lesson 5 Using Additional Join Types and UNION (ALL) m UNIT OBJECTIVES, + Use SOL Expressions in CDS Views + Use Built-in SOL Functions in CDS Views + Define CDS Views Based on Other CDS Views + Use Aggregate Functions and Group By in CDS Views + Understand Additional Join Types + Understand UNION and UNION ALL Sconmnane A ighes rare «SyUsing SQL Expressions in CDS Views ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Use SQL Expressions in CDS Views Literals Character Literals. Hello’ as col_char, //Type CHA *32768" as col_numc, //Type NUMC (only digits) Numeric Literals 32768 as col_inté, //Type INTa 4711 as col_int2, //Type INT2 in Range [~32768,32767] 255 as eol_inti, //Type INT1 in Range [0,255] 4.5 as col_fltp, //Type FLIP Literals with Domain Prefix S_CLASS."Y" as col_ecol, //S_CLASS is a domain in OIC HSCLASS.Y as col_eco2, //S CLASS has Fixed values 2S-€LASS.Y as col_eco3. //Value 'Y' checked by syntax check Figure 58: Literals ABAP CDS syntax offers the following types of literals: Character Literal: + Series of characters enclosed in single quotes + Type NUMC if it consists only of digits + Type CHAR otherwise Numeric Literals + Series of digits without quotes + May contain a decimal point, but not before the first digit Sconmnane A ighes rare = SyLesson: Using SQL Expressions in CDS Views + Type FLTP if it contains a decimal point + Type INT1, INT2 or INT4 otherwise, depending on the size Note: > ‘There are no numeric literals of type INT. This means that integer literals rhust lie Iv the value range of INT, Domain Prefixes far Literals In certain operand positions, a literal can have a domain prefix. A domain prefix consists of the name of a repositary object of type DOMAIN, intraduced with character "#" or"; "and separated by a pericd (" For most of the text literals, the quotes can be omitted when they are prefixed with a domain. Ifa literal is prefixed with a domain, syntax check will issue a warning in case the literal does nat match the fixed values of the domain or daes not lie in the value range specified by the domain. CASE Distinction ‘Simple Case Distinction CASE operand WHEN operand? THEN resulta [WHEN eperand2 THEN result2] [ELSE resultn] END + Comparable to ABAP Statement CASE ... WHEN... ENOCASE + Result depends on a series of “EQUALS"-comparisons ‘Complex Case Distinction (= Searched Case) CASE WHEN sqi_conditiont THEN resulet [WHEN sql_condition? THEN result2] [ELSE resultn] eno + Comparable to ABAP Statement IF .., ELSEIF .... ENDIF, + Result depends an a sequence of SOL conditions (logical expressions) Figure 59: Case Distinetians ABAP CDS offers case distinctions that can be used in the element list of a SELECT statement and as operands for other expressions. ‘A.case distinction returns exactly one value. This value depends on a series of conditions. ‘A.case distinction always starts with the keyward CASE and ends with the keyword END. The rest depends on the type of case distinction: Simple Case Distinction The result depends on the values of several operands. The simple case distine comparable to the CASE statement in ABAP. Sconmnane A ighes rare a GyUnit 3: More SOL Features in CDS Views Complex Case Distinction Also known as searched distinction, The result depends on a sequence of logical expressions. The complex case distinction is comparable to the IF statement in ABAP. @AbapCatalog.sqlViewName: 'S40430_EXPRCASE" define view $4d436 Expression Case as select, fron sbook { If Simple
If, like in the example, the ELSE branch is missing, syntax check will issue a warning. Sconmnane A ighes rare = ByLesson: Using SQL Expressions in CDS Views @AbapCatalog.sqlViewName: 'S40430_EXPRCASE' define view $4d43@_Expression Case as select fron sbook { If Complex case case when class = °F’ then ' * when wunit = ‘KG' and luggweight > 20 then ‘x" hen wunit = "LB’ and luggweight > © then "x" FSR end ‘as excess_luggaget, t Figure 61: Example 2: & Complex Case Expression ‘The figure above gives an example of a complex case distinction in a CDS View. Customers with a luggage weight larger than 20 kilograms or 44 pounds will be classified as having excess luggage. First class passengers, however, are always excluded from this classification. € hen (Cwunit = "KG' and lugeweight > 20 ) or ( wundt = °LB" and luggvedght >< ) ‘as excess luggage?! Figure 62; Example 2: Two Nested Case Expressions ‘The figure£xample 3: Two Nested Case Expressightes an example of nested case distinctions ina CDS View. ‘The outer CASE expression checks whether this is a first class booking. ‘The result in the ELSE branch of the outer CASE expression is not just literal but it consists of another case expression based on the luggage weight and unit: Of course, the result after a WHEN ... THEN branch could also be a case expression. Sconmnane A ighes rare = EyUnit 3: More SOL Features in CDS Views Arithmetic Expressions Four arithmetic operators (+,-,*, /) and brackets Three Types of Expressions + linteger Expression ‘Ab Operands have integer type (INT. INT2, INT, INTE) * Decimal Expression ‘Atleast one operand has decimal type (DEC, CURR, QUAN) (No operand of type FLIP + Floating Point Expression ‘Ab-operands have type FLIP Important Restrictions + If ona operand has type FLT, all operands require type FLTP * Operator "/* only allowed in floating point expressions. See next section for the possibility of type conversions Figure 63; Arithmetic Expressions In ABAP CDS, arithmetic expressions can be used as elements of the field list. ABAP CDS supports four operators, brackets and three different arithmetics (integer, decimal and floating point). The value range and precision of intermediate results hig! depends on the arithmetic that is used. > Note: Numeric literals without decimals have an integer type. Numeric Literals with decimals have the type: FLTP. } @AbapCatalog.sqlViewName: 'S40430_EXPRARITH" define view sid43@_Expression_arithmetic as select fron sflight { seatsmax, seatsocc, seatsmax - seatsoce as seatsfree, Seatsoce + seatsoce_b + seatsoce_f as seatsmax_tot, 2 * price as double_price Figure 64; Example; Arithmetic Expressions in CDS Views The figurexample; Arithmetic Expressions in CDS Vigives some examples for arithmetic expressions in CDS Sconmnane A ighes rare PESADALesson: Using SQL Expressions in CDS Views Type Conversions m + What it looks like: CAST ( operand AS target_type [PRESERVE TYPE] ) + What it does: ‘Converts the value of eperandinte forget type + Many Options for operand: Literal (without a domain pref) Field of a data source Arinmetc expression ‘Case aistinction wth GASE redtines tuncton + Two Options for target_type: A predefined dictionary type, e.g. abep-int4, abap.char(J@), abap.dec(8, 2) ‘Any Dictionary data element, € 9. 5_CARRID . BUCRS Ailton PRESERVE TYPE to change eamantiestributes, nly Figure 65: Type Conversion with CAST Expression Unlike ABAP, ABAP CDS does not know implicit type conversions. On the contrary, CDS inspects very strict type compatibility rules. ‘The CAST expressian of CDS allows you to implement explicit type conversions, ‘The operand for a type conversion cannot only bea literal or a field of the data source (for ‘example, of a database table). all kinds of other expressions are possible like arithmetic expressions, CASE distinctions, predefined functions, and many others. In NW 7.40, the target type could only be specified as a technical type, Le. as a predefined Dictionary type like INT4, CHAR or DE As of NW 7,50, any data element from the Dictionary can be the target type of a type conversion with CAST. A.cast with a Dictionary data element as target type can be useful, even if the technical type of the operand and the target data element are identical, In this case, only the semantic attributes of the operand are modified, You cam suppress a related syntax warning by adding the addition PRESERVING TYPE Note: » ‘There are restrictions with regard to the combination of source type and tafget type. Some combinations are not supported at all. Others only work with limitations. For example, it is currently not possible to use operands of typé FLTP. as source for the CAST expression. detailed matrix can be found in the ABAP language documentation Sconmnane A ighes rare = EyUnit 3: More SQL Features in COS Views @AbapCatalog-sqlviewame: "SaD430_EXPRCAST define view $40430_Expression Cast as select fron sflight 4 ‘agg9iie9" as col_char, cast(*198911@9' as abap. int) as col_inta, cast(‘19892109' as abap.dec(16,2)) as col dec, cast('19891109' as abap. fltp) as col_fitp, cast("19891109' as abap.dats) as col dats, cast('19891169' as s_date) as col_ddic, ‘cast("19891109' as s_customer preserving type) as col_cust, cast(seatsoce as abap.fltp) / cast(seatsmax as abap. ftp) ratio , oe ee (Re ea — RRR“) EET RTT] Figure 65; Example: ype Conversions With CAST The figureéxample: Type Conversions With CASiVes some examples of type conversions in CDS Views. Note that literal '19891109" and data element S CUSTOMER have the identical technical type NUMC(8). Tem LESSON SUMMARY ‘You should now be able to: + Use SOL Expressions in COS Views Sconmnane A ighes rare = EyUsing Built-in SQL Functions in CDS Views ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Use Built-in SQL Functions in CDS Views Arithmetic Functions ABAP CDS offers a variety of buil expressions. in functions that supplement calculations with arithmetic | Built-in Functions for Calculations + div(argt,arg2) Inst Onin values (NTF, BVT, NTA, NTH er DEC, CURR, QUAN Wh decir = 0) esutiye: pe start Resa lens rounded nego aloe » mediarg1,arg2) Input: Oni integer types (NTA, V2, INT, ITE) Result type type ot rot Result can be negative * division(arg?, arg2, dec) Input: Integer valuas, values with fed decimal (Types INT, #772, INT4,INTB_ and DEC, CURR, QUAN with any number of Gocimals) Result type: DEC win dec decimal places, length depend on type of aygt Result i alvoys rounded t dee decinatt Figure 67; Numeric Functions (1) ‘The main differences between functions div ) and division( ) are as follows: Input: Div( } only allows integer values as input. Division( ) only excludes flo: (binary or decimal), point numbers Result: Div( ) always retums an integer value. Divisiant ) allows you to specify the precision of the result. Sconmnane A ighes rare = EyUnit 3: More SOL Features in CDS Views Note: >» With respect to the signs, functions div{ ) and mod{ ) behave differently than the ABAP operators DIV and MOD. In SQL function div¢ }, the amounts of the arguments are divided and then the sign is assigned (positive if the arguments have the same signs, and negative if they have different signs). Accordingly, the result of MOD can be negative,|The ABAP operator MOD, on the other hand, only produces positive results. Built-in Rounding Functions abs(arg) eur the moka org + floor(arg) round othe nto negee towards 2g > 0, ay a 280 arg <0 + eoil(arg) round st ghar ietege avy tom zoe 1g >0, tds 24 ag <0 = round(arg,pos) pos > 0: Round arg to pos decimal places os £0, Round arg te positon [BR eure 60: numeric Functions (24 String Functions ABAP CDS offers a variety of built-in functions for string processing. Some were alresdy available in release NW 7.40, athers are new in NW 7.50. Sconmnane A ighes rare EECApALesson: Using Bullt-in SQL Functions in CDS Views Some Built-in Functions for String Processing (NW 7.40) * concat(arg?,arg2) Returns result of ype CHAR or SSTRING (depending on types of argt and arg2) All trailing blanks are removed Corresponds to ABAP statement GONCATENATE without addlion SEPARATED BY + replace(arg1, arg2, arg3) Result type depends on type of arg? corresponds to ABAP statement REPLACE ALL OCCURENCES OF arg? IN argl WITH arg3. + substring(arg,pos, len) Result type depends on type of arg ‘Similar to ABAP function substring( } or direct substring access: dobj {+off1[¢1en)] Important difference: pos denotes the position, not the offset! [Efe 6: string Processing Functions(a) The figure shows some important string functions available as off NW 7.40. A complete list, can be found in the ABAP language help. ‘Some Built-in Functions for String Processing (NW 7.50) = coneat_with_space(arg1,arg2,count) Like concat( ) but with count spaces between arg? and arg2 Si ir tOABAP statement CONCATENATE with addition SEPARATED BY = length(arg) Returns result of type INT4 Trailing blanks do not count ~ Corresponds '@ ABAP builtin function numefohar ( ) «= left(arg,n) and right(arg,n) ~ Similar to substring( ), but returns first or last n characters of arg left ) corresponds to ABAP expression arg (n) a Figure 70: String Processing Functions{2}) In NW 7.50 the existing functions for string processing were supplemented to fill gaps and to cover special cases. The figure shows some examples. & complete list can be found in the ABAP language help. Sconmnane A ighes rare EECADAUnit 3: More SOL Features in CDS Views Built-in Functions for String Processing (NW 7.51) + lower(arg) “Result type identical to ype of arg -NUNG, DATS and TIMS not alowed as input type Corresponds to ABAP statement TRANSLATE arg TO LOWER CASE + upper(arg) + Result type identical ta type of arg *NUMC, DATS and TIMS not allowed as input type *Corresponds to ABAP statement TRANSLATE arg TO UPPER CASE [ER Faure 72: string Processing Functions (3) Even more built-in functions for string processing were added in NW 7.51. Among them the functions for translating text to upper case and ta lower case are of special interest. » Note: Built-in functions ¢an be chained at will, This was actually used quite often, when in NW 7.40 fureettmat_with_space was not yet available. The solution based on the furmimatiooked like this: concat(concat(argi," '},arg2) @abapCatalog.sqlviewName: '54043@_FUNCCHAR, define view 244430 Funetion string as select fron searr ( carrid, = 1H! carrname ‘Lufthansa’ concat (carrid,carrname) “UNLufthansa a5 col_concat, concat_with_space(carrid, carrnane, >) "LH Lufthansa’ as col_concat_space, replace(carrname, "hans', 'Fritz') 1 => ‘Luftenitaa® ‘as col_replace, substring(carrnane, 5°) 44m ‘hans* as col_substring, Jength(carrid) as col_length If => 2 (trailing blank! ) ? where carmame = ‘Lufthansa’ [ES swe 72: rare ia recta na COE Wen The figurexample: String Processing in a CDS Visives some examples of string processing in CDS Views. Sconmnane A ighes rare FACADALesson: Using Bullt-in SQL Functions in CDS Views >» we The second argument of function replacet ) is upper-case but content of carmame is lower-case. + The second argument of function substring( ) is 5, not 4! + Function lengtht ) returns a value of 2 because the third character i a trailing blank CARRID is Currency and Unit Conversion Amounts and measurements are usually stored on the database in a source unit and source currency. To make values in different units or currencies comparable with each ather, they need to be converted, Traditionally, we do these conversions with standard function modules provided by SAP (e.g. UNIT_CONVERSION_SIMPLE or CONVERT_TO_LOCAL_CURRENCY). _ Built-in functions + Unit_Conversion(pl => a1, p2 =) Returns res of type abap quan CConwets. quanti in source unt ino a value target unt ‘Rulos maiained in ransacton CUN! and stored i databaco ilo TO06 ae) + Currency Conversion(pi => al, pz => a2, .. ) ‘Retumns res of type abap cur Converts an amount Source curency ne a value in target eurency [Based on the exchenge role vad on 6 trpet date Rules maintained in wansaction OBO and stored in database ables TUR. General Remarks: Parameter assignee wih oneal (Comma separated paremeters ‘Opconal parameter error_hanang with dtaut value FAIL_ON_ERROR™ ‘Other optons. “SET_TO NULL" and "KEEP_UNGONVERTED" ‘Result may depend on the database (aeterentrouncing rules) Figure 73: Curreney and Unit Conversions ‘The function modules make use of conversion rules that are maintained in standard transactions and stored in (client-dependent} tables. ABAP CDS allows you to move the conversions fram the ABAP stack onto database level. Two built-in functions are available to implement conversions in the DDL Source. Note: » Although the built-in functions use the same rules and lagic as the corresppnding ABAP function modules, you must not expect the exact same results. This js obvious when yau take into consideration that different rounding rules may apply for calculations on the database and for calculations in ABAP. Sconmnane A ighes rare = EyUnit 3: More SOL Features in CDS Views @AbapCatalog..sqlViewName: '540430_FUNCCONVL" define view $4443 Funetion Canvertionl as select fron spfli { carrid, connid, GSenantics.quantity.unitofeasure: 'OISTID Unit_Conversion( quantity => distance, ‘source _unit => distid, target_unit => cast('MI’ as abap. unit) ) as distance, @Semantics.unitofMessure: true cast('MI’ as abop.unit) as distid y Figure 74: Example: Unit Conversion from Kilometers to Miles Database table SPFLI contains a field DISTANCE in which the flight distance is stored for each flight connection. The corresponding unit of measure is found in field DISTID. In the CDS View definition above, the value in table field DISTANCE is converted into miles ('MI") and returned as view field DISTANCE. Literal "Ml" is retumed as view field DISTID. Semantics annotations are used to link the twa view fields to each other, Note: DD The tec itera! nas to be converted into ABAP Dictionary type Unit twice: To|make it compatible the input paramdénget_unitand to make use of the annotation Semantics. unitOfMeasure. | @AbapCatalog.sqlViewName: 'S4043@_FUNCCONV2" define view s4d43@_Function Conversion? as select fron s#light { carrid, connid, fidate, @Semant ics.anount .currencyCode: "CURRENCY" currency_conversion( camaunt => price, source currency => currency, round 2x, ‘target_currency => cast( 'USD" as abep. cuky), vexchange_rate_type => 'M', ‘exchange_rate_date => fldate, ‘error_handling => 'SET_TO_NULL* ) as price, @Semantics.currencyCode: true cast(‘USD' as abap.cuky) as currency , [EY re 75: amie: Corey Conversion Sconmnane A ighes rare = EyLesson: Using Bullt-in SQL Functions in CDS Views Database table SFLIGHT contains a field PRICE in which the standard ticket price is stored for each flight. The corresponding currency cade is found in field CURRENCY. In the CDS View definition in the figfample: Currency Conversiaihe value in table field PRICE is converted into US Dollars ("USD") and returned as view field PRICE. Literal "USD" is returned as view field CURRENCY. ‘Semantics annotations are used to link the twa view fields to each ather. Note: > The text literal has to be converted into ABAP Dictionary type CUKY twice: Th make it compatible with input paramdtrget_currencyand ta make use of annotation Semantics.currencyCode. Calculations with Dates. ‘As ABAP developers, we are used to doing calculations with data objects of type D: Subtract a date field from another date field to calculate the number of days that lie between them or add an integer value ta a date field to calculate the date that lies a certain number of days in the future. This is possible because ABAP automatically translates values of type D into integer values. similar mechanism does not exist on the database level. Here, date fields are not recognizable as date fields. Normally, they are created as ordinary character fields of length 8 Using these character fields in arithmetic expressions will lead to syntax errors and type casting with CAST will lead to wrong results. mm Built-in funetions, new in NW 7.50 = dats_is_valid(date) Returns result of type INT4 Retums 1 if date contains a valid date. 0 otherwise = dats_days_between(date1,date2) Returns result of type INT4 Calculates number of days between two dates (corresponds to date2 — date? in ABAP) » dats_add_days(date,count,on_error) Returns result of type DATS ‘Adds count days to the given date (corresponds to date + count in ABAP) = dats_add_months(date,count,on_error) Returns result of type DATS ‘Adds count months to the given date (na simple equivalent in ABAP) ‘General Remarks: ~ All dates in format YYYYMMIOD (technical format on database) += Possible values for on_error ‘FAIL’, ‘NULL, ‘INITIAL’, UNCHANGED! Figure 76: Calculations with Dates In order to make calculations with dates, four built-in functians are available in CDS as of NW 7.50 Scanian At igh recone = EyUnit 3: More SOL Features in CDS Views @AbapCatalog. salViewName: ,S4043@_FUNCDAYS* define view $40430_Function_Days as select from sbook 7 carrid, connid, fldate, bookid, dats_days between(order_date, fldate) as days ahead, dats_add_days( onder_date, 14, "FAIL' ) as due_date Figure 77: Example: Calculations with Dates The figureéxample: Calculations with Datyises two examples: + Fielddays_aheadeturns the number of days that lie between the order date of the booking and the actual flight date, + Fielddue_dateadds 14 days to the date found in tietter_date. Input value ‘FAIL! causes the function to raise an exception should an error occur. With ether options, you can make the function return the NULL value, the initial value 00000000") or the unaltered input value. yal LESSON SUMMARY You should now be able to: + Use Built-in SQL Functions in CDS Views Sconmnane A ighes rare « EyUnderstanding Nested Views ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Define CDS Views Based on Other CDS Views CDS Views Based on Other CDS Views Up ta now, our CDS Views were all based on a single database table or on a join of several database tables, In CDS you can also define CDS views that are based on one or more other CDS Views. This is sometimes referred to di/iew on View concept as"Nested Views” + CDS Views as data source of other CDS Views Join of COS Views and join of COS View wah OS tale supportes No technical limit of nesting depth and complet + Improved Re-use 9 calculation done in one basis view tat is used in several oer views Instead of cocig (anc martaning)Gerteal exoressions » Improved Readability nt et cr ean te rs [Eo 78 Need Views ew on vew Concer Building nested views is another important difference between the classical database views in ABAP Dictionary and the new CDS Views, The big advantages are the improved re-use of views and the improved readability. Note: > Regarding the advantages there is a striking similarity with the advantages pf modularization of source code, Sconmnane A ighes rare = 2Unit 3: More SQL Features in COS Views Advantages and Pitfalls . nn cocheoeradeed an a = Too many Nesting Levels inereage the hkelinood fer recursive references ‘eterirate the readability ofthe model incase the hkelinood for recundancies [ED Fore 75: ae orieie views Recommendations ml © Group your views into levels (proferably 3 levels) + Only access views that are assigned to a lower lavel Ee Tym LESSON SUMMARY ‘You should now be able to: + Define CDS Views Based on Other CDS Views. Sconmnane A ighes rare « EyUsing Aggregations in CDS Views ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Use Aggregate Functions and Group By in CDS Views Aggregate Expressions @ Aggregate Functions © MIN{ operand) and MAX( operand) Fetus the smallesigretest valve in eperand » SUM( operand) Calculates the sum ote vats of operand » AVG( operand) Calculates the average value of he valves f operand + COUNT(*) Fetus the number of enties in he result sat GOUNT( DISTINCT operand) Returs the number of sinc vans cf operand Figure 61: Aggregate Functions ‘An aggregate expression calculates a single walue from an operand (operand) by calling an aggregate function for multiple rows of a results set. The Aggregate Functiorshows the possible aggregate functions, ‘Aggregate expressions can be used in the field list of a SELECT statement or in an (optional) HAVING clause. Note: > For aggregate functions in the field list, it is mandatory to pravide an alias (addition AS) Regarding the result type, the following rules apply: + the result type of expressions MIN, MAX, and SUM is identical to the data type of operand. Sconmnane A ighes rare = EyUnit 3: More SOL Features in CDS Views + The result type of expressions COUNT and COUNT DISTINCT ...) is type INT4, +The result type of expression AVG is type FLTP - unless addition AS is used inside the expression, Usually, operand is a column or field in the data source of the current CDS View. Other options for operand are: + Literals + Case distinctions @AbapCatalog.sqlViewName: 'S4D43@AGGREGATE" define view 544430_Aggregates as select ‘from sflight C i min( seatsocs ) col_min, max( seatsocc ) col_max. sun( ) col_sum, avg seatsoce ) as col_avg. avg{ as abap.dec(15,2) ) as col_avg_cenv, count (*) as col_count, count(distinct planetype) as col_ent_dist, east( sum( 1) as abap.int@) as col_1iteral, sum( hen seateoce > seatemax then cast( 1 as abap.intd ) else 0 end ) | col_overbooked Figure 82; Example: Aggregate Functions The figureéxample: Aggregate Functiastsows examples far the various aggregate functions. The second AVG( ) expression uses addition AS to change the result type from abap.fitp to abap.dec(16,2). The last two elements of the field list are examples for alternative operands. Note that without the cast expression the result type of sum( 1) would be abap.intl (the type of literal 1). This would lead to an overflow as soon as the result exceeds 255. Note: Sum expressions with operands of a small value range (intl, int2, dec, curr,,quan with small value for length) are likely to cause overflow errors. Wrap it with p cast expression to provide a result type of sufficient value range. Sconmnane A ighes rare « OyLesson: Using Aggregations in CDS Views GAbapCatalog.sqiViewName: '$4043@_AGGRORPI define view $40420 Aggregates Group By 1 as select from sfiight { carrid, connid, eoune(*) ave( seatsoce ) col_count, ) group by eanrid, connid
[email protected]
: 'S40430_AGGRGRP2' define view $4D438_Aggregates_Group By 2 a2 select from sflight { concat_with_space(carrid, connid, 1) as 10, count(*) as col_count,, avg( eatsoce ) as col_avg, } group by carrid, connid Figure 83: Example: Aggregate Functions with GROUP BY ‘Addition GROUP BY groups rows in the result set that have the same content in the fields listed after GROUP BY, and retums a single row for each group. The fields must be specified using the same names as the fields in the data source. Any elements of the CDS view that are not specified after GROUP BY must be defined in the SELECT list using aggregate expressions, Conversely, GROUP BY must be used if aggregate expressions are contained in the SELECT list and all elements not defined using aggregate expressions must be specified after GROUP BY. Literals and other expressions cannot be specified after GROUP BY, If expressions or calls of predefined functions are specified as elements of the SELECT list using aggregate expressions, all the fields used must be specified in the GROUP BY clause. Hints oO ‘The ABAP DDL Source Editor is able to generate the correct GROUP BY clause automatically from the element list of the view. You can use this feature as| follows: + Go to thePrablemstab below the editor. + Expand nodérors. + Right-click error messag@ROUP BY clause is missjpand choos@uick Fix + On the following dialog window, chobisésh, Restrictions in ABAP CDS In CDS, several restris ns apply for the use of aggregate func! Sconmnane A ighes rare ° SlyUnit 3: More SOL Features in CDS Views ~ Argument of aggregate function vonly fields, literals, case distinctions +no other expressions or functions ( e.g. avg (seatsmax— seatsocc ) ) suse , View on View" to aggregate calculated results » Argument of function SUM has tobe numeric “INTS, DFL16, DFL34 are not supported ~ NULL values Are not considered in the aggregation + CDS View Extensions (see later) “CDS Views with aggregates cannot be extended before Rel. 7.51 Figure 84; Important Restrictions for Aggregate Functions in COS ml LESSON SUMMARY ‘You should now be able to: Use Aggregate Functions and Group By in CDS Views: ©Copyright. all rights reservedUsing Additional Join Types and UNION (ALL) ‘gam LESSON OBJECTIVES After completing this lesson, you will be able to: + Understand Additional Join Types + Understand UNION and UNION ALL Outer Joins SQL supports a large variety of join types. Only Inner Joins are supported in classical database views in ABAP Dictionary. Figure 85: Reminder: inner Join Asa reminder, the figuRteminder: Inner Join illustratea inner join: One row of the left table and one row of the right table are combined to a common result row if they fulfill the JOIN condition. Sconmnane A ighes rare na SyUnit 3: More SQL Features in COS Views © Left Outer Join Special treatment for let table Result set may contain entries of lefttabie without matching entnes in right table ‘Supparted in eeasicat Open SL + Right Outer Join Special trestment for ihttabie eeu set may contain ens of ight table who matching erties ine abe ‘Supported in Open SOL (9 of NW 7.40'SPUE) and ABAP COS + Full Outer Join Spocaltresimert for bth abies Rest set may contain ene of ef table wrout matching eres in igh abe Ree et iy contin antes of gh tble who matching tsi a as Net yet suppotedin pan SL and ABAP COS | teces SQL standard knows three (sub}types of outer joins. JOIN Condition: Lx = RY [ER gure 27: Ler outer jin Ina left outer join, one row of the left table and one row of the right table are combined to a common result row if they fulfill the JOIN conditien (like in inner joins). In addition, rows of the left table without matching row in the right table are copied to the query result. The missing values (from the right table) are filled with NULL values. Aleft outer join ensures that any entry of the left table that fulfills the selection criteria appears at least once in the join result, Sconmnane A ighes rare = EYLesson: Using /Additional join Types and UNION (ALLY Note: >» ‘These NULL values are set to a type-friendly initial value when the CDS view is used in Open SQL. OU] ME] NOTE x JOIN Condition: LX = RY [ER Faure so: nian outer jin In a right outer join the role of left and right table are exchanged: Rows of the right table without a matching row in the left table are copied to the query result. The missing values (from the left table) are filled with NULL values. Avright outer join ensures that any entry of the right table that fulfills the selection criteria appears at least once in the join result. Sconmnane A ighes rare = EDUnit 3: More SOL Features in CDS Views re a SES JOIN Condition: L.x = RY ns ULL [ MULE UL [MOLE xa} om|en] » ea] no| Ine [Ey owes be Fu osteroin (ot suponad m ABA COs) In a full outer jain, both tables are treated in the same way. Rows of both tables without a matching row in the other table are copied to the query result. The missing values (from the other table} are filled with NULL values. Note: DD Rat Gucerjons ae not yet supported in Open SOL or ABA CDS. As work around, you can use a UNION (see later) of a left outer join and a right outer @AbapCatalog.sqlviewName: 'S40430_JOINRIGHT* define view $44438_Join_Right_outer ax select from spfli_as ¢ right outer join scarr as a on c.carrid = a.carrid { key a.carrid, clcannid, c.cityfrom, c.chtyto 2] Mremneeeed «tm 3 ok aes SG888 PREREEE | [Braue 20: exampie: righ outer jin Sconmnane A ighes rare ™ EYLesson: Using /Additional join Types and UNION (ALLY ‘The figure gives you an example of a COS View with a right outer join. The Data Preview for this CDS View clearly shows the entries from the right table (SCARR) without matching entries in the left table (SPFLI. Cross Join Figure 81; Gross Jin (As off Release 7.51) When two data sources are joined using CROSS JOIN, the result is the cross product of these two data sources: All entries on the left side are combined with all entries on the right side, ‘The number of rows in the results set is the number of rows on the left side multiplied by the number of rows on the right side. It is not possible to specify a join condition for cross joins. Note: Across join with a WHERE condition has the same result as an inner join with an identical ON condition. Unlike the inner join, in a cross join all data is read fifst before the condition is evaluated, In an inner join only data that meets the ON condition is read. Sconmnane A ighes rare =Unit 3: More SOL Features in CDS Views @AbapCatalog.sqlWiewName: 'S4D432_JOINCROSS" define view $40436_JOIN_CROSS- ject eres anrticas ¢ RESUS exer ms = { key [REATFTJas carrid_scarr, 3carrmane, [ccearcid]as carrid_spfla, c.connid, c.cityfrom, <.cityto y » TRsomn,ou.cron » z tormenta rer Toe |= nme [oon] = ed he Oe [EE Bewre 92: Examte: Cross Join * All Datalls Read [No preselection through a join condition Escertion: tot tables ae cient pectic an impli in condition forthe cient field i used + Large Data Sources — Huge Result Set umber of resut ie sivaye the product of the number ofall ous of both dats [BR Pour 93: warnings Regaraing Cross Jin specify an ON condition, all data of all involved data sources is read. In the| of very large datasets, the results set (whose number of rows is always the product of the number af all rows of both data sources) can qi large. Caution: Across join should only be used with extreme caution. Since it is not pos ‘ kly becom Multiple Joins Explicit (with parantheses) or implicit (no parantheses) Parentheses are recommends (males the code easier to res) «+ Implicit Order of Evaluation INNER nd OUTER JOINS: Arrangement ef he ON conditions GROSS JOINS: fram lft ight [EE Fines 28: neste join Expressions - Order of Evaluation Sconmnane A ighes rare > EYLesson: Using /Additional join Types and UNION (ALLY ‘The FROM clause of a CDS View definition allows nested join expressions. ‘You can use parentheses (brackets) in order to influence the sequence in which the system evaluates these nested expressions. Note: > The use of parentheses is recommended for making the code easier to read) and to avoid unexpected behavior. Without parentheses, nested join expressions are evaluated in the following order: + In the case of inner and outer joins, by the arrangement of the ON conditions. From left to right, the mest adjacent ON conditions are assigned to each JOIN and this expression is parenthesized implicitly. + Cross joins are evaluated from left to right. Nate: > If several cross joins are combined, the order of the evaluation is irrelevant. |The result Is always the same and the number of raws is the product of the number of rows of all involved data sources. If cross joins are combined with inner and outer joins, the result can depend on the order of evaluation or the parentheses. @AbapCatalog.sqlViewName: 'S40430_JOINNEST! define view $4d43@_Join_Nested as select from sear as a left outer join ( sairport as p Left cuter join scounter as ¢ ‘on p.id = c.airport ) on a.carrid = c.carrid { a.carrid as carrier_id, pid as sirport_id, €.countnun as counter_number » | ee This example reads information about ticket counters {table scounter}. This information is joined with details about the airport where the ticket counter is located (table sairport) and the carrier that runs the counter (table scarr). The example uses outer joins because the result set should also include airports, where there are no ticket counters, and carriers, that do nat run any ticket counters at all ‘The parentheses are not required, But they are used to increase the readability of the expression. Sconmnane A ighes rare > SyUnit 3: More SOL Features in CDS Views @AbapCatalog.sqlViewame: “S4043@_JOINIMPL define view $44438_Join Nested _Implicite as select from scarr asa Left outer join sairport as p left outer Join scounter asc on p.id = c.airport =~ on a.carrid = c.earrid { a.carrid as carrier_id, p.id as ainport_id, c.countnum as counter_number » Figure 96; Example: Same Join with Implicit Ordering The figureexample: Same Join with Implicit Ordeshgws the same nested join expression, but this time without parentheses. This has no influence on the result. The two joins are evaluated in exactly the same order. But even for experienced developers, the evaluation order wi Note: » When defining views with nested joins, always add the parentheses to improve Prerequisites and Result Set of UNION _ SELECT A, 8, C, D FROM WHERE . aAvTeleyo 1 1[7] 9 2L2]2 2 [ays [eyo] a[3 9 +} Po ete 2]2lele 3[ 333 a[4[ata ‘UNION # ss SELECT A, 8, ee FROM. a 2 a 4 [ER Faure 27: umiow If you place keyword UNION between twa select statements, you create the ut the two results sets. Completely identical entries are removed from the result set. A.union results set can itself be the left side of a further union. Sconmnane A ighes rare = SD not be obvious at first glance. In of rows inLesson: Using /Additional join Types and UNION (ALLY Prerequisites + Compatible Structure of Result Sets ‘Same number of elements Elements in same postion have compatible data type Elements in same postion have identical nametaias Properties of Result Set + Element Names ‘Are identical inboth SELECT statements » Key Definition taken from frst SELECT statement + Element Type taken thm fret SELECT staernent Figure 88; UNION; Prerequisites and Result Set A prerequisite for UNION (ALL) is that the structures of the results sets are compatible. This means that the results sets must have the same number of elements and that the pairs of elements in each position have a compatible data type. The element names of the result sets must match, The properties of the union results set are defined as follows: + The element names are taken either from an explicitly specified name list or, if no list is specified, the matching names from the SELECT lists of all SELECT statements are used. + The definition of the key elements is taken from the SELECT list of the first SELECT statement. + The data types are taken from the elements in the first SELECT statement. If an element in the other SELECT statement has a compatible but longer type than the element in the first statement, for example chart20) instead of char(10), its content will be truncated. Caution: A When implementing a UNION in CDS ABAP, make sure the data types of tht elements in the element list of the first SELECT statement are long enough for the corresponding elements in the other SELECT statements. Otherwise information from the other statements cauld be truncated. Sconmnane A ighes rare »
You might also like
S4D480 EN Col21
PDF
No ratings yet
S4D480 EN Col21
270 pages
ABAP Development For SAP Business Workflow - Copy Yadp-82bf-q76m-Iuzh
PDF
100% (1)
ABAP Development For SAP Business Workflow - Copy Yadp-82bf-q76m-Iuzh
199 pages
SAP UI5 and Fiori Training
PDF
0% (1)
SAP UI5 and Fiori Training
121 pages
BR235 - EN - Col18 SAP Convergent Charging
PDF
No ratings yet
BR235 - EN - Col18 SAP Convergent Charging
195 pages
SAP DataSphere Tutorial
PDF
100% (1)
SAP DataSphere Tutorial
38 pages
SAP AIF - BIT750 - EN - Col03
PDF
No ratings yet
SAP AIF - BIT750 - EN - Col03
214 pages
S4D437 EN Col22
PDF
100% (1)
S4D437 EN Col22
184 pages
Free RAP Video Series On SAP TECHNOMANIAC YouTube Channel 1708760034
PDF
100% (1)
Free RAP Video Series On SAP TECHNOMANIAC YouTube Channel 1708760034
200 pages
S4D430 Building Views in Core Data Services ABAP (CDS ABAP)
PDF
0% (1)
S4D430 Building Views in Core Data Services ABAP (CDS ABAP)
20 pages
Act100 23 En-Us
PDF
No ratings yet
Act100 23 En-Us
261 pages
S4LG1 EN Col09 ILT FV Show
PDF
No ratings yet
S4LG1 EN Col09 ILT FV Show
246 pages
Extend SAP S - 4HANA in The Cloud and On Premise With ABAP Based Extensions
PDF
100% (1)
Extend SAP S - 4HANA in The Cloud and On Premise With ABAP Based Extensions
44 pages
SAP Ebook - 400
PDF
0% (3)
SAP Ebook - 400
1 page
1
PDF
20% (5)
1
1 page
CL 201
PDF
No ratings yet
CL 201
126 pages
No-Code Development With SAP Build Apps Enablement 2024
PDF
100% (1)
No-Code Development With SAP Build Apps Enablement 2024
81 pages
HC450
PDF
No ratings yet
HC450
249 pages
SAP ODATA V2 Transport and Troubleshooting Guide
PDF
No ratings yet
SAP ODATA V2 Transport and Troubleshooting Guide
37 pages
Sap Bpa
PDF
No ratings yet
Sap Bpa
95 pages
Ha300 en Col16 Ilt FV Show
PDF
No ratings yet
Ha300 en Col16 Ilt FV Show
405 pages
S4D401 EN Col24 CO A4
PDF
No ratings yet
S4D401 EN Col24 CO A4
25 pages
Abap Cloud Cheat Sheet
PDF
No ratings yet
Abap Cloud Cheat Sheet
33 pages
TSEC10 2 EN Col11
PDF
No ratings yet
TSEC10 2 EN Col11
245 pages
ABAP Platform in SAP 2023
PDF
No ratings yet
ABAP Platform in SAP 2023
104 pages
SAP - ABAP CDS Development User Guide: Client Version 3.6
PDF
No ratings yet
SAP - ABAP CDS Development User Guide: Client Version 3.6
108 pages
Rap VS Cap
PDF
100% (2)
Rap VS Cap
12 pages
ABAP
PDF
100% (1)
ABAP
21 pages
How To Find CDS View On S4HANA Embeded Analytics
PDF
100% (2)
How To Find CDS View On S4HANA Embeded Analytics
75 pages
Step by Step Process To Post Odata Services in Sap Sap Hana System
PDF
100% (1)
Step by Step Process To Post Odata Services in Sap Sap Hana System
44 pages
Sap La Sacp21 en 34 Ex
PDF
No ratings yet
Sap La Sacp21 en 34 Ex
359 pages
How To Call A BW ABAP-Backend From SAC Analytic Ap... - SAP Community
PDF
50% (2)
How To Call A BW ABAP-Backend From SAC Analytic Ap... - SAP Community
24 pages
SAP - ABAP CDS Development User Guide
PDF
No ratings yet
SAP - ABAP CDS Development User Guide
150 pages
SAP Workflow Bit601 en Col10
PDF
100% (1)
SAP Workflow Bit601 en Col10
432 pages
BIT602 EN Col23 CO A4
PDF
No ratings yet
BIT602 EN Col23 CO A4
23 pages
ABAP On Cloud - 5 - Introduction To RESTFul ABAP Programming
PDF
No ratings yet
ABAP On Cloud - 5 - Introduction To RESTFul ABAP Programming
14 pages
HANA CDS View
PDF
100% (1)
HANA CDS View
21 pages
Define Data Model
PDF
100% (1)
Define Data Model
34 pages
DEV211 - Core Data Services: Next On Sap Hana: Generation Data Definition and Access
PDF
No ratings yet
DEV211 - Core Data Services: Next On Sap Hana: Generation Data Definition and Access
66 pages
SAP Adobe Interactive Form Tutorial - Parte 4
PDF
100% (1)
SAP Adobe Interactive Form Tutorial - Parte 4
16 pages
ABAP CDS Best Practises
PDF
No ratings yet
ABAP CDS Best Practises
18 pages
SAP - ABAP RESTful Programming Model
PDF
100% (1)
SAP - ABAP RESTful Programming Model
28 pages
DMM360 Exercises PDF
PDF
100% (1)
DMM360 Exercises PDF
134 pages
SAPUI5 Training
PDF
No ratings yet
SAPUI5 Training
148 pages
Adm328 en Col22 Ilt FV Co A4
PDF
No ratings yet
Adm328 en Col22 Ilt FV Co A4
37 pages
CDS Views With Association
PDF
100% (1)
CDS Views With Association
11 pages
Developer Extensibility For SAP S4HANA Cloud On The SAP API Business Hub
PDF
No ratings yet
Developer Extensibility For SAP S4HANA Cloud On The SAP API Business Hub
8 pages
ABAP On HANA Using ABAP Development Tool PDF
PDF
No ratings yet
ABAP On HANA Using ABAP Development Tool PDF
61 pages
Introduction To ADT in Eclipse & HANA As Secondary DB
PDF
No ratings yet
Introduction To ADT in Eclipse & HANA As Secondary DB
41 pages
HA300 Notes
PDF
No ratings yet
HA300 Notes
86 pages
SAP Experts Mini Ebook OCT16
PDF
No ratings yet
SAP Experts Mini Ebook OCT16
71 pages
ABAP Programming
PDF
0% (1)
ABAP Programming
15 pages
Custom Business Configuration Apps in SAP S4HANA Cloud, On-Premise, and in SAP BTP ABAP Environment
PDF
No ratings yet
Custom Business Configuration Apps in SAP S4HANA Cloud, On-Premise, and in SAP BTP ABAP Environment
6 pages
CustomCodeMigration OP1809
PDF
No ratings yet
CustomCodeMigration OP1809
42 pages
ABAP Test Cockpit - Overview
PDF
No ratings yet
ABAP Test Cockpit - Overview
18 pages
D-Code Presentation - Building ABAP Applications Using Code Pushdown
PDF
No ratings yet
D-Code Presentation - Building ABAP Applications Using Code Pushdown
71 pages
Safeguard Performance of ABAP CDS Views CDS View Complexity
PDF
No ratings yet
Safeguard Performance of ABAP CDS Views CDS View Complexity
4 pages
BRFPlus - Custom Expression Types and Action Types PDF
PDF
No ratings yet
BRFPlus - Custom Expression Types and Action Types PDF
111 pages
CDS Views Notes
PDF
No ratings yet
CDS Views Notes
19 pages
ABAP Training For SAP HANA (Autosaved)
PDF
No ratings yet
ABAP Training For SAP HANA (Autosaved)
30 pages
SAP ABAP I3 IT SOLUTIONZ
PDF
No ratings yet
SAP ABAP I3 IT SOLUTIONZ
12 pages