0% found this document useful (0 votes)
15 views154 pages

Sap La S4D430 en 24 Ex

The document outlines a training course on Data Modeling in ABAP Dictionary and ABAP Core Data Services, consisting of exercises and solutions that span approximately 7.5 hours. It includes various units focusing on creating database tables, defining global data types, and working with CDS views, among other topics. The content emphasizes hands-on practice with ABAP development in an Eclipse environment, guiding users through the creation and analysis of different data objects.

Uploaded by

Daeslo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views154 pages

Sap La S4D430 en 24 Ex

The document outlines a training course on Data Modeling in ABAP Dictionary and ABAP Core Data Services, consisting of exercises and solutions that span approximately 7.5 hours. It includes various units focusing on creating database tables, defining global data types, and working with CDS views, among other topics. The content emphasizes hands-on practice with ABAP development in an Eclipse environment, guiding users through the creation and analysis of different data objects.

Uploaded by

Daeslo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

S4D430

Data Modeling in ABAP Dictionary


and ABAP Core Data Services

.
.
EXERCISES AND SOLUTIONS
.
Course Version: 24
Exercise Duration: 7 Hours 30 Minutes
Material Number: 50165753
SAP Copyrights, Trademarks and
Disclaimers

© 2024 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 well as their respective logos are
trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other
countries. Please see https://www.sap.com/corporate/en/legal/copyright.html for additional
trademark information and notices.
Some software products marketed by SAP SE and its distributors contain proprietary software
components of other software vendors.
National product specifications may vary.
These materials 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 purposes 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 should be construed as constituting an
additional warranty.
In particular, SAP SE or its affiliated companies have no 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 information in this document is not a commitment, promise, or legal
obligation to deliver any material, code, or functionality. All forward-looking statements are subject to
various risks and uncertainties that could cause actual results to differ materially from expectations.
Readers are cautioned not 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.

© Copyright. All rights reserved. iii


Typographic Conventions

American English is the standard used in this handbook.


The following typographic conventions are also used.

This information is displayed in the instructor’s presentation

Demonstration

Procedure

Warning or Caution

Hint

Related or Additional Information

Facilitated Discussion

User interface control Example text

Window title Example text

© Copyright. All rights reserved. iv


Contents

Unit 1: Exploring Data Modeling in ABAP

1 Exercise 1: Analyze Dictionary and CDS Objects

Unit 2: Creating Database Tables

9 Exercise 2: Create Domains and Data Elements


14 Exercise 3: Create a Database Table Definition
23 Exercise 4: Handle Changes to a Database Table

Unit 3: Defining Global Data Types

30 Exercise 5: Define and Use Dictionary Structures


37 Exercise 6: Define and Use Dictionary Table Types

Unit 4: Defining Basic CDS Views

44 Exercise 7: Define a Basic CDS View


48 Exercise 8: Use Annotations in Data Definitions
54 Exercise 9: Define a View on a View

Unit 5: Defining Relationships and Associations

59 Exercise 10: Define a Foreign Key Relationship


71 Exercise 11: Define a CDS View with Associations
79 Exercise 12: Use Associations in Path Expressions

Unit 6: Using Code Pushdown in CDS Views

86 Exercise 13: Use Expressions in a CDS View


91 Exercise 14: Use Built-in Functions in a CDS View
98 Exercise 15: Define and Use a CDS View Entity with Input
Parameters
107 Exercise 16: Process Data Sets in CDS Views

Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

117 Exercise 17: Create an Authorization Object and CDS Access


Controls
128 Exercise 18: Extend a Database Table Definition
135 Exercise 19: Extend CDS View Entities
144 Exercise 20: Create CDS Metadata Extensions

© Copyright. All rights reserved. v


© Copyright. All rights reserved. vi
Unit 1
Exercise 1
Analyze Dictionary and CDS Objects

You want to learn how to define objects in ABAP Dictionary and ABAP Core Data Services. In
the first step, you prepare the ABAP development environment, create a new package, and
analyze some existing objects.

Task 1: Prepare the Project


In Eclipse, create an ABAP Cloud Project and add package /LRN/S4D430_EXERCISE to the
list of favorite packages. In the ABAP Cloud project, create a new package under the
superpackage ZLOCAL (suggested name: ZS4D430_##, where ## is your group number) and
add it also to the favorite packages.

1. Open Eclipse, switch to the ABAP perspective and create an ABAP Cloud Project.

2. Add package /LRN/S4D430_EXERCISE to the list of Favorite Packages.

3. In your ABAP Cloud project, create a new package with the attributes listed in the table.
When prompted for a transport, choose the transport request in which you are involved. If
no transport request is listed, create a new request.

Field Value
Name ZS4D430_##, where ## is your group
number
Description Modeling in ABAP

Add to favorite packages Checked


Superpackage ZLOCAL

Package Type Development

Software Component ZLOCAL

Application Component Leave this field blank


Transport Layer Leave this field blank

Task 2: Analyze Objects


Analyze the content of package /LRN/S4D430_INTRO.

Note:
Package /LRN/S4D430_INTRO is a subpackage of package /LNR/
S4D430_EXERCISE.

© Copyright. All rights reserved. 1


Unit 1: Exploring Data Modeling in ABAP

1. In the Project Explorer view, expand /LRN/S4D430_EXERCISE → /LRN/


S4D430_INTRO → Dictionary and analyze the content.

Which types of development objects do you find in the Dictionary node?

Are there any objects with the same name?

2. Similarly, expand /LRN/S4D430_EXERCISE → /LRN/S4D430_INTRO → Core Data


Services and analyze the content.

Which types of development objects do you find in the Core Data Services node?

Do any of the objects under Core Data Services have identical names?

Task 3: Explore Usage in ABAP


Create an ABAP class that implements interface IF_OO_ADT_CLASSRUN (suggested name:
ZCL_##_INTRO, where ## stands for your group number). Use code completion to explore
which objects from package /LRN/S4D430_INTRO you can use as data types and as data
source in a SELECT statement.

1. In your package, create a new ABAP class (suggested name: ZCL_##_INTRO, where ##
stands for your group number).

2. In the IF_OO_ADT_CLASSRUN~MAIN method, declare a variable of type string


(suggested name: var).

3. Replace type string with an object from package /LRN/S4D430_INTRO. Use code-
completion to find out which of the objects you can use as data types.

Note:
All objects in package /LRN/S4D430_INTRO have a name that starts
with /LRN/S4D430_IND.

© Copyright. All rights reserved. 2


Exercise 1: Analyze Dictionary and CDS Objects

Which dictionary object(s) from package /LRN/S4D430_IND are available to be used as


data types?

How does this relate to the fact that the dictionary objects have different names?

Which CDS objects from package /LRN/S4D430_IND are offered as data types?

How does this relate to the fact that the CDS objects in this package have identical
names?

4. Implement a SELECT statement that reads from database table /LRN/S4D430_IND.

Hint:
To keep it simple, read all fields (FIELDS *), all rows (no WHERE clause), and
use an inline declaration in the INTO TABLE clause.

5. Replace /lrn/S4D430_ind in the FROM clause with another object from package /LRN/
S4D430_INTRO. Use code-completion to find out which of the objects you can use as data
source.

Note:
All objects in the /LRN/S4D430_INTRO package have a name that starts
with /LRN/S4D430_IND.

Which dictionary object(s) from the /LRN/S4D430_INTRO package are offered as data
sources in ABAP SQL?

© Copyright. All rights reserved. 3


Unit 1
Solution 1
Analyze Dictionary and CDS Objects

You want to learn how to define objects in ABAP Dictionary and ABAP Core Data Services. In
the first step, you prepare the ABAP development environment, create a new package, and
analyze some existing objects.

Task 1: Prepare the Project


In Eclipse, create an ABAP Cloud Project and add package /LRN/S4D430_EXERCISE to the
list of favorite packages. In the ABAP Cloud project, create a new package under the
superpackage ZLOCAL (suggested name: ZS4D430_##, where ## is your group number) and
add it also to the favorite packages.

1. Open Eclipse, switch to the ABAP perspective and create an ABAP Cloud Project.
a) Open Eclipse and close all tabs.

b) Choose Window → Perspective → Open Perspective → Other.

c) In the dialog box, double-click ABAP.

d) Choose File → New → ABAP Cloud Project.

e) Select Use a Service Key and choose Next.

f) Choose Import and select the file containing the service key that you have been given.

g) Choose Open Logon Page in Browser.

h) On the browser page that opens, choose directaccess.accounts.ondemand.com and


log on with the user and password that you have been given.

i) When you see the message, You have been successfully logged on, close the browser
window and return to Eclipse.

j) To finish creating the project, choose Finish.

2. Add package /LRN/S4D430_EXERCISE to the list of Favorite Packages.


a) In the Project Explorer on the left, expand your ABAP cloud project and then subnode
Favorite Packages.

b) Right-click Favorite Packages and choose Add Package ....

c) In the search field, enter /LRN/S4D430.

d) From the list of matching items, select /LRN/S4D430_EXERCISE, then choose OK.

3. In your ABAP Cloud project, create a new package with the attributes listed in the table.
When prompted for a transport, choose the transport request in which you are involved. If
no transport request is listed, create a new request.

© Copyright. All rights reserved. 4


Solution 1: Analyze Dictionary and CDS Objects

Field Value
Name ZS4D430_##, where ## is your group
number
Description Modeling in ABAP

Add to favorite packages Checked


Superpackage ZLOCAL

Package Type Development

Software Component ZLOCAL

Application Component Leave this field blank


Transport Layer Leave this field blank

a) In the Project Explorer, right-click on your ABAP Cloud Project and choose New →
ABAP Package .

b) Enter the package name ZS4D430_## where ## is your group number.

c) Enter the description Modeling in ABAP.

d) Select the checkbox Add to favorite packages

e) Enter the superpackage ZLOCAL.

f) Ensure that the Package Type is set to Development.

g) Choose Next.

h) Ensure the Software component is set to ZLOCAL.

i) Ensure that Application component is empty.

j) Ensure that Transport layer is empty.

k) Choose Next.

l) Check if there is a transport request listed under option Choose from requests in which
I am involved. If this is the case, choose this option. If the list is empty, choose the
option Create a new request and enter a request description, for example ABAP
Exercises.

m) Choose Finish.

Task 2: Analyze Objects


Analyze the content of package /LRN/S4D430_INTRO.

Note:
Package /LRN/S4D430_INTRO is a subpackage of package /LNR/
S4D430_EXERCISE.

© Copyright. All rights reserved. 5


Unit 1: Exploring Data Modeling in ABAP

1. In the Project Explorer view, expand /LRN/S4D430_EXERCISE → /LRN/


S4D430_INTRO → Dictionary and analyze the content.

Which types of development objects do you find in the Dictionary node?

Data Elements, Database Tables, Domains, Structure Types, and Table Types.

Are there any objects with the same name?

No, all five dictionary objects have different names.

2. Similarly, expand /LRN/S4D430_EXERCISE → /LRN/S4D430_INTRO → Core Data


Services and analyze the content.

Which types of development objects do you find in the Core Data Services node?

Access Controls, Behavior Definitions, Data Definitions, and Metadata Extensions.

Do any of the objects under Core Data Services have identical names?

Yes, all four CDS objects have the same name.

Task 3: Explore Usage in ABAP


Create an ABAP class that implements interface IF_OO_ADT_CLASSRUN (suggested name:
ZCL_##_INTRO, where ## stands for your group number). Use code completion to explore
which objects from package /LRN/S4D430_INTRO you can use as data types and as data
source in a SELECT statement.

1. In your package, create a new ABAP class (suggested name: ZCL_##_INTRO, where ##
stands for your group number).
a) In the Project Explorer view, right-click your package Z##_S4D430 to open the context
menu.

b) From the context menu, choose New → ABAP Class.

c) Confirm that the Package field contains the name of your package. Enter the name of
the new class in the Name field and Analyze dictionary and CDS in the
Description field.

d) Choose Add....

e) On the dialog window, enter IF_OO_ADT_CLASSRUN and choose OK.

f) Back on the previous window choose Next.

g) Confirm the transport request and choose Finish.

2. In the IF_OO_ADT_CLASSRUN~MAIN method, declare a variable of type string


(suggested name: var).

© Copyright. All rights reserved. 6


Solution 1: Analyze Dictionary and CDS Objects

a) Adjust the code as follows:

METHOD if_oo_adt_classrun~main.

DATA var TYPE string.

ENDMETHOD.

3. Replace type string with an object from package /LRN/S4D430_INTRO. Use code-
completion to find out which of the objects you can use as data types.

Note:
All objects in package /LRN/S4D430_INTRO have a name that starts
with /LRN/S4D430_IND.

a) Remove string.

b) Enter /LRN/S4D430_IND and press Ctrl + Space to invoke code-completion.

Which dictionary object(s) from package /LRN/S4D430_IND are available to be used as


data types?

All dictionary objects are available as data types except for the domain /LRN/
S4D430_IND_DOMAIN. Domains are not supported as ABAP data types.

How does this relate to the fact that the dictionary objects have different names?

Dictionary objects that are available as data types need to be distinguishable from each
other. Therefore it is not possible that data elements, structures, table types, and
database tables have identical names.

Which CDS objects from package /LRN/S4D430_IND are offered as data types?

Only CDS view entity /LRN/S4D430_IND_CDS_VIEW. All other CDS objects are not
supported as ABAP data types.

How does this relate to the fact that the CDS objects in this package have identical
names?

Identical names are allowed because the CDS objects are not used in the same places. In
particular, access controls, behavior definitions, and metadata extensions are not used as
data types.

4. Implement a SELECT statement that reads from database table /LRN/S4D430_IND.

© Copyright. All rights reserved. 7


Unit 1: Exploring Data Modeling in ABAP

Hint:
To keep it simple, read all fields (FIELDS *), all rows (no WHERE clause), and
use an inline declaration in the INTO TABLE clause.

a) Add the following code:

SELECT FROM /lrn/s4d430_ind


FIELDS *
INTO TABLE @DATA(result).

5. Replace /lrn/S4D430_ind in the FROM clause with another object from package /LRN/
S4D430_INTRO. Use code-completion to find out which of the objects you can use as data
source.

Note:
All objects in the /LRN/S4D430_INTRO package have a name that starts
with /LRN/S4D430_IND.

a) In the FROM clause, place the cursor immediately after /LRN/S4D430_IND.

b) Press Ctrl + Space to invoke code-completion.

Which dictionary object(s) from the /LRN/S4D430_INTRO package are offered as data
sources in ABAP SQL?

Only database tables, dictionary views (deprecated), and CDS entities are supported as
data sources. The only CDS entity in package /LRN/S4D430_INTRO is CDS view
entity /LRN/S4D430_IND_CDS_View.

© Copyright. All rights reserved. 8


Unit 2
Exercise 2
Create Domains and Data Elements

You want to create your own data model. In this exercise, you start by defining domains and
data elements for employee numbers and annual salary data.
Template:

n.a.

Solution:

/LRN/AMOUNT (Domain)
/LRN/EMPLOYEE_ID (Domain)
/LRN/ANNUAL_SALARY (Data Element)
/LRN/EMPLOYEE_ID (Data Elements)

Task 1: Create a Domain


Create a domain (suggested name: Z##_AMOUNT, where ## is your group number). Use the
appropriate dictionary type for amount values. Set the length to 15 and the number of
decimal places to 2.

1. Create a new domain Z##_AMOUNT.

2. Set the data type of the domain to CURR with a length of 15 and 2 decimals.

3. Activate the domain.

Task 2: Create Data Element


Create a data element that is based on your domain (suggested name: Z##_ANNUAL_SALARY,
where ## is your group number).

1. Create a new data element Z##_ANNUAL_SALARY.

2. Let the data element use domain Z##_AMOUNT.

3. Maintain the field labels and activate the data element.

Task 3: Create Data Element and Domain


Create a data element for the employee number (suggested name: Z##_EMPLOYEE_ID ,
where ## is your group number). Use forward navigation to create the domain. Give the
domain the same name as the data element. Make sure the employee number is 6 characters
long and consists only of digits.

1. Create a new data element Z##_EMPLOYEE_ID.

2. Use forward navigation to create a new domain for this data element. Use the same name
as for the data element.

3. Set the type of the domain to NUMC and the length to 6.

4. Activate the domain and return to the data element.

© Copyright. All rights reserved. 9


Unit 2: Creating Database Tables

5. Maintain the field labels for data element Z##_EMPLOYEE_ID and activate the data
element.

© Copyright. All rights reserved. 10


Unit 2
Solution 2
Create Domains and Data Elements

You want to create your own data model. In this exercise, you start by defining domains and
data elements for employee numbers and annual salary data.
Template:

n.a.

Solution:

/LRN/AMOUNT (Domain)
/LRN/EMPLOYEE_ID (Domain)
/LRN/ANNUAL_SALARY (Data Element)
/LRN/EMPLOYEE_ID (Data Elements)

Task 1: Create a Domain


Create a domain (suggested name: Z##_AMOUNT, where ## is your group number). Use the
appropriate dictionary type for amount values. Set the length to 15 and the number of
decimal places to 2.

1. Create a new domain Z##_AMOUNT.


a) In the Project Explorer view, right-click on your package to open the context menu.

b) Choose New → Other ABAP Repository Object.

c) On the dialog window that displays, enter doma in the search field.

d) Choose Domain and choose Next.

e) Confirm the package, enter the name Z##_AMOUNT and the description Amount, and
choose Next.

f) Assign the new object to a transport request and choose Finish.

2. Set the data type of the domain to CURR with a length of 15 and 2 decimals.
a) Place the cursor in the Data Type field and press Ctrl + Space.

b) From the suggestion list, choose CURR and press Enter.


Result
Two input fields appear: Length and Decimals.

c) Enter 15 in the Length field and 2 in the Decimals field.

3. Activate the domain.


a) Press Ctrl + F3 to activate the development object.

Task 2: Create Data Element


Create a data element that is based on your domain (suggested name: Z##_ANNUAL_SALARY,
where ## is your group number).

© Copyright. All rights reserved. 11


Unit 2: Creating Database Tables

1. Create a new data element Z##_ANNUAL_SALARY.


a) In the Project Explorer view, expand your package, and right-click on Dictionary to open
the context menu.

b) Choose New → Data Element.

c) Confirm the package, enter the name Z##_ANNUAL_SALARY, the description Annual
Salary, and choose Next.

d) Assign the new object to a transport request and choose Finish.

2. Let the data element use domain Z##_AMOUNT.


a) Under Category, keep the suggested value Domain.

b) Under Type Name, enter Z##, where ## is your group number, and press Ctrl +
Space.

c) From the suggestion list, choose Z##_AMOUNT.

3. Maintain the field labels and activate the data element.


a) In section Field Labels, enter the following data:

Field Value
Short Salary
Medium Annual salary
Long Annual salary
Heading Annual salary

b) Press Ctrl + F3 to activate the data element.

Task 3: Create Data Element and Domain


Create a data element for the employee number (suggested name: Z##_EMPLOYEE_ID ,
where ## is your group number). Use forward navigation to create the domain. Give the
domain the same name as the data element. Make sure the employee number is 6 characters
long and consists only of digits.

1. Create a new data element Z##_EMPLOYEE_ID.


a) In the Project Explorer view, expand your package, and right-click on Dictionary to open
the context menu.

b) Choose New → Data Element.

c) Confirm the package, enter the name Z##_EMPLOYEE_ID, the description Employee
Number, and choose Next.

d) Assign the new object to a transport request and choose Finish.

2. Use forward navigation to create a new domain for this data element. Use the same name
as for the data element.
a) In the Category field, keep the suggested value Domain.

© Copyright. All rights reserved. 12


Solution 2: Create Domains and Data Elements

b) In the Type Name field, enter Z##_EMPLOYEE_ID.

c) Open the Problems view below the editor.


Result
You should now see an error message No active domain Z##_EMPLOYEE_ID.

d) Choose label Type Name to create the new domain.

e) On the dialog window, enter your package, confirm the name of the domain, and enter
a description ( suggest value: Employee Number) . Then choose Next.

3. Set the type of the domain to NUMC and the length to 6.


a) In the Data Type field, enter NUMC and in the Length field, enter 6.

4. Activate the domain and return to the data element.


a) Press Ctrl + F3 to activate the new domain.

b) Choose the tab with the data element.

5. Maintain the field labels for data element Z##_EMPLOYEE_ID and activate the data
element.
a) In section Field Labels, enter the following data:

Field Value
Short Employee
Medium Employee No.
Long Employee Number
Heading Employee Number

b) Press Ctrl + F3 to activate the data element.

© Copyright. All rights reserved. 13


Unit 2
Exercise 3
Create a Database Table Definition

You want to create your own data model. In this exercise, you define a database table for
employee data.
Template:

n.a.

Solution:

/LRN/EMPLOY (Database Table Definition)


/LRN/BIRTH_DATE (Data Element)
/LRN/ENTRY_DATE (Data Element)

Task 1: Define a Database Table


Create a new database table definition Z##EMPLOY, where ## is your group number.
In addition to the client field, add the following fields:

Field Name Data Element


employee_id Z##_EMPLOYEE_ID (created in the previous
exercise)
first_name /DMO/FIRST_NAME
last_name /DMO/LAST_NAME
birth_date Z##_BIRTH_DATE (new, based on
domain /DMO/DATE)
entry_date Z##_ENTRY_DATE ((new, based on do-
main /DMO/DATE)
annual_salary Z##_ANNUAL_SALARY (created in the pre-
vious exercise)
currency_code WAERS

Hint:
If you have not completed the previous exercise, you can use data
elements /LRN/EMPLOYEE_ID and /LRN/ANNUAL_SALARY instead of your own
data elements.

1. Create a new development object of type Database Table (suggested name: Z##EMPLOY).

2. After the client field, add a second key field employee_id, and type it with the your data
element Z##_EMPLOYEE_ID. Use code completion to insert the name of the data element.

© Copyright. All rights reserved. 14


Exercise 3: Create a Database Table Definition

Note:
If you have not completed the previous exercise, use data element /LRN/
EMPLOYEE_ID, instead.

3. Add the following non-key fields. Use code completion to insert the names of the existing
data elements.
Field Name Data Element
first_name /DMO/FIRST_NAME

last_name /DMO/LAST_NAME

4. Add the following fields and use a quick fix to create the new data elements:
Field Name Data Element
birth_date Z##_BIRTH_DATE

entry_date Z##_ENTRY_DATE

For both data elements, use existing domain /DMO/DATE as data type.

5. Add the following amount and currency code fields, and use a quick fix to add the
@Semantics.amount.currencyCode: annotation for the reference to the currency code
field.
Field Name Data Element
annual_salary Z##_ANNUAL_SALARY

currency_code WAERS

6. Maintain the technical table settings. Use the value help to choose appropriate values for
the data class and the size category.

Note:
We expect the table to contain between 50 thousand and 60 thousand data
sets.

7. Activate the technical table settings and the database table definition.

Task 2: Include a Structure


Analyze dictionary structure /LRN/S_ADMIN and include it into the field list of your database
table definition.

Hint:
The administrative fields in this structure play an important role in the ABAP
RESTful application programming model. See the corresponding unit of the Basic
ABAP Programming course for more information.

© Copyright. All rights reserved. 15


Unit 2: Creating Database Tables

1. Open the definition of structure type /LRN/S_ADMIN.

2. Analyze the component list of the structure and the referenced data types.

How many components does the structure type have?

What are the technical types of the structure components?

3. Edit the field list in database table definition Z##_EMPLOYEE. Use code completion to
include structure /LRN/S_ADMIN at the end of the field list.

4. Display the Code Element Info for your database table and analyze the field list.

5. Activate all inactive development objects.

Task 3: Fill the Table


Fill your new database table with some example data. To do so, create a copy of ABAP
class /LRN/CL_S4D430_CHECK_AND_FILL (suggested name: ZCL_##_CHECK_AND_FILL,
where ## is your group number), adjust the value of constant c_employ_table, and execute
the class as console app.

1. Create a copy of ABAP class /LRN/CL_S4D430_CHECK_AND_FILL, name it


Z##_S4D430_CHECK_AND_FILL and place it in your package ZS4D430_##.

2. Change the value of the c_employ_table constant to the name of your database table.

3. Activate the ABAP class and execute it as a console app. If the console output contains
errors, adjust the definition of your database table until it is compatible with database
table definition /LRN/EMPLOY.

© Copyright. All rights reserved. 16


Unit 2
Solution 3
Create a Database Table Definition

You want to create your own data model. In this exercise, you define a database table for
employee data.
Template:

n.a.

Solution:

/LRN/EMPLOY (Database Table Definition)


/LRN/BIRTH_DATE (Data Element)
/LRN/ENTRY_DATE (Data Element)

Task 1: Define a Database Table


Create a new database table definition Z##EMPLOY, where ## is your group number.
In addition to the client field, add the following fields:

Field Name Data Element


employee_id Z##_EMPLOYEE_ID (created in the previous
exercise)
first_name /DMO/FIRST_NAME
last_name /DMO/LAST_NAME
birth_date Z##_BIRTH_DATE (new, based on
domain /DMO/DATE)
entry_date Z##_ENTRY_DATE ((new, based on do-
main /DMO/DATE)
annual_salary Z##_ANNUAL_SALARY (created in the pre-
vious exercise)
currency_code WAERS

Hint:
If you have not completed the previous exercise, you can use data
elements /LRN/EMPLOYEE_ID and /LRN/ANNUAL_SALARY instead of your own
data elements.

1. Create a new development object of type Database Table (suggested name: Z##EMPLOY).
a) In the Project Explorer, expand your package and open the context menu on subnode
Dictionary.

© Copyright. All rights reserved. 17


Unit 2: Creating Database Tables

b) Choose New → Database Table.

c) Confirm the package, enter the name Z##EMPLOY and the description Employee, then
choose Next.

d) Assign the new object to a transport request and choose Finish.

e) The code of the database table definition should look like this:

@EndUserText.label : 'Employee'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table z##employ {

key client : abap.clnt not null;

2. After the client field, add a second key field employee_id, and type it with the your data
element Z##_EMPLOYEE_ID. Use code completion to insert the name of the data element.

Note:
If you have not completed the previous exercise, use data element /LRN/
EMPLOYEE_ID, instead.

a) Adjust the code as follows:

define table z##employ {

key client : abap.clnt not null;


key employee_id : z##_employee_id;

3. Add the following non-key fields. Use code completion to insert the names of the existing
data elements.
Field Name Data Element
first_name /DMO/FIRST_NAME

last_name /DMO/LAST_NAME

a) Adjust the code as follows:

define table z##employ {

key client : abap.clnt not null;


key employee_id : z##_employee_id;
first_name : /dmo/first_name;
last_name : /dmo/last_name;

4. Add the following fields and use a quick fix to create the new data elements:

© Copyright. All rights reserved. 18


Solution 3: Create a Database Table Definition

Field Name Data Element


birth_date Z##_BIRTH_DATE

entry_date Z##_ENTRY_DATE

For both data elements, use existing domain /DMO/DATE as data type.
a) At the end of the element list, add birth_date : z##_birth_date; (with ## being
your group number).

b) Open the Problems view. You should see an error Field BIRTH_DATE: Component type
or domain used not active or does not exist.

c) place the cursor onz##_birth_date, and press Ctrl + 1 to open the quick fix
menu.

d) From the quick fix menu, double-click Create data element ....

e) Confirm the package and the name, enter a description, for example, Date of
birth, and choose Next.

f) Assign the new object to a transport request and choose Finish.

g) Under Type Name, enter /DMO/DATE and enter the following field labels:

Field Value
Short Born
Medium Born on
Long Date of Birth
Heading Date of Birth

h) Activate the new data element and return to database table Z##EMPLOY.

i) In a new code line, addentry_date : z##_entry_date; and use the quick fix again
to create data element Z##_ENTRY_DATE using the same domain, but with the
following field labels:

Field Value
Short Entry date
Medium Company entry date
Long Works for the company since
Heading Works for the company since

5. Add the following amount and currency code fields, and use a quick fix to add the
@Semantics.amount.currencyCode: annotation for the reference to the currency code
field.

© Copyright. All rights reserved. 19


Unit 2: Creating Database Tables

Field Name Data Element


annual_salary Z##_ANNUAL_SALARY

currency_code WAERS

a) Adjust the code as follows:

define table z##employ {

key client : abap.clnt not null;


key employee_id : z##_employee_id;
first_name : /dmo/first_name;
last_name : /dmo/last_name;
birth_date : z##_birth_date;
entry_date : z##_entry_date;
annual_salary : z##_annual_salary;
currency_code : waers;
}

b) Place the cursor over the error icon next to annual_salary to see error message
Annotation with reference to currency code for field ANNUAL_SALARY is missing.

c) Choose the error icon to open the quick fix menu.

d) Choose Assign currency code reference to field currency_code.

e) Make sure the quick fix adjusted the code as follows:

define table z##employ {


key client : abap.clnt not null;
key employee_id : z##_employee_id;
first_name : /dmo/first_name;
last_name : /dmo/last_name;
birth_date : z##_birth_date;
entry_date : z##_entry_date;
@Semantics.amount.currencyCode : 'z##_employ.currency_code'
annual_salary : z##_annual_salary;
currency_code : waers;
}

6. Maintain the technical table settings. Use the value help to choose appropriate values for
the data class and the size category.

Note:
We expect the table to contain between 50 thousand and 60 thousand data
sets.

a) Right-click anywhere in the editor and choose Open Others → Technical Settings.

b) Place the cursor at the beginning of the Data Class field and press Ctrl + Space to
display the value help.

c) Choose APPL0 Master Data, Transparent Table.

d) Repeat with the Size Category field and choose 3 Expected records 43.000 - 170.000.

7. Activate the technical table settings and the database table definition.

© Copyright. All rights reserved. 20


Solution 3: Create a Database Table Definition

a) While still on the Technical Table Setttings dialog, press Ctrl + F3 to activate the
technical table settings.

b) Return to the editor with the source code of the database table definition and press
Ctrl + F3 to activate the database table definition.

Task 2: Include a Structure


Analyze dictionary structure /LRN/S_ADMIN and include it into the field list of your database
table definition.

Hint:
The administrative fields in this structure play an important role in the ABAP
RESTful application programming model. See the corresponding unit of the Basic
ABAP Programming course for more information.

1. Open the definition of structure type /LRN/S_ADMIN.


a) From the eclipse toolbar, choose Open ABAP Development Object. Alternatively, press
Ctrl + Shift + A.

b) Enter /LRN/S_ADMIN and press Enter.

2. Analyze the component list of the structure and the referenced data types.

How many components does the structure type have?

The structure type has 5 components.

What are the technical types of the structure components?

The two components ending with _BY are of type CHAR(12). The other three components
are of type DEC(21,7).

a) In the row starting with define structure, place the cursor on /lrn/s_admin and
press F2 to display the Code Element Information.

3. Edit the field list in database table definition Z##_EMPLOYEE. Use code completion to
include structure /LRN/S_ADMIN at the end of the field list.
a) Before the closing curly bracket, enter in and press Ctrl + Space to invoke code
completion.

b) From the suggestion list, choose template includeStructure - Include Structure.

c) Replace the placeholder other_structure_name with Z##S, and press Ctrl +


Space.

d) From the suggestion list, choose Z##S_ADMIN.

© Copyright. All rights reserved. 21


Unit 2: Creating Database Tables

e) Make sure the code now looks like this:

currency_code : waers;
include /lrn/s_admin;
}

4. Display the Code Element Info for your database table and analyze the field list.
a) In the code row starting with define table, place the cursor in the table name and
press F2.

b) Confirm that the five components of structure /LRN/S_ADMIN are now fields of your
database table.

5. Activate all inactive development objects.


a) From the eclipse toolbar, choose Activate inactive ABAP development objects.
Alternatively, press Ctrl + Shift + F3.

b) Choose Select All and Activate.

Task 3: Fill the Table


Fill your new database table with some example data. To do so, create a copy of ABAP
class /LRN/CL_S4D430_CHECK_AND_FILL (suggested name: ZCL_##_CHECK_AND_FILL,
where ## is your group number), adjust the value of constant c_employ_table, and execute
the class as console app.

1. Create a copy of ABAP class /LRN/CL_S4D430_CHECK_AND_FILL, name it


Z##_S4D430_CHECK_AND_FILL and place it in your package ZS4D430_##.
a) In the Project Explorer view, locate the /LRN/CL_S4D430_CHECK_AND_FILL class in
package /LRN/S4D430_EXERCISE and right-click on it to open the context menu.

b) From the context menu, choose Duplicate.

c) Enter the name of your package, the name for the copy and a description. Then choose
Next.

d) Assign the new object to a transport request and choose Finish.

2. Change the value of the c_employ_table constant to the name of your database table.
a) Scroll down to the code row starting with CONSTANTS c_employ_table.

b) In the literal after VALUE, replace ## with your group number.

3. Activate the ABAP class and execute it as a console app. If the console output contains
errors, adjust the definition of your database table until it is compatible with database
table definition /LRN/EMPLOY.
a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the ABAP class as console app.

c) Make sure the console output contains the text Filled table ... for your database table.

© Copyright. All rights reserved. 22


Unit 2
Exercise 4
Handle Changes to a Database Table

You need to make changes to the field list of a database table that already contains data.
Depending on the nature of the change, the system request you to adjust the table.
Template:

/LRN/EMPLOY (Database Table Definition)

Solution:

/LRN/EMPLOY_DEP (Database Table Definition)


/LRN/DEPARTMENT_ID (Data Element)
/LRN/DEPARTMENT_ID (Domain)

Task 1: Copy Template (Optional)


Copy the template database table definition. If you finished the previous exercise, you can
skip this task and continue editing your database table Z##EMPLOY.

1. Copy database table definition /LRN/EMPLOY to your own package (suggested name:
Z##EMPLOY, where ## stands for your group number).

2. Activate the copy.

Task 2: Handle Direct Changes


In the field list of your database table, add a new field (suggested name: DEPARTMENT_ID)
and type it with built in type CHAR and length 40. After activating the table with the new field,
reduce the length of the field to 20 and adjust the table on the database.

1. Before theANNUAL_SALARY field, add a new field (suggested name: DEPARTMENT_ID) and
type it with built in type CHAR and length 40.

2. Activate the database table definition.

3. Display the Dictionary Log for the table.

How did the dictionary tool update the database table?

4. Reduce the length of the new field from 40 to 20.

5. Activate the database table definition.

© Copyright. All rights reserved. 23


Unit 2: Creating Database Tables

Why do you get an activation error this time?

6. Analyze the ABAP log.

7. Use the quick fix to convert the content of your database table.

Task 3: Handle Indirect Changes


Replace the hard-coded type with a new data element (suggested name:
Z##_DEPARTMENT_ID, where ## is your group number) which uses a new domain
((suggested name: Z##_DEPARTMENT_ID). In the domain, use technical type CHAR with a
length of 20. After activating the database table, change the length in the domain to 10. Then
activate and adjust the database table.

1. In your database table definition, replace abap.char(20) with Z##_DEPARTMENT_ID and


use a quick fix to create the new data element.

2. Save the data element. Then use forward navigation to create the domain with technical
type CHAR and a length of 20.

3. Save the domain. Then activate the domain, the data element, and the database table
definition.

4. In your domain for the department ID, reduce the technical length and the display length
from 20 to 10.

5. Try to activate the domain and analyze the messages on the Problems view.

Why do you see error messages?

6. Use the quick fix for the error message Domain ... cannot be activated due to dependent
tables.

Why does this quick fix fail?

7. Use a quick fix to adjust and convert the dependent database table, that is, your database
table Z##EMPLOY.

8. Activate the domain for the department ID.

© Copyright. All rights reserved. 24


Unit 2
Solution 4
Handle Changes to a Database Table

You need to make changes to the field list of a database table that already contains data.
Depending on the nature of the change, the system request you to adjust the table.
Template:

/LRN/EMPLOY (Database Table Definition)

Solution:

/LRN/EMPLOY_DEP (Database Table Definition)


/LRN/DEPARTMENT_ID (Data Element)
/LRN/DEPARTMENT_ID (Domain)

Task 1: Copy Template (Optional)


Copy the template database table definition. If you finished the previous exercise, you can
skip this task and continue editing your database table Z##EMPLOY.

1. Copy database table definition /LRN/EMPLOY to your own package (suggested name:
Z##EMPLOY, where ## stands for your group number).
a) In the Project Explorer view, right-click database table definition /LRN/EMPLOY to open
the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
Z##EMPLOY, where ## stands for your group number.

d) Confirm the transport request and choose Finish.

2. Activate the copy.


a) Press Ctrl + F3 to activate the database table definition.

Task 2: Handle Direct Changes


In the field list of your database table, add a new field (suggested name: DEPARTMENT_ID)
and type it with built in type CHAR and length 40. After activating the table with the new field,
reduce the length of the field to 20 and adjust the table on the database.

1. Before theANNUAL_SALARY field, add a new field (suggested name: DEPARTMENT_ID) and
type it with built in type CHAR and length 40.
a) Adjust the code as follows:

birth_date : z##birth_date;
entry_date : z##entry_date;
department_id : abap.char(40);
@Semantics.amount.currencyCode : 'z##employ.currency_code'
annual_salary : z##annual_salary;
currency_code : waers;

2. Activate the database table definition.

© Copyright. All rights reserved. 25


Unit 2: Creating Database Tables

a) Press Ctrl + F3 to activate the development object.

3. Display the Dictionary Log for the table.

How did the dictionary tool update the database table?

Adjustment of the field catalog (ALTER TABLE).

a) Right-click anywhere in the source code and choose Open With → Dictionary Log.

b) Navigate to the Dictionary Log tab that appears below the editor.

c) Hold down the Ctrl key and click on the row starting with See log.

d) From the toolbar on the Dictionary Log tab, choose Show Search Toolbar.

e) Enter the name of your database table in the Find: field and press Enter.

f) The update strategy is mentioned after the row Adjust table in DB >>>.

4. Reduce the length of the new field from 40 to 20.


a) Adjust the code as follows:

birth_date : z##birth_date;
entry_date : z##entry_date;
department_id : abap.char(20);
@Semantics.amount.currencyCode : 'z##employ.currency_code'
annual_salary : z##annual_salary;
currency_code : waers;

5. Activate the database table definition.

Why do you get an activation error this time?

The dictionary tool is not able to handle the field length reduction with ALTER TABLE. An
explicit conversion of the database table is required.

a) Press Ctrl + F3 to activate the development object.

6. Analyze the ABAP log.


a) On the dialog window with the error message, choose Open ABAP Log to display the
Dictionary Log.

b) On the Dictionary Log tab, hold down the Ctrl key and click on the row starting with
See log.

c) From the toolbar on the Dictionary Log tab, choose Show Search Toolbar.

d) Enter the name of your database table in the Find: field and press Enter.

e) The update strategy is mentioned after the row Adjust table in DB >>>.

7. Use the quick fix to convert the content of your database table.
a) Navigate to the source code of your database table definition.

© Copyright. All rights reserved. 26


Solution 4: Handle Changes to a Database Table

b) In the code row that starts with define table, place the cursor on the table name
and press Ctrl + 1 to invoke the quick fix.

c) From the list of available quick fixes, choose Adjust and activate database table,
convert data.

Task 3: Handle Indirect Changes


Replace the hard-coded type with a new data element (suggested name:
Z##_DEPARTMENT_ID, where ## is your group number) which uses a new domain
((suggested name: Z##_DEPARTMENT_ID). In the domain, use technical type CHAR with a
length of 20. After activating the database table, change the length in the domain to 10. Then
activate and adjust the database table.

1. In your database table definition, replace abap.char(20) with Z##_DEPARTMENT_ID and


use a quick fix to create the new data element.
a) Adjust the code as follows:

birth_date : z##_birth_date;
entry_date : z##_entry_date;
department_id : z##_department_id;
@Semantics.amount.currencyCode : 'z##employ_dep.currency_code'
annual_salary : z##_annual_salary;
currency_code : waers;

b) Click on z##_department_id, and press Ctrl + 1 to open the quick fix menu.

c) From the quick fix menu, double-click Create data element ....

d) Confirm the package and the name, enter a description, for example, Department
Identification, and choose Next.

e) Assign the new object to a transport request and choose Finish.

f) Under Type Name, enter Z##_DEPARTMENT_ID and enter the following field labels:

Field Value
Short Dep.
Medium Department
Long Department ID
Heading Department ID

2. Save the data element. Then use forward navigation to create the domain with technical
type CHAR and a length of 20.
a) Press Ctrl + S to save the data element.

b) Choose the Type Name: label to start creating the domain.

c) Confirm the package and the name, enter a description, for example, Department
Identification, and choose Next.

d) Assign the new object to a transport request and choose Finish.

e) Enter CHAR as Data Type and 20 as Length.

© Copyright. All rights reserved. 27


Unit 2: Creating Database Tables

3. Save the domain. Then activate the domain, the data element, and the database table
definition.
a) Press Ctrl + S to save the domain.

b) Choose Activate inactive ABAP development objects. Alternatively, press Ctrl +


Shift + F3.

c) Choose Select All and then Activate.

4. In your domain for the department ID, reduce the technical length and the display length
from 20 to 10.
a) Navigate to your domain Z##_DEPARTMENT_ID.

b) Change the value in the Length field from 20 to 10.

c) Remove the value in the Output Length field (this will be filled automatically during
activation).

5. Try to activate the domain and analyze the messages on the Problems view.

Why do you see error messages?

The domain cannot be activated due to dependent tables and the table must be
converted.

a) Press Ctrl + F3 to activate the domain.

b) Open the Problems view below the editor to display the error messages.

6. Use the quick fix for the error message Domain ... cannot be activated due to dependent
tables.

Why does this quick fix fail?

It is not possible to adjust the dependent table with ALTER TABLE. A conversion of the
table content is required.

a) In the Problems view, place the cursor on the error message that starts with Domain ...
and press Ctrl + 1 to invoke the quick fix.

b) Choose Finish.

c) From the Previous Result section on the lower right, choose Activation Log to analyze
the activation log.

7. Use a quick fix to adjust and convert the dependent database table, that is, your database
table Z##EMPLOY.
a) Navigate to the source code of your database table definition.

b) In the code row that starts with define table, place the cursor on the table name
and press Ctrl + 1 to invoke the quick fix.

c) From the list of available quick fixes, choose Adjust and activate database table,
convert data.

© Copyright. All rights reserved. 28


Solution 4: Handle Changes to a Database Table

8. Activate the domain for the department ID.


a) Navigate to the definition of your domain for the department ID.

b) Press Ctrl + F3 to activate the development object.

© Copyright. All rights reserved. 29


Unit 3
Exercise 5
Define and Use Dictionary Structures

You need some structure types that you can access in several global classes. You decide to
define structure types in the ABAP Dictionary.

Hint:
Before you define structure types in the ABAP Dictionary, you should investigate
the option to define public structure types in one of the global classes or in a
global interface.

Template:

/LRN/CL_S4D430_TYT_STRUCTURE (Global Class)

Solution:

/LRN/CL_S4D430_TYS_STRUCTURE (Global Class)


/LRN/S_ADDRESS (Structure Type)
/LRN/S_NAME (Structure Type)
/LRN/S_PERSON (Structure Type)

Task 1: Define a Simple Structure


Create a copy of global class /LRN/CL_S4D430_TYT_STRUCTURE (suggested name:
ZCL_##_STRUCTURE, where ## is your group number). Replace structure type st_address
with a dictionary structure (suggested name: Z##S_ADDRESS).

1. Copy class /LRN/CL_S4D430_TYT_STRUCTURE to a class in your own package


(suggested name: ZCL_##_STRUCTURE, where ## is your group number).

2. In the PUBLIC SECTION of the class definition, analyze the definition of type st_address.

3. Create a new dictionary object of type Structure (suggested name: Z##S_ADDRESS).

4. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure. Then replace it with a component street. Use the same
data element as in the st_address type in your global class.

5. Add components for the postal code, the city, and the country. Use the same component
names and data elements as in the st_address type in your global class.

6. Activate the structure type.

7. Return to the source code of your global class. In the implementation of the
IF_OO_ADT_CLASSRUN~MAIN method, replace st_address with your new dictionary
structure type. Make sure there are no syntax errors.

Task 2: Define a Nested Structure


In your global class, remove or comment the public structure type st_person and replace it
with a dictionary structure (suggested name: Z##S_PERSON). For the address, re-use the

© Copyright. All rights reserved. 30


Exercise 5: Define and Use Dictionary Structures

structure type you already created. For the name, use a quick fix to create a second simple
structure with two components (suggested name: Z##S_NAME).

1. Create a new dictionary object of type structure.

2. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure and replace it with a component for the address
(suggested name: address). Type the new component with the structure that you
created in the previous task (Z##S_ADDRESS).

3. Add another component for the name of the person (suggested name: Name). Enter
Z##S_NAME as the name of the component type.

Note:
This structure type does not yet exist. You create it in the next step.

4. Save the structure type. Then use a quick fix to create structure type Z##S_NAME.

5. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure and replace it with a component for the first name
(suggested name: first_name) and a component for the last name (suggested name:
last_name). Use suitable data elements from the /DMO/ name space as components
types.

6. Save the structure type. Then activate all inactive development objects.

7. Return to the source code of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of the types st_name and st_person.

8. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace st_person


with your new dictionary structure type. Make sure there are no syntax errors.

Task 3: Define Named Includes


In your global class, remove or comment public structure type st_person_inc and replace it
with a dictionary structure (suggested name: Z##S_PERSON_INC). Instead of structured
components NAME and ADDRESS define named includes of the same name.

1. Create a copy of your nested dictionary structure (suggested name: Z##S_PERSON_INC,


where ## is your group number).

2. Turn structured component name into a named include.

3. Repeat this for structured component address.

4. Activate the structure type.

5. Return to the source code of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of type st_person_inc.

6. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace


st_person_inc with your new dictionary structure type. Make sure both alternatives for
accessing the components work.

7. Activate and debug the class as a console app. Analyze the content of the data objects
address, person, and person2.

© Copyright. All rights reserved. 31


Unit 3
Solution 5
Define and Use Dictionary Structures

You need some structure types that you can access in several global classes. You decide to
define structure types in the ABAP Dictionary.

Hint:
Before you define structure types in the ABAP Dictionary, you should investigate
the option to define public structure types in one of the global classes or in a
global interface.

Template:

/LRN/CL_S4D430_TYT_STRUCTURE (Global Class)

Solution:

/LRN/CL_S4D430_TYS_STRUCTURE (Global Class)


/LRN/S_ADDRESS (Structure Type)
/LRN/S_NAME (Structure Type)
/LRN/S_PERSON (Structure Type)

Task 1: Define a Simple Structure


Create a copy of global class /LRN/CL_S4D430_TYT_STRUCTURE (suggested name:
ZCL_##_STRUCTURE, where ## is your group number). Replace structure type st_address
with a dictionary structure (suggested name: Z##S_ADDRESS).

1. Copy class /LRN/CL_S4D430_TYT_STRUCTURE to a class in your own package


(suggested name: ZCL_##_STRUCTURE, where ## is your group number).
a) In the Project Explorer view, right-click class /LRN/CL_S4D430_TYT_STRUCTURE to
open the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
ZCL_##_STRUCTURE, where ## stands for your group number.

d) Adjust the description and choose Next.

e) Confirm the transport request and choose Finish.

2. In the PUBLIC SECTION of the class definition, analyze the definition of type st_address.
a) Perform this step as you have done earlier.

3. Create a new dictionary object of type Structure (suggested name: Z##S_ADDRESS).


a) In the Project Explorer view, expand your package and open the context menu on
subnode Dictionary.

© Copyright. All rights reserved. 32


Solution 5: Define and Use Dictionary Structures

b) Choose New → Structure.

c) Confirm the package, enter the name Z##S_ADDRESS and the description Address,
then choose Next.

d) Assign the new object to a transport request and choose Finish.

4. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure. Then replace it with a component street. Use the same
data element as in the st_address type in your global class.
a) Adjust the code as follows:

define structure z##s_address {


street : /dmo/street;

5. Add components for the postal code, the city, and the country. Use the same component
names and data elements as in the st_address type in your global class.
a) Adjust the code as follows:

define structure z##s_address {


street : /dmo/street;
postal_code : /dmo/postal_code;
city : /dmo/city;
country : land1;

6. Activate the structure type.


a) Press Ctrl + F3 to activate the development object.

7. Return to the source code of your global class. In the implementation of the
IF_OO_ADT_CLASSRUN~MAIN method, replace st_address with your new dictionary
structure type. Make sure there are no syntax errors.
a) Adjust the code as follows:

* Task 1
*****************************************************************
* DATA address TYPE st_address.
DATA address TYPE z##s_address.

address-street = 'Dietmar-Hopp-Allee 16'.


address-postal_code = '69190'.
address-city = 'Walldorf'.
address-country = 'DE'.

Task 2: Define a Nested Structure


In your global class, remove or comment the public structure type st_person and replace it
with a dictionary structure (suggested name: Z##S_PERSON). For the address, re-use the
structure type you already created. For the name, use a quick fix to create a second simple
structure with two components (suggested name: Z##S_NAME).

1. Create a new dictionary object of type structure.


a) In the Project Explorer view, expand your package and open the context menu on the
Dictionary subnode .

© Copyright. All rights reserved. 33


Unit 3: Defining Global Data Types

b) Choose New → Structure.

c) Confirm the package, enter the name Z##S_PERSON and the description Person
(Name and Address), then choose Next.

d) Assign the new object to a transport request and choose Finish.

2. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure and replace it with a component for the address
(suggested name: address). Type the new component with the structure that you
created in the previous task (Z##S_ADDRESS).
a) Adjust the code as follows:

define structure z##s_person {


address : z##s_address;

3. Add another component for the name of the person (suggested name: Name). Enter
Z##S_NAME as the name of the component type.

Note:
This structure type does not yet exist. You create it in the next step.

a) Adjust the code as follows:

define structure z##s_person {


name : z##s_name;
address : z##s_address;

4. Save the structure type. Then use a quick fix to create structure type Z##S_NAME.
a) Press Ctrl + S to save the development object.

b) Left-click on the error icon next to the code line you just added and choose Create
Dictionary Structure ....

c) Enter the description Name and choose Next.

d) Assign the structure to a transport request and choose Finish.

5. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure and replace it with a component for the first name
(suggested name: first_name) and a component for the last name (suggested name:
last_name). Use suitable data elements from the /DMO/ name space as components
types.
a) Adjust the code as follows:

define structure z##s_name {


first_name : /dmo/first_name;
last_name : /dmo/last_name;

6. Save the structure type. Then activate all inactive development objects.

© Copyright. All rights reserved. 34


Solution 5: Define and Use Dictionary Structures

a) Press Ctrl + S to save the development object.

b) From the eclipse toolbar, choose Activate inactive ABAP development objects.
Alternatively, press Ctrl + Shift + F3.

c) Choose Select All and Activate.

7. Return to the source code of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of the types st_name and st_person.
a) Perform this step as before.

8. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace st_person


with your new dictionary structure type. Make sure there are no syntax errors.
a) Adjust the code as follows:

* Task 2
***********************************************************
* DATA person TYPE st_person.
DATA person TYPE z##s_person.

person-name-first_name = 'Dictionary'.
person-name-last_name = 'ABAP'.
person-address-street = 'Dietmar-Hopp-Allee 16'.
person-address-postal_code = '69190'.
person-address-city = 'Walldorf'.
person-address-country = 'DE'.

Task 3: Define Named Includes


In your global class, remove or comment public structure type st_person_inc and replace it
with a dictionary structure (suggested name: Z##S_PERSON_INC). Instead of structured
components NAME and ADDRESS define named includes of the same name.

1. Create a copy of your nested dictionary structure (suggested name: Z##S_PERSON_INC,


where ## is your group number).
a) In the Project Explorer view, expand your package and subnode
Dictionary → Structure.

b) Open the context menu on structure type Z##S_PERSON and choose Duplicate.

c) Enter the name Z##S_PERSON_INC and choose Next.

d) Assign the new development object to a transport request and choose Finish.

2. Turn structured component name into a named include.


a) After the colon that separates the component name and the component type, insert
keyword INCLUDE.

3. Repeat this for structured component address.


a) Make sure the structure type now looks like this:

define structure z##s_person_inc {


name : include z##s_name;
address : include z##s_address;
}

4. Activate the structure type.


a) Press Ctrl + F3 to activate the development object.

© Copyright. All rights reserved. 35


Unit 3: Defining Global Data Types

5. Return to the source code of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of type st_person_inc.
a) Perform this step as before.

6. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace


st_person_inc with your new dictionary structure type. Make sure both alternatives for
accessing the components work.
a) Adjust the code as follows:

* Task 3
**********************************************************************
* DATA person2 TYPE st_person_inc.
DATA person2 TYPE z##s_person_inc.

person2-name-first_name = 'Dictionary'.
person2-name-last_name = 'ABAP'.
person2-address-street = 'Dietmar-Hopp-Allee 16'.
person2-address-postal_code = '69190'.
person2-address-city = 'Walldorf'.
person2-address-country = 'DE'.
* or -------------------------------------------------------
person2-first_name = 'Dictionary'.
person2-last_name = 'ABAP'.
person2-street = 'Dietmar-Hopp-Allee 16'.
person2-postal_code = '69190'.
person2-city = 'Walldorf'.
person2-country = 'DE'.

7. Activate and debug the class as a console app. Analyze the content of the data objects
address, person, and person2.
a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the class as console app.

© Copyright. All rights reserved. 36


Unit 3
Exercise 6
Define and Use Dictionary Table Types

You need some table types that you can access in several global classes. You decide to define
table types in the ABAP Dictionary.

Hint:
Before you define table types in the ABAP Dictionary, you should investigate the
option to define public table types in one of the global classes or in a global
interface.

Template:

/LRN/CL_S4D430_TYT_TABLE_TYPE (Global Class)

Solution:

/LRN/CL_S4D430_TYS_TABLE_TYPE (Global Class)


/LRN/T_ADDRESSES (Table Type)
/LRN/S_PERSON_DEEP (Structure Type)
/LRN/T_PERSONS (Table Type)

Task 1: Define a Table Type


Create a copy of global class /LRN/CL_S4D430_TYT_TABLE_TYPE (suggested name:
ZCL_##_TABLE_TYPE, where ## is your group number). Replace public table type
tt_addresses with a dictionary table type (suggested name: Z##T_ADDRESSES).

1. Copy class /LRN/CL_S4D430_TYT_TABLE_TYPE to a class in your own package


(suggested name: ZCL_##_TABLE_TYPE, where ## stands for your group number).

2. In the PUBLIC SECTION of the class definition, analyze the definition of type
tt_addresses.

3. Create a new dictionary object of type Table Type (suggested name: Z##T_ADDRESSES).

4. Specify your structure type Z##S_ADDRESS as row type.

Note:
If you have not finished the previous exercise, you can use the structure
type /LRN/S_ADDRESS, instead.

5. Specify the same table kind and key definition as in table type tt_addresses.

6. Activate the table type.

7. Return to the source ode of your global class. In the implementation of the
IF_OO_ADT_CLASSRUN~MAIN method, replace tt_addresses with your new dictionary
structure type. Make sure there are no syntax errors.

© Copyright. All rights reserved. 37


Unit 3: Defining Global Data Types

Task 2: Define a Deep Structure


In your global class, remove or comment public structure type st_person_deep and replace
it with a dictionary structure (suggested name: Z##S_PERSON_DEEP). For the addresses, re-
use the table type you already created.

1. Create a new dictionary object of type Structure.

2. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure and replace it with a component for the first_name
(suggested name:first_name), the last name (suggested name: last_name).

3. Add another component for the addresses of the person (suggested name: addresses).
As type, use the table type you created in the previous task.

4. Activate the structure type.

5. Return to the source code of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of type st_person_deep.

6. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace


st_person_deep with your new dictionary structure type. Make sure there are no syntax
errors.

Task 3: Define a Nested Table Type


In your global class, remove or comment public table type tt_persons and replace it with a
dictionary table type (suggested name: Z##T_PERSONS). As its row type, use the deep
structure type you created in the previous task.

1. Create a new dictionary object of type Table Type.

2. Specify your structure type Z##S_PERSON_DEEP as the row type.

3. Specify the same table kind and key definition as in table type tt_persons.

4. Activate the table type.

5. Return to the source ode of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of type tt_persons .

6. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace tt_persons


with your new dictionary table type. Make sure there are no syntax errors.

7. Activate and debug the class as a console app. Analyze the content of the data objects
addresses, person, and persons.

© Copyright. All rights reserved. 38


Unit 3
Solution 6
Define and Use Dictionary Table Types

You need some table types that you can access in several global classes. You decide to define
table types in the ABAP Dictionary.

Hint:
Before you define table types in the ABAP Dictionary, you should investigate the
option to define public table types in one of the global classes or in a global
interface.

Template:

/LRN/CL_S4D430_TYT_TABLE_TYPE (Global Class)

Solution:

/LRN/CL_S4D430_TYS_TABLE_TYPE (Global Class)


/LRN/T_ADDRESSES (Table Type)
/LRN/S_PERSON_DEEP (Structure Type)
/LRN/T_PERSONS (Table Type)

Task 1: Define a Table Type


Create a copy of global class /LRN/CL_S4D430_TYT_TABLE_TYPE (suggested name:
ZCL_##_TABLE_TYPE, where ## is your group number). Replace public table type
tt_addresses with a dictionary table type (suggested name: Z##T_ADDRESSES).

1. Copy class /LRN/CL_S4D430_TYT_TABLE_TYPE to a class in your own package


(suggested name: ZCL_##_TABLE_TYPE, where ## stands for your group number).
a) In the Project Explorer view, right-click class /LRN/CL_S4D430_TYT_TABLE_TYPE to
open the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
ZCL_##_TABLE_TYPE, where ## stands for your group number.

d) Adjust the description and choose Next.

e) Confirm the transport request and choose Finish.

2. In the PUBLIC SECTION of the class definition, analyze the definition of type
tt_addresses.
a) Perform this step as before.

3. Create a new dictionary object of type Table Type (suggested name: Z##T_ADDRESSES).
a) In the Project Explorer view, expand your package and open the context menu on
subnode Dictionary.

© Copyright. All rights reserved. 39


Unit 3: Defining Global Data Types

b) Choose New → Table Type.

c) Confirm the package, enter the name Z##T_ADDRESSES and the description
Addresses, then choose Next.

d) Assign the new object to a transport request and choose Finish.

4. Specify your structure type Z##S_ADDRESS as row type.

Note:
If you have not finished the previous exercise, you can use the structure
type /LRN/S_ADDRESS, instead.

a) In the Row Type section, change the Category from Predefined Type to Dictionary.

b) In the Type Name field, enter /LRN/S_ADDRESS or Z##S_ADDRESS.

5. Specify the same table kind and key definition as in table type tt_addresses.
a) In the Initialization and Access section, change the table kind from Standard Table to
Sorted Table.

b) In the Key Overview section, select <Primary Key>.

c) In the Primary Key Details section, change the Key Definition from Standard Key to
Key Components.

d) In the Key Components section, use code completion to enter COUNTRY and CITY as
key fields.

6. Activate the table type.


a) Press Ctrl + F3 to activate the development object.

7. Return to the source ode of your global class. In the implementation of the
IF_OO_ADT_CLASSRUN~MAIN method, replace tt_addresses with your new dictionary
structure type. Make sure there are no syntax errors.
a) Adjust the code as follows:

* Task 1
**********************************************************************
* DATA addresses TYPE tt_addresses.
DATA addresses TYPE z##t_addresses.

addresses =
VALUE #(
( street = 'Dietmar-Hopp-Allee 16'
postal_code = '69190'
city = 'Walldorf'
country = 'DE'
)
( street = '3999 West Chester Pike'
postal_code = '19073'
city = 'Newtown Square, PA'
country = 'US'
)
).

© Copyright. All rights reserved. 40


Solution 6: Define and Use Dictionary Table Types

Task 2: Define a Deep Structure


In your global class, remove or comment public structure type st_person_deep and replace
it with a dictionary structure (suggested name: Z##S_PERSON_DEEP). For the addresses, re-
use the table type you already created.

1. Create a new dictionary object of type Structure.


a) In the Project Explorer view, expand your package and open the context menu on
subnode Dictionary.

b) Choose New → Structure.

c) Confirm the package, enter the name Z##S_PERSON_DEEP and the description
Person (Name and Several Addresses), then choose Next.

d) Assign the new object to a transport request and choose Finish.

2. Remove the placeholder component_to_be_Changed : abap.string(0); from the


component list of the structure and replace it with a component for the first_name
(suggested name:first_name), the last name (suggested name: last_name).
a) Adjust the code as follows:

define structure z##s_person_deep {


first_name : /dmo/first_name;
last_name : /dmo/last_name;

3. Add another component for the addresses of the person (suggested name: addresses).
As type, use the table type you created in the previous task.
a) Adjust the code as follows:

define structure z##s_person_deep {


first_name : /dmo/first_name;
last_name : /dmo/last_name;
addreses : z##t_addresses;

4. Activate the structure type.


a) Press Ctrl + F3 to activate the development object.

5. Return to the source code of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of type st_person_deep.
a) Perform this step as before.

6. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace


st_person_deep with your new dictionary structure type. Make sure there are no syntax
errors.
a) Adjust the code as follows:

* Task 2
**********************************************************************
* DATA person TYPE st_person_deep.
DATA person TYPE /lrn/s_person_deep.

© Copyright. All rights reserved. 41


Unit 3: Defining Global Data Types

person-first_name = 'Dictionary'.
person-last_name = 'ABAP'.
person-addresses = addresses.

Task 3: Define a Nested Table Type


In your global class, remove or comment public table type tt_persons and replace it with a
dictionary table type (suggested name: Z##T_PERSONS). As its row type, use the deep
structure type you created in the previous task.

1. Create a new dictionary object of type Table Type.


a) In the Project Explorer view, expand your package and open the context menu on
subnode Dictionary.

b) Choose New → Table Type.

c) Confirm the package, enter the name Z##T_PERSONS and the description Persons
(With Name and Addresses), then choose Next.

d) Assign the new object to a transport request and choose Finish.

2. Specify your structure type Z##S_PERSON_DEEP as the row type.


a) In the Row Type section, change the Category from Predefined Type to Dictionary.

b) In the Type Name field, enter Z##S_PERSON_DEEP.

3. Specify the same table kind and key definition as in table type tt_persons.
a) In the Initialization and Access section, change the table kind from Standard table
to Hashed Table.

b) In the Key Overview section, select <Primary Key>.

c) In the Primary Key Details section, change the Key Definition from Standard Key to
Key Components and the Key Category from Non-Unique to Unique.

d) In the Key Components section, specify the key fields LAST_NAME and FIRST_NAME.

4. Activate the table type.


a) Press Ctrl + F3 to activate the development object.

5. Return to the source ode of your global class. In the PUBLIC SECTION of the class
definition, remove or comment the definition of type tt_persons .
a) Perform this step as before.

6. In the implementation of the IF_OO_ADT_CLASSRUN~MAIN method, replace tt_persons


with your new dictionary table type. Make sure there are no syntax errors.
a) Adjust the code as follows:

* Task 3
**********************************************************************
* DATA persons TYPE tt_persons.
DATA persons TYPE /lrn/t_persons.

persons =
VALUE #(
( person )

© Copyright. All rights reserved. 42


Solution 6: Define and Use Dictionary Table Types

(
first_name = 'CDS'
last_name = 'ABAP'
addresses =
VALUE #(
( street = 'SAP-Allee 29'
postal_code = '68789'
city = 'St.Leon-Rot'
country = 'DE'
)
( street = '35 rue d''Alsace'
postal_code = '92300'
city = 'Levallois-Perret'
country = 'FR'
)
( street = 'Bedfont Road'
postal_code = 'TW14 8HD'
city = 'Feltham'
country = 'GB'
)
)
)
).

7. Activate and debug the class as a console app. Analyze the content of the data objects
addresses, person, and persons.
a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the class as console app.

© Copyright. All rights reserved. 43


Unit 4
Exercise 7
Define a Basic CDS View

You want to decouple the data access and the table definition. To do so, you define a CDS
view entity that read
Template:

n.a.

Solution:

/LRN/R_EMPLOYEE (Data Definition)

For this exercise, you need the database table for employee data that you created and filled in
a previous exercise (suggested name was: Z##EMPLOY, where ## is your group number). If
you have not finished that exercise, create a copy of the database table /LRN/EMPLOY_DEP .

Task 1: Define a CDS View Entity


Define a new CDS view entity that reads from your database table with employee data
(suggested name: Z##_R_Employee, where ## is your group number). Use a template that
adds all table fields to the element list of the view (except for the client field, the annual salary
and the currency code) and that takes over the key definition from the database table.

1. In your own package, create a new data definition (suggested name: Z##_R_EMPLOYEE,
where ## is your group number). Specify your database table as Referenced Object and
choose the Define View Entity template to generate the definition statement, some
standard annotations and the element list.

2. For the time being, comment elements AnnualSalary and CurrencyCode.

3. Apply source code formatting.

4. Activate the data definition.

Task 2: Analyze the CDS View Entity


Analyze the technical implementation of the CDS view entity in the database and test the
result.

1. Display the SQL statement with which the technical representation of the view entity is
created in the database.

Do the CDS view entity and the representation in the database have the same fields?

© Copyright. All rights reserved. 44


Exercise 7: Define a Basic CDS View

Does the representation in the database contain a WHERE clause?

2. Open the Data Preview for your CDS view.

© Copyright. All rights reserved. 45


Unit 4
Solution 7
Define a Basic CDS View

You want to decouple the data access and the table definition. To do so, you define a CDS
view entity that read
Template:

n.a.

Solution:

/LRN/R_EMPLOYEE (Data Definition)

For this exercise, you need the database table for employee data that you created and filled in
a previous exercise (suggested name was: Z##EMPLOY, where ## is your group number). If
you have not finished that exercise, create a copy of the database table /LRN/EMPLOY_DEP .

Task 1: Define a CDS View Entity


Define a new CDS view entity that reads from your database table with employee data
(suggested name: Z##_R_Employee, where ## is your group number). Use a template that
adds all table fields to the element list of the view (except for the client field, the annual salary
and the currency code) and that takes over the key definition from the database table.

1. In your own package, create a new data definition (suggested name: Z##_R_EMPLOYEE,
where ## is your group number). Specify your database table as Referenced Object and
choose the Define View Entity template to generate the definition statement, some
standard annotations and the element list.
a) In the Project Explorer view, right-click your database table definition Z##EMPLOY to
open the context menu.

b) From the context menu, choose New Data Definition.

c) Confirm that the Package field contains the name of your package and that the
Referenced Object field contains the name of your database table definition.

d) In the Name field, enter the name for the CDS view entity (Z##_R_Employee, where
## is your group number).

e) Enter Employee (Entity) in the Description field and choose Next.

f) Confirm the transport request and choose Next.

Caution:
Make sure you don't choose Finish yet. If you do, you are not able to
choose the template that you want to use.

g) From the list of Templates, choose Define View Entity, then choose Finish.

2. For the time being, comment elements AnnualSalary and CurrencyCode.

© Copyright. All rights reserved. 46


Solution 7: Define a Basic CDS View

a) Select both code rows and press Ctrl + < to add two slash signs (/) at the beginning
of each row.

3. Apply source code formatting.


a) From the eclipse menu, choose Source Code → Format. Alternatively, choose Shift
+ F1.

4. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

Task 2: Analyze the CDS View Entity


Analyze the technical implementation of the CDS view entity in the database and test the
result.

1. Display the SQL statement with which the technical representation of the view entity is
created in the database.

Do the CDS view entity and the representation in the database have the same fields?

No, the representation in the database also contains the client field that is not required in
the CDS view entity.

Does the representation in the database contain a WHERE clause?

Yes, the tool adds a filter for the current client.

a) Right-click anywhere in the source code of the data definition and choose Show SQL
CREATE Statement.

2. Open the Data Preview for your CDS view.


a) Right-click anywhere in the source code of the data definition and choose Open
With → Data Preview. Alternatively, place the cursor anywhere in the source code of
the data definition and press F8.

© Copyright. All rights reserved. 47


Unit 4
Exercise 8
Use Annotations in Data Definitions

You want to enrich your CDS view entity with metadata. In a first step, you define and
maintain ABAP annotations for both, the entire view and individual view elements.
Template:

/LRN/R_EMPLOYEE (Data Definition)

Solution:

/LRN/R_EMPLOYEE_ANN (Data Definition)

Task 1: Copy Template (Optional)


Copy the template data definition. If you have finished the previous exercise, you can skip this
task and continue editing your data definition Z##_EMPLOYEE.

1. Copy the /LRN/R_EMPLOYEE data definition to a data definition in your own package
(suggested name: Z##_EMPLOYEE, where ## stands for your group number).

2. Activate the copy.

Task 2: Maintain View Annotations


In your data definition, maintain the view annotations. Add an annotation that can be used to
restrict data preview for a CDS view entity and adjust the values of the
ObjectModel.usageType annotations.

1. At the beginning of the data definition, use code-completion to add annotation


@ABAPCatalog.dataMaintenance with its default value.

2. Group the entity annotations that start with @ABAPCatalog.

Hint:
You can use the syntax of the @ObjectModel.usageType annotation group as
a blueprint.

3. Display the documentation for the @ObjectModel.usageType annotations and maintain


the values.

Note:
You should make sure that the annotation values fit the technical table settings
of your database table for employee data.

Task 3: Maintain Element Annotations


In your data definition, add the mandatory element annotation to establish the link between
the annual salary and the currency code. Use the Active Annotations view to analyze the
element labels that are derived from data elements and provide an alternative label for the
CurrencyCode element.

© Copyright. All rights reserved. 48


Exercise 8: Use Annotations in Data Definitions

1. In the element list, un-comment the AnnualSalary element and the CurrencyCode
element.

2. Add the mandatory element annotation that identifies the AnnualSalary element as an
amount and links it to theCurrencyCode element.

Note:
You might need to add this annotation manually with the support of code
completion. At the time of writing, the editor for data definitions does not offer
a quick fix for this error. (The editor for database table definitions does.)

3. Open the Active Annotations View and analyze the values of the EndUserText.Label
annotation for the different view elements.

Where do the text for the labels come from?

What is the value of annotation @EndUserText.label for view element CurrencyCode?

4. Return to the source code of your data definition and add element annotation
EndUSerText.label for view element CurrencyCode. Change the label from Currency to
Currency Key.

5. Activate the data definition.

6. Return to the Active Annotations view, refresh the display, and confirm that now the new
label is active.

Hint:
To find a specific annotation more easily, you can first collapse the entire tree
and then expand the element and main annotation you are interested in.

© Copyright. All rights reserved. 49


Unit 4
Solution 8
Use Annotations in Data Definitions

You want to enrich your CDS view entity with metadata. In a first step, you define and
maintain ABAP annotations for both, the entire view and individual view elements.
Template:

/LRN/R_EMPLOYEE (Data Definition)

Solution:

/LRN/R_EMPLOYEE_ANN (Data Definition)

Task 1: Copy Template (Optional)


Copy the template data definition. If you have finished the previous exercise, you can skip this
task and continue editing your data definition Z##_EMPLOYEE.

1. Copy the /LRN/R_EMPLOYEE data definition to a data definition in your own package
(suggested name: Z##_EMPLOYEE, where ## stands for your group number).
a) In the Project Explorer view, right-click the /LRN/R_EMPLOYEE data definition to open
the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
for the CDS view entity (Z##_Employee, where ## stands for your group number).

d) Adjust the description and choose Next.

e) Confirm the transport request and choose Finish.

2. Activate the copy.


a) Press Ctrl + F3 to activate the data definition.

Task 2: Maintain View Annotations


In your data definition, maintain the view annotations. Add an annotation that can be used to
restrict data preview for a CDS view entity and adjust the values of the
ObjectModel.usageType annotations.

1. At the beginning of the data definition, use code-completion to add annotation


@ABAPCatalog.dataMaintenance with its default value.
a) Place the cursor at the beginning of the first code row and press Enter to insert a new
empty row.

b) In the empty row, enter @A and press Ctrl + Space to invoke code-completion.

c) From the suggestion list, choose @ABAPCatalog: { } (annotation.

d) Enter a period sign (.) and press Ctrl + Space again.

e) Choose dataMaintenance: #RESTRICTED (annotation).

© Copyright. All rights reserved. 50


Solution 8: Use Annotations in Data Definitions

2. Group the entity annotations that start with @ABAPCatalog.

Hint:
You can use the syntax of the @ObjectModel.usageType annotation group as
a blueprint.

a) Adjust the code as follows:

// @AbapCatalog.dataMaintenance: #RESTRICTED
// @AbapCatalog.viewEnhancementCategory: [#NONE]
@AbapCatalog: {
dataMaintenance: #RESTRICTED,
viewEnhancementCategory: [#NONE]
}
@AccessControl.authorizationCheck: #NOT_REQUIRED

3. Display the documentation for the @ObjectModel.usageType annotations and maintain


the values.

Note:
You should make sure that the annotation values fit the technical table settings
of your database table for employee data.

a) Place the cursor on @ObjectModeland press F1 to open the ABAP language help.

b) On the ABAP Language Help view that opens below the editor, choose@ObjectModel,
CDS View annotations, View Entity.

c) For the serviceQuality annotation, choose #D because the view does not support
transactional processing.

d) For the sizeCategory annotation, choose #M because we expect less than 100,000 data
sets.

e) For the dataClass annotation, choose #MASTER because employee data are maser
data.

Task 3: Maintain Element Annotations


In your data definition, add the mandatory element annotation to establish the link between
the annual salary and the currency code. Use the Active Annotations view to analyze the
element labels that are derived from data elements and provide an alternative label for the
CurrencyCode element.

1. In the element list, un-comment the AnnualSalary element and the CurrencyCode
element.
a) Select both code rows and press Ctrl + Shift + < to remove the comment signs
from the beginning of each row.

2. Add the mandatory element annotation that identifies the AnnualSalary element as an
amount and links it to theCurrencyCode element.

© Copyright. All rights reserved. 51


Unit 4: Defining Basic CDS Views

Note:
You might need to add this annotation manually with the support of code
completion. At the time of writing, the editor for data definitions does not offer
a quick fix for this error. (The editor for database table definitions does.)

a) Adjust the code as follows:

department_id as DepartmentId,
@Semantics.amount.currencyCode: 'CurrencyCode'
annual_salary as AnnualSalary,
currency_code as CurrencyCode,

3. Open the Active Annotations View and analyze the values of the EndUserText.Label
annotation for the different view elements.

Where do the text for the labels come from?

The end user texts are derived from the data elements that are used as types for the
corresponding database table fields.

What is the value of annotation @EndUserText.label for view element CurrencyCode?

The value is Currency.

a) Right-click anywhere in the source code of the data definition and choose Open With
→ Active Annotations.
Result
The Active Annotations view appears as a new tab below the editor view. The source of
the end user texts is listed in the Origin Data Type column.

4. Return to the source code of your data definition and add element annotation
EndUSerText.label for view element CurrencyCode. Change the label from Currency to
Currency Key.
a) Adjust the code as folows:

@Semantics.amount.currencyCode: 'CurrencyCode'
annual_salary as AnnualSalary,
@EndUserText.label: 'Currency Key'
currency_code as CurrencyCode,

5. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

6. Return to the Active Annotations view, refresh the display, and confirm that now the new
label is active.

© Copyright. All rights reserved. 52


Solution 8: Use Annotations in Data Definitions

Hint:
To find a specific annotation more easily, you can first collapse the entire tree
and then expand the element and main annotation you are interested in.

a) From the toolbar on the Active Annotations view, choose Refresh (F5). Alternatively,
place the cursor anywhere on the view and press F5.

b) From the toolbar on the Active Annotations view, choose Collapse All.

c) Expand Z##_R_EMPLOYEE → CurrencyCode → @EndUserText.

© Copyright. All rights reserved. 53


Unit 4
Exercise 9
Define a View on a View

You want to separate the basic definition of your data model from its specific usage
(consumption). To do so, you build a new CDS view entity on top of your existing data model
entity.
Template:

n.a.

Solution:

/LRN/C_EMPLOYEE_ANN (Data Definition)

For this exercise, you need the view entity for employee data that you created and annotated
in previous exercises (suggested name was: Z##_R_Employee, where ## is your group
number). If you have not finished the previous exercise, create a copy of data definition /LRN/
R_EMPLOYEE_ANN.

Task 1: Define a CDS View Entity


Define a new CDS view entity that reads from your CDS view entity for employee data
(suggested name: Z##_C_Employee, where ## is your group number). Use a template that
adds all view elements of entity Z##_R_Employee to the element list of the new view and
takes over the key definition from the base view.

1. In your own package, create a new data definition (suggested name: Z##_C_EMPLOYEE,
where ## is your group number). Specify your existing view entity as Referenced Object
and choose the Define View Entity template to generate the definition statement, some
standard annotations and the element list.

2. Adjust the @ObjectModel.usageType annotations. Use the same values as in the base
view.

3. Apply source code formatting.

Task 2: Propagate Annotations


Enable the propagation of element annotations in your new view and analyze the result in the
Active Annotations view. Then disable the propagation again and specify the mandatory
element annotation directly.

1. In your new data definition, enable the propagation of element annotations.

2. Activate the data definition.

3. Open the Active Annotations View and analyze the element annotation values for view
elements AnnualSalary and CurrencyCode .

© Copyright. All rights reserved. 54


Exercise 9: Define a View on a View

Where does the value for the @Semantics.amount.CurrencyCode annotation come from?

4. In your new data definition, disable the propagation of element annotations again.

5. Solve the syntax error by adding the mandatory element annotation directly to the
AnnualSalary view element.

6. Activate the data definition.

© Copyright. All rights reserved. 55


Unit 4
Solution 9
Define a View on a View

You want to separate the basic definition of your data model from its specific usage
(consumption). To do so, you build a new CDS view entity on top of your existing data model
entity.
Template:

n.a.

Solution:

/LRN/C_EMPLOYEE_ANN (Data Definition)

For this exercise, you need the view entity for employee data that you created and annotated
in previous exercises (suggested name was: Z##_R_Employee, where ## is your group
number). If you have not finished the previous exercise, create a copy of data definition /LRN/
R_EMPLOYEE_ANN.

Task 1: Define a CDS View Entity


Define a new CDS view entity that reads from your CDS view entity for employee data
(suggested name: Z##_C_Employee, where ## is your group number). Use a template that
adds all view elements of entity Z##_R_Employee to the element list of the new view and
takes over the key definition from the base view.

1. In your own package, create a new data definition (suggested name: Z##_C_EMPLOYEE,
where ## is your group number). Specify your existing view entity as Referenced Object
and choose the Define View Entity template to generate the definition statement, some
standard annotations and the element list.
a) In the Project Explorer view, right-click your existing data definition Z##_R_EMPLOYEE
to open the context menu.

b) From the context menu, choose New Data Definition.

c) Confirm that the Package field contains the name of your package and that the
Referenced Object field contains the name of your data definition.

d) In the Name field, enter the name for the CDS view entity (Z##_C_Employee, where
## is your group number).

e) Enter Employee (Consumption) in the Description field and choose Next.

f) Confirm the transport request and choose Next.

Caution:
Make sure you don't choose Finish yet. If you do, you are not able to
choose the template that you want to use.

g) From the list of Templates, choose Define View Entity, then choose Finish.

© Copyright. All rights reserved. 56


Solution 9: Define a View on a View

2. Adjust the @ObjectModel.usageType annotations. Use the same values as in the base
view.
a) Adjust the code as follows:

@ObjectModel.usageType:{
serviceQuality: #D,
sizeCategory: #M,
dataClass: #MASTER
}

3. Apply source code formatting.


a) From the eclipse menu, choose Source Code → Format. Alternatively, choose Shift
+ F1.

Task 2: Propagate Annotations


Enable the propagation of element annotations in your new view and analyze the result in the
Active Annotations view. Then disable the propagation again and specify the mandatory
element annotation directly.

1. In your new data definition, enable the propagation of element annotations.


a) Change the value of annotation @Metadata.ignorePropagatedAnnotations from true
to false.

2. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

3. Open the Active Annotations View and analyze the element annotation values for view
elements AnnualSalary and CurrencyCode .

Where does the value for the @Semantics.amount.CurrencyCode annotation come from?

It is taken over from the base view entity Z##_R_Employee.

a) Right-click anywhere in the source code of the data definition and choose Open With
→ Active Annotations.

b) The Active Annotations view appears as a new tab below the editor view.

c) From the toolbar on the Active Annotations view, choose Collapse All.

d) Expand Z##_C_EMPLOYEE → AnnualSalary → @Semantics → Amount.

4. In your new data definition, disable the propagation of element annotations again.
a) Change the value of annotation @Metadata.ignorePropagatedAnnotations back to
true.

5. Solve the syntax error by adding the mandatory element annotation directly to the
AnnualSalary view element.
a) Adjust the code as follows:

DepartmentId,
@Semantics.amount.currencyCode: 'CurrencyCode'
AnnualSalary,
CurrencyCode,

© Copyright. All rights reserved. 57


Unit 4: Defining Basic CDS Views

6. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

© Copyright. All rights reserved. 58


Unit 5
Exercise 10
Define a Foreign Key Relationship

You define a second database table for departments and define the foreign key relationship
between departments and employees.
Template:

/LRN/EMPLOY_DEP (Database Table Definition)

Solution:

/LRN/DEPMENT_REL (Database Table Definition)


/LRN/EMPLOY_REL (Database Table Definition)
/LRN/DEPMENT_HEAD (Data Element)
/LRN/DEPMENT_ASSISTANT (Data Element)

For this exercise, you need the database table for employee data that you created and filled in
a previous exercise (suggested name was: Z##EMPLOY, where ## is your group number). If
you have not finished that exercise, create a copy of database table /LRN/EMPLOY_DEP.

Task 1: Define a Database Table for Department Data


Create a database table definition to store department data (suggested name: Z##DEPMENT,
where ## is your group number).
In addition to the client field, add the following fields:

Field Name Data Element


id Z##_DEPARTMENT_ID (created in the previ-
ous exercise)
description /LRN/DEPMENT_DESCRIPTION

Add the id field to the table key and include the /LRN/S_ADMIN structure for administrative
data into the field list.

1. Create a new development object of type Database Table (suggested name:


Z##DEPMENT).

2. After the client field, add a second key field id, and type it with the your data element
Z##_DEPARTMENT_ID.

Note:
If you have not completed the corresponding exercise, use data
element /LRN/DEPARTMENT_ID, instead.

3. Add a field description based on the /LRN/DEPMENT_DESCRIPTION data element.

4. Include structure /LRN/S_ADMIN with administrative fields.

© Copyright. All rights reserved. 59


Unit 5: Defining Relationships and Associations

5. Maintain the technical table settings. Use the value help to choose appropriate values for
the data class and the size category.

Note:
We expect the table to contain less than 100 entries.

6. Activate the technical table settings and the database table definition.

Task 2: Define a Foreign Key Relationship


Define a foreign key relationship between your database tables for employee data and
department data. The relationship should document that employees can only be assigned to
existing departments. Or in other words, in the department_id field of the Z##EMPLOY table,
only those values are allowed for which an entry exists in table Z##DEMENT. Choose a suitable
cardinality to document that any number of employees can be assigned a single department.

1. Identify the foreign key table and navigate to the check field.

Which table is the check table and which table is the foreign key table?

Which fields in the foreign key table form the foreign key?

Which field is the check field?

2. Add a foreign key to the check field.

Hint:
Use code-completion where possible.

3. Save the database table definition to invoke auto-formatting.

Note:
When saving the definition, the editor also adds annotation
@AbapCatalog.foreignKey.screenCheck.

© Copyright. All rights reserved. 60


Exercise 10: Define a Foreign Key Relationship

4. Add a cardinality to document that a single department ID can be used in any number of
employee data sets, and that on the other hand, every employee should be assigned to an
existing department.

5. Activate the database table definition.

Task 3: Define Department Head and Assistant


Extend your database table for department data with fields for the department head and the
department assistant (suggested names: head_id and assistant_id). Define a new data
element for each of the fields, but make sure that you use the same domain as in the
employee_id field of your employee table. Then define a foreign key relation for each of the
fields to document that only existing employee numbers are allowed.

1. Edit the field list of your database table for department data. Before the INCLUDE
statement, add the following fields and use a quick fix to create the new data elements:
Field Name Data Element
department_head Z##_DEPMENT_HEAD
department_assistant Z##_DEPMENT_ASSISTANT

For both data elements, use your domain Z##_EMPLOYEE_IDas the data type.

Note:
Only If you did not create a Z##_EMPLOYEE_ID domain, you can use the /LRN/
EMPLOYEE_ID domain, instead. Make sure the key field ID of your database
table for employee data (suggested name was Z##EMPLOY) is based on the
same domain.

2. For both new fields, add a foreign key relationship with table Z##EMPLOY as check table.
Then save the database table definition to invoke auto-formatting.

Hint:
Use code-completion where possible.

3. Add a cardinality to both foreign key relationships. Choose the cardinality based on the
following information:

● Not every employee can be a department head or a department assistant.

● The same employee cannot be a head of more than one department.

● The same employee cannot be an assistant of more than one department.

● Each department needs exactly one department assistant.

● A department could well do without a department head.

4. Activate the database table definition.

© Copyright. All rights reserved. 61


Unit 5: Defining Relationships and Associations

Task 4: Fill Tables


Fill your new database table with some department data and update the employee table. To
do so, create a copy of ABAP class /LRN/CL_S4D430_CHECK_AND_FILL and adjust the
values of constants c_version, c_employ_table and c_depment_table. Then activate
and execute the class as a console app.

1. Create a copy of the ABAP class /LRN/CL_S4D430_CHECK_AND_FILL, name it


Z##_S4D430_CHECK_AND_FILL and place it in your package ZS4D430_##.

Note:
Skip this step if you created a copy of /LRN/CL_S4D430_CHECK_AND_FILL in
an earlier exercise.

2. Change the value of constant c_version from


lcl_generator=>employee_table_only to
lcl_generator=>with_relationships.

Hint:
You can add a comment sign in front of the current definition and remove the
comment sign from the second definition alternative.

3. Change the values of constants c_employ_table and c_depment_table to the names


of your database tables.

4. Activate the ABAP class and execute it as a console app. If the console output contains
errors, adjust the definition of your database tables until they are compatible with
database table definitions /LRN/EMPLOY_REL and LRN/DEPMENT_REL.

© Copyright. All rights reserved. 62


Unit 5
Solution 10
Define a Foreign Key Relationship

You define a second database table for departments and define the foreign key relationship
between departments and employees.
Template:

/LRN/EMPLOY_DEP (Database Table Definition)

Solution:

/LRN/DEPMENT_REL (Database Table Definition)


/LRN/EMPLOY_REL (Database Table Definition)
/LRN/DEPMENT_HEAD (Data Element)
/LRN/DEPMENT_ASSISTANT (Data Element)

For this exercise, you need the database table for employee data that you created and filled in
a previous exercise (suggested name was: Z##EMPLOY, where ## is your group number). If
you have not finished that exercise, create a copy of database table /LRN/EMPLOY_DEP.

Task 1: Define a Database Table for Department Data


Create a database table definition to store department data (suggested name: Z##DEPMENT,
where ## is your group number).
In addition to the client field, add the following fields:

Field Name Data Element


id Z##_DEPARTMENT_ID (created in the previ-
ous exercise)
description /LRN/DEPMENT_DESCRIPTION

Add the id field to the table key and include the /LRN/S_ADMIN structure for administrative
data into the field list.

1. Create a new development object of type Database Table (suggested name:


Z##DEPMENT).
a) In the Project Explorer, expand your package and open the context menu on subnode
Dictionary.

b) Choose New → Database Table.

c) Confirm the package, enter the name Z##DEPMENT and the description Department,
then choose Next.

d) Assign the new object to a transport request and choose Finish.

© Copyright. All rights reserved. 63


Unit 5: Defining Relationships and Associations

e) The code of the database table definition should look like this:

@EndUserText.label : 'Department'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table z##depment {

key client : abap.clnt not null;

2. After the client field, add a second key field id, and type it with the your data element
Z##_DEPARTMENT_ID.

Note:
If you have not completed the corresponding exercise, use data
element /LRN/DEPARTMENT_ID, instead.

a) Adjust the code as follows:

define table z##depment {

key client : abap.clnt not null;


key id : z##_department_id;

3. Add a field description based on the /LRN/DEPMENT_DESCRIPTION data element.


a) Adjust the code as follows:

define table z##depment {

key client : abap.clnt not null;


key id : z##_department_id;
description : /lrn/depment_description;

4. Include structure /LRN/S_ADMIN with administrative fields.


a) Adjust the code as follows:

define table z##depment {

key client : abap.clnt not null;


key id : z##_department_id;
description : /lrn/depment_description;
include : /lrn/s_admin;

5. Maintain the technical table settings. Use the value help to choose appropriate values for
the data class and the size category.

© Copyright. All rights reserved. 64


Solution 10: Define a Foreign Key Relationship

Note:
We expect the table to contain less than 100 entries.

a) Right-click anywhere in the editor and choose Open Others → Technical Settings.

b) Choose APPL0 Master Data, Transparent Table.

c) Choose 0 Expected records 0 - 2.600.

6. Activate the technical table settings and the database table definition.
a) While still on the Technical Table Setttings dialog, press Ctrl + F3 to activate the
technical table settings.

b) Return to the editor with the source code of the database table definition and press
Ctrl + F3 to activate the database table definition.

Task 2: Define a Foreign Key Relationship


Define a foreign key relationship between your database tables for employee data and
department data. The relationship should document that employees can only be assigned to
existing departments. Or in other words, in the department_id field of the Z##EMPLOY table,
only those values are allowed for which an entry exists in table Z##DEMENT. Choose a suitable
cardinality to document that any number of employees can be assigned a single department.

1. Identify the foreign key table and navigate to the check field.

Which table is the check table and which table is the foreign key table?

The database table for department data is the check table, the database table for
employee data is the foreign key table.

Which fields in the foreign key table form the foreign key?

The foreign key consists of the client field and the department_id field.

Which field is the check field?

The department_id field is the last field of the foreign key and therefore the check field.

a) Open the definition of your database table for employee data (suggested name was
Z##EMPLOY) .

b) Scroll down to the department_id field.

2. Add a foreign key to the check field.

© Copyright. All rights reserved. 65


Unit 5: Defining Relationships and Associations

Hint:
Use code-completion where possible.

a) In the definition of the department_id field, place the cursor before the closing semi-
colon (;) and press Enter to insert a new code row.

b) Place the cursor at the beginning of the new row and press Ctrl + Space to invoke
code-completion.

c) From the suggestion list, choose with foreign key - keyword.

d) Enter a blank space and press Ctrl + Space to invoke code completion again.

e) From the suggestion list, choose your database table for department data, that is entry
z##depment - table.

f) Enter a blank space and use code-completion to enter the WHERE keyword.

g) Keep using code completion to add the assignment of key fields (on the left-hand side)
and foreign key fields (on the right-had side).

3. Save the database table definition to invoke auto-formatting.

Note:
When saving the definition, the editor also adds annotation
@AbapCatalog.foreignKey.screenCheck.

a) Press Ctrl + Space to save the development object.

b) The code should now look like this:

entry_date : z##_entry_date;
@AbapCatalog.foreignKey.screenCheck : false
department_id : z##_department_id
with foreign key z##depment
where client = z##employ.client
and id = z##employ.department_id;

4. Add a cardinality to document that a single department ID can be used in any number of
employee data sets, and that on the other hand, every employee should be assigned to an
existing department.
a) Adjust the code as follows:

entry_date : z##_entry_date;
@AbapCatalog.foreignKey.screenCheck : false
department_id : z##_department_id
with foreign key [0..*,1] z##depment
where client = z##employ.client
and id = z##employ.department_id;

5. Activate the database table definition.


a) Press Ctrl + F3 to activate the development object.

© Copyright. All rights reserved. 66


Solution 10: Define a Foreign Key Relationship

Task 3: Define Department Head and Assistant


Extend your database table for department data with fields for the department head and the
department assistant (suggested names: head_id and assistant_id). Define a new data
element for each of the fields, but make sure that you use the same domain as in the
employee_id field of your employee table. Then define a foreign key relation for each of the
fields to document that only existing employee numbers are allowed.

1. Edit the field list of your database table for department data. Before the INCLUDE
statement, add the following fields and use a quick fix to create the new data elements:
Field Name Data Element
department_head Z##_DEPMENT_HEAD
department_assistant Z##_DEPMENT_ASSISTANT

For both data elements, use your domain Z##_EMPLOYEE_IDas the data type.

Note:
Only If you did not create a Z##_EMPLOYEE_ID domain, you can use the /LRN/
EMPLOYEE_ID domain, instead. Make sure the key field ID of your database
table for employee data (suggested name was Z##EMPLOY) is based on the
same domain.

a) At the end of the element list, enter department_head : z##_depment_head;


(with ## being your group number).

b) Open the Problems view. You should see an error Field DEPARTMENT_HEAD:
Component type or domain used not active or does not exist.

c) Place the cursor onz##_depment_head, and press Ctrl + 1 to open the quick fix
menu.

d) From the quick fix menu, double-click Create data element ....

e) Confirm the package and the name, enter a description, for example, Department
Head, and choose Next.

f) Assign the new object to a transport request and choose Finish.

g) Under Type Name, enter Z##_EMPLOYEE_ID and enter the following field labels:

Field Value
Short Dep. Head

Medium Department Head

Long Department Head

Heading Department Head

© Copyright. All rights reserved. 67


Unit 5: Defining Relationships and Associations

h) Activate the new data element and return to database table Z##DEPMENT.

i) In a new code line, enter assistant_id : Z##_depment_assistant; and use the


quick fix again to create data element Z##_DEPMENT_ASSISTANT using the same
domain, but with the following field labels:

Field Value
Short Assistant

Medium Dep. Assistant

Long Department Assistant

Heading Department Assistant

2. For both new fields, add a foreign key relationship with table Z##EMPLOY as check table.
Then save the database table definition to invoke auto-formatting.

Hint:
Use code-completion where possible.

a) After applying the auto-formatting, the code should look like this:

define table z##depment {


key client : abap.clnt not null;
key id : z##_department_id not null;
description : /lrn/depment_description;

@AbapCatalog.foreignKey.screenCheck : false
head_id : z##_depment_head
with foreign key z##employ
where client = z##depment.client
and employee_id = z##depment.head_id;

@AbapCatalog.foreignKey.screenCheck : false
assistant_id : z##_depment_assistant
with foreign key z##employ
where client = z##depment.client
and employee_id = z##depment.assistant_id;

include /lrn/s_admin;
}

3. Add a cardinality to both foreign key relationships. Choose the cardinality based on the
following information:

● Not every employee can be a department head or a department assistant.

● The same employee cannot be a head of more than one department.

● The same employee cannot be an assistant of more than one department.

© Copyright. All rights reserved. 68


Solution 10: Define a Foreign Key Relationship

● Each department needs exactly one department assistant.

● A department could well do without a department head.

a) Adjust the code as follows:

@AbapCatalog.foreignKey.screenCheck : false
head_id : z##_depment_head
with foreign key [0..1,0..1] z##employ
where client = z##depment.client
and employee_id = z##depment.head_id;

@AbapCatalog.foreignKey.screenCheck : false
assistant_id : z##_depment_assistant
with foreign key [0..1,1] z##employ
where client = z##depment.client
and employee_id = z##depment.assistant_id;

4. Activate the database table definition.


a) Press Ctrl + F3 to activate the development object.

Task 4: Fill Tables


Fill your new database table with some department data and update the employee table. To
do so, create a copy of ABAP class /LRN/CL_S4D430_CHECK_AND_FILL and adjust the
values of constants c_version, c_employ_table and c_depment_table. Then activate
and execute the class as a console app.

1. Create a copy of the ABAP class /LRN/CL_S4D430_CHECK_AND_FILL, name it


Z##_S4D430_CHECK_AND_FILL and place it in your package ZS4D430_##.

Note:
Skip this step if you created a copy of /LRN/CL_S4D430_CHECK_AND_FILL in
an earlier exercise.

a) In the Project Explorer view, locate the ABAP class in package /LRN/
S4D430_EXERCISE and right-click on it to open the context menu.

b) From the context menu, choose Duplicate.

c) Enter the name of your package, the name for the copy and a description. Then choose
Next.

d) Assign the new object to a transport request and choose Finish.

2. Change the value of constant c_version from


lcl_generator=>employee_table_only to
lcl_generator=>with_relationships.

Hint:
You can add a comment sign in front of the current definition and remove the
comment sign from the second definition alternative.

© Copyright. All rights reserved. 69


Unit 5: Defining Relationships and Associations

a) Adjust the code as follows:

* CONSTANTS c_version TYPE t_version VALUE


lcl_generator=>employee_table_only.
CONSTANTS c_version TYPE t_version VALUE
lcl_generator=>with_relationships.
* CONSTANTS c_version TYPE t_version VALUE
lcl_generator=>with_extensions.

3. Change the values of constants c_employ_table and c_depment_table to the names


of your database tables.
a) Scroll down to the code row starting with CONSTANTS c_employ_table.

b) If the literal after VALUE still contains ##, replace it with your group number.

c) Scroll down to the code row starting with CONSTANTS c_depment_table.

d) In the literal after VALUE, replace ## with your group number.

4. Activate the ABAP class and execute it as a console app. If the console output contains
errors, adjust the definition of your database tables until they are compatible with
database table definitions /LRN/EMPLOY_REL and LRN/DEPMENT_REL.
a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the ABAP class as console app.

c) Make sure the console output contains the text Filled table ... for both database tables.

© Copyright. All rights reserved. 70


Unit 5
Exercise 11
Define a CDS View with Associations

You define a basic CDS view entity for departments and the associations between
departments and employees.
Template:

/LRN/R_EMPLOYEE_ANN (Data Definition)

Solution:

/LRN/R_DEPARTMENT_REL (Data Definition)


/LRN/R_EMPLOYEE_REL (Data Definition)

For this exercise, you need the CDS view entity for employee data which you created in a
previous exercise (suggested name was: Z##_R_Employee, where ## is your group number).
If you have not finished that exercise, create a copy of data definition /LRN/
R_EMPLOYEE_ANN.

Task 1: Define a CDS View Entity for Department Data


Define a CDS view entity for department data (suggested name: Z##_R_Department, where
## is your group number). Let the new CDS view entity read all fields from the database table
that you created in the previous exercise (suggested name was: Z##DEPMENT).

Note:
If you have not finished the previous exercise, you can let your CDS view entity
read the database table /LRN/DEPMENT_REL.

1. In your own package, create a new data definition (suggested name: Z##_R_DEPARTMENT,
where ## is your group number). Specify your database table as Referenced Object and
choose the Define View Entity template to generate the definition statement, some
standard annotations and the element list.

2. Apply source code formatting.

3. Activate the data definition.

Task 2: Define an Association


In your basic CDS view entity for employee data (suggested name was: Z##_R_Employee),
define and expose an association using your new CDS view entity for department data as
target (suggested association name: _Department). Choose a cardinality that matches the
cardinality used in the foreign key relationship for the DEPARTMENT_ID table field.

1. Open the basic data definition for employee data (suggested name was:
Z##_R_EMPLOYEE).

2. Define an association to your CDS view entity for department data with association name
_Department.

© Copyright. All rights reserved. 71


Unit 5: Defining Relationships and Associations

3. Define the ON-condition, using the department ID field in both view entities.

Hint:
Make use of the $projection. prefix to address the element of the source
view entity and the_Department. prefix to address the element of the target
view entity.

4. Add a cardinality that matches the cardinality of the foreign key relationship for the
DEPARTMENT_ID table field.

Note:
The cardinality of the foreign key relationship is 0..*,1. The first part specifies
the number employees per department. The second part expresses the
number of departments per employee.

5. Expose the association.

6. Activate the CDS data definition.

Task 3: Define More Associations


In your basic CDS view entity for department data, define and expose three associations: an
association for all employees (suggested association name: _Employee), an association for
the department head (suggested name: _Head), and an association for the department
assistant (suggested name: _Assistant). Choose the cardinalities based on the
corresponding foreign key relationships in the underlying database tables.

1. Return to the data definition for department data. Define association _Employee to
address all employees that are assigned to this department.

Note:
Take into account that a department can have any number of employees,
including zero.

2. Define an association to address the details of the department head. Set the cardinality
based on the cardinality of the foreign key relationship between the underlying database
tables.

Note:
In our model, it is NOT necessary that a department has a department head.

3. Define an association to address the details of the department assistant. Set the
cardinality based on the cardinality of the foreign key relationship between the underlying
database tables.

Note:
In our model, a department cannot exist without a department assistant.

© Copyright. All rights reserved. 72


Exercise 11: Define a CDS View with Associations

4. Expose the association.

5. Activate the CDS data definition.

Task 4: Analyze and Use the Associations


Analyze the technical implementation of your CDS view for department data and use the
associations for navigation in the Data Preview tool.

1. Display the SQL statement with which the technical representation of the view entity is
created in the database.

Do the associations show up in the CREATE statement?

2. Open the Data Preview for your CDS view for department data.

3. Display all employees that work for the Sales and Distribution department.

4. Return to the department list and display the assistant of the Administration department.

5. Without returning to the list of departments, navigate to the department, this person
works for and from there to the department head.

© Copyright. All rights reserved. 73


Unit 5
Solution 11
Define a CDS View with Associations

You define a basic CDS view entity for departments and the associations between
departments and employees.
Template:

/LRN/R_EMPLOYEE_ANN (Data Definition)

Solution:

/LRN/R_DEPARTMENT_REL (Data Definition)


/LRN/R_EMPLOYEE_REL (Data Definition)

For this exercise, you need the CDS view entity for employee data which you created in a
previous exercise (suggested name was: Z##_R_Employee, where ## is your group number).
If you have not finished that exercise, create a copy of data definition /LRN/
R_EMPLOYEE_ANN.

Task 1: Define a CDS View Entity for Department Data


Define a CDS view entity for department data (suggested name: Z##_R_Department, where
## is your group number). Let the new CDS view entity read all fields from the database table
that you created in the previous exercise (suggested name was: Z##DEPMENT).

Note:
If you have not finished the previous exercise, you can let your CDS view entity
read the database table /LRN/DEPMENT_REL.

1. In your own package, create a new data definition (suggested name: Z##_R_DEPARTMENT,
where ## is your group number). Specify your database table as Referenced Object and
choose the Define View Entity template to generate the definition statement, some
standard annotations and the element list.
a) In the Project Explorer view, right-click your database table definition Z##DEPMENT to
open the context menu.

b) From the context menu, choose New Data Definition.

c) Confirm that the Package field contains the name of your package and that the
Referenced Object field contains the name of your database table definition.

d) In the Name field, enter the name for the CDS view entity (Z##_R_Department, where
## is your group number).

e) Enter Department (Entity) in the Description field and choose Next.

f) Confirm the transport request and choose Next.

© Copyright. All rights reserved. 74


Solution 11: Define a CDS View with Associations

Caution:
Make sure you don't choose Finish yet. If you do, you are not able to
choose the template that you want to use.

g) From the list of Templates, choose Define View Entity, then choose Finish.

2. Apply source code formatting.


a) From the eclipse menu, choose Source Code → Format. Alternatively, choose Shift
+ F1.

3. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

Task 2: Define an Association


In your basic CDS view entity for employee data (suggested name was: Z##_R_Employee),
define and expose an association using your new CDS view entity for department data as
target (suggested association name: _Department). Choose a cardinality that matches the
cardinality used in the foreign key relationship for the DEPARTMENT_ID table field.

1. Open the basic data definition for employee data (suggested name was:
Z##_R_EMPLOYEE).
a) Press Ctrl + Shift + A.

b) Enter Z##_R_.

c) From the list of matching items, choose Z##_R_EMPLOYEE (Data Definition)


and choose Next.

2. Define an association to your CDS view entity for department data with association name
_Department.
a) Adjust the code as follows:

define view entity Z##_R_Employee


as select from z##employ
association to Z##_R_Department as _Department

3. Define the ON-condition, using the department ID field in both view entities.

Hint:
Make use of the $projection. prefix to address the element of the source
view entity and the_Department. prefix to address the element of the target
view entity.

a) Adjust the code as follows:

define view entity Z##_R_Employee


as select from z##employ
association to Z##_R_Department as _Department
on $projection.DepartmentId = _Department.Id

4. Add a cardinality that matches the cardinality of the foreign key relationship for the
DEPARTMENT_ID table field.

© Copyright. All rights reserved. 75


Unit 5: Defining Relationships and Associations

Note:
The cardinality of the foreign key relationship is 0..*,1. The first part specifies
the number employees per department. The second part expresses the
number of departments per employee.

a) Adjust the code as follows:

define view entity Z##_R_Employee


as select from z##employ
association[1..1] to Z##_R_Department as _Department
on $projection.DepartmentId = _Department.Id

5. Expose the association.


a) At the end of the element list, add a comma and the association name.

b) Adjust the code as follows:

last_changed_at as LastChangedAt,
_Department
}

6. Activate the CDS data definition.


a) Press Ctrl + F3 to activate the development object.

Task 3: Define More Associations


In your basic CDS view entity for department data, define and expose three associations: an
association for all employees (suggested association name: _Employee), an association for
the department head (suggested name: _Head), and an association for the department
assistant (suggested name: _Assistant). Choose the cardinalities based on the
corresponding foreign key relationships in the underlying database tables.

1. Return to the data definition for department data. Define association _Employee to
address all employees that are assigned to this department.

Note:
Take into account that a department can have any number of employees,
including zero.

a) Adjust the code as follows:

define view entity Z##_R_Department


as select from z##depment
association [0..*] to Z##_R_Employee as _Employee
on $projection.Id = _Employee.DepartmentId

2. Define an association to address the details of the department head. Set the cardinality
based on the cardinality of the foreign key relationship between the underlying database
tables.

© Copyright. All rights reserved. 76


Solution 11: Define a CDS View with Associations

Note:
In our model, it is NOT necessary that a department has a department head.

a) Adjust the code as follows:

define view entity Z##_R_Department


as select from z##depment
association [0..*] to Z##_R_Employee as _Employee
on $projection.Id = _Employee.DepartmentId
association [0..1] to Z##_R_Employee as _Head
on $projection.HeadId = _Head.EmployeeId

3. Define an association to address the details of the department assistant. Set the
cardinality based on the cardinality of the foreign key relationship between the underlying
database tables.

Note:
In our model, a department cannot exist without a department assistant.

a) Adjust the code as follows:

define view entity Z##_R_Department


as select from z##depment
association [0..*] to Z##_R_Employee as _Employee
on $projection.Id = _Employee.DepartmentId
association [0..1] to Z##_R_Employee as _Head
on $projection.HeadId = _Head.EmployeeId
association [1..1] to Z##_R_Employee as _Assistant
on $projection.AssistantId = _Assistant.EmployeeId

4. Expose the association.


a) At the end of the element list, add a comma and the three association names (comma-
separated).

b) Adjust the code as follows:

last_changed_at as LastChangedAt,
_Employee,
_Head,
_Assistant
}

5. Activate the CDS data definition.


a) Press Ctrl + F3 to activate the development object.

Task 4: Analyze and Use the Associations


Analyze the technical implementation of your CDS view for department data and use the
associations for navigation in the Data Preview tool.

1. Display the SQL statement with which the technical representation of the view entity is
created in the database.

© Copyright. All rights reserved. 77


Unit 5: Defining Relationships and Associations

Do the associations show up in the CREATE statement?

No, as long as the associations are only exposed and not used in path expressions, they
have no effect on database layer.

a) Right-click anywhere in the source code of the data definition and choose Show SQL
CREATE Statement.

2. Open the Data Preview for your CDS view for department data.
a) Right-click anywhere in the source code of the data definition and choose Open
With → Data Preview. Alternatively, place the cursor anywhere in the source code of
the data definition and press F8.

3. Display all employees that work for the Sales and Distribution department.
a) Right-click anywhere in the row with value SALE in the Id column and choose Follow
Association. Alternatively, place the cursor anywhere in the row and press Ctrl + G.

b) Choose _Employee → Z##_R_Employee [0..*].

4. Return to the department list and display the assistant of the Administration department.
a) On the navigation path that is displayed above the Data Preview tab (sometimes
referred to as “Breadcrumb naviation”), choose Z##_R_DEPARTMENT to return to the
list of departments.

b) Right-click anywhere in the row with value ADMIN in the Id column and choose Follow
Association. Alternatively, place the cursor anywhere in the row and press Ctrl + G.

c) Choose _Assistant → Z##_R_Employee [1..1].

5. Without returning to the list of departments, navigate to the department, this person
works for and from there to the department head.
a) Right-click anywhere in the single row that is displayed and choose Follow Association.

b) Choose _Department → Z##_R_Department [1..1].

c) Right-click anywhere in the single row that is displayed and choose Follow Association.

d) Choose _Head → Z##_R_Employee [0..1].

© Copyright. All rights reserved. 78


Unit 5
Exercise 12
Use Associations in Path Expressions

You defined CDS view entities with exposed associations. You want to make use of the
exposed associations. First you do so in a CDS view, then in a SELECT statement in ABAP
SQL.
Template:

/LRN/CL_S4D430_RLT_PATH_EXP (Global Class)

Solution:

/LRN/C_EMPLOYEE_QRY (Data Definition)


/LRN/CL_S4D430_RLS_PATH_EXP (Global Class)

Task 1: Use Exposed Associations in CDS


Define a new CDS view entity (suggested name: Z##_C_EmployeeQuery). As data source,
use your view entity for employee data which exposes an association (suggested name was:
Z##_R_Employee). In the element list, read the employee ID and name. Then, add path
expressions to read the department description and the department assistant's last name.

Note:
If you have not finished the previous exercise, you can let your new view entity
read from the /LRN/R_Employee_Rel view entity.

1. In your own package, create a new data definition (suggested name:


Z##_C_EMPLOYEEQUERY, where ## is your group number). Specify your CDS view entity
Z##_R_Employee as Referenced Object and choose the Define View Entity template to
generate the definition statement, some standard annotations and the element list.

2. Apply source code formatting.

3. Edit the element list of the new data definition. Remove all elements except for
EmployeeID, FirstName, LastName, DepartmentID, and the exposed association
_Department.

4. After the DepartmentID element, add a path expression to read the description of the
department, to which the employee is assigned (suggested element name:
DepartmentDescription).

5. Save the data definition and display the SQL CREATE statement.

Note:
If you don't save the data definition, your changes will not appear in the SQL
CREATE statement.

© Copyright. All rights reserved. 79


Unit 5: Defining Relationships and Associations

Does the path expression show up in the CREATE statement?

6. Add a path expression to read the last name of the department assistant (suggested
element name: AssistantName).

7. Activate the data definition and display the SQL CREATE statement again.

How many JOIN statements does the FROM clause contain now?

8. Display the query result in the Data Preview tool.

Task 2: Use Exposed Associations in ABAP SQL


Create a copy of ABAP class /LRN/CL_S4D430_RLT_PATH_EXPR (suggested name:
ZCL_##_PATH_EXPR) and adjust the SELECT statement. Read all fields from the CDS view
entity which you just created (suggested name was: Z##_C_EmployeeQuery). In addition,
implement a path expression in ABAP SQL to read the department head's name.

1. Copy the /LRN/CL_S4D430_RLT_PATH_EXPR class to a class in your own package


(suggested name: ZCL_##_PATH_EXPR, where ## is for your group number).

2. In the IF_OO_ADT_CLASSRUN~MAIN method, change the SELECT statement.


Replace /LRN/C_Employee_Ann in the FROM clause with the name of the CDS view
entity that you have just created (Z##_C_EmployeeQuery).

3. At the end of the field list, also read the new view elements DepartmentDescription
and AssistantName.

4. After the department assistant's name, implement a path expression that reads the last
name of the department head (suggested field name: HEADNAME).

Hint:
Use code-completion where possible. Remember that in ABAP SQL,
association names require a backslash sign (\) as a prefix and that a dash
sign (-) is used between the association name and the element name.

5. Activate the global class and execute it as a console app.

© Copyright. All rights reserved. 80


Unit 5
Solution 12
Use Associations in Path Expressions

You defined CDS view entities with exposed associations. You want to make use of the
exposed associations. First you do so in a CDS view, then in a SELECT statement in ABAP
SQL.
Template:

/LRN/CL_S4D430_RLT_PATH_EXP (Global Class)

Solution:

/LRN/C_EMPLOYEE_QRY (Data Definition)


/LRN/CL_S4D430_RLS_PATH_EXP (Global Class)

Task 1: Use Exposed Associations in CDS


Define a new CDS view entity (suggested name: Z##_C_EmployeeQuery). As data source,
use your view entity for employee data which exposes an association (suggested name was:
Z##_R_Employee). In the element list, read the employee ID and name. Then, add path
expressions to read the department description and the department assistant's last name.

Note:
If you have not finished the previous exercise, you can let your new view entity
read from the /LRN/R_Employee_Rel view entity.

1. In your own package, create a new data definition (suggested name:


Z##_C_EMPLOYEEQUERY, where ## is your group number). Specify your CDS view entity
Z##_R_Employee as Referenced Object and choose the Define View Entity template to
generate the definition statement, some standard annotations and the element list.
a) In the Project Explorer view, right-click your data definition Z##_R_EMPLOYEE to open
the context menu.

b) From the context menu, choose New Data Definition.

c) Confirm that the Package field contains the name of your package and that the
Referenced Object field contains the name of your database table definition.

d) In the Name field, enter the name for the CDS view entity (Z##_C_EmployeeQuery,
where ## is your group number).

e) Enter Employee (Query) in the Description field and choose Next.

f) Confirm the transport request and choose Next.

© Copyright. All rights reserved. 81


Unit 5: Defining Relationships and Associations

Caution:
Make sure you don't choose Finish yet. If you do, you are not able to
choose the template that you want to use.

g) From the list of Templates, choose Define View Entity, then choose Finish.

2. Apply source code formatting.


a) From the eclipse menu, choose Source Code → Format. Alternatively, choose Shift
+ F1.

3. Edit the element list of the new data definition. Remove all elements except for
EmployeeID, FirstName, LastName, DepartmentID, and the exposed association
_Department.
a) Adjust the code as follows:

define view entity Z##_C_EmployeeQuery


as select from Z##_R_Employee
{
key EmployeeId,
FirstName,
LastName,
DepartmentID,

/* Associations */
_Department

4. After the DepartmentID element, add a path expression to read the description of the
department, to which the employee is assigned (suggested element name:
DepartmentDescription).
a) Adjust the code as follows:

define view entity Z##_C_EmployeeQuery


as select from Z##_R_Employee
{
key EmployeeId,
FirstName,
LastName,
DepartmentID,

_Department.Description as DepartmentDescription,

/* Associations */
_Department

5. Save the data definition and display the SQL CREATE statement.

Note:
If you don't save the data definition, your changes will not appear in the SQL
CREATE statement.

© Copyright. All rights reserved. 82


Solution 12: Use Associations in Path Expressions

Does the path expression show up in the CREATE statement?

Yes, the association is translated into a JOIN expression and the department description is
read from the joined data source.

a) Press Ctrl + S to save the development object.

b) Right-click anywhere in the source code of the data definition and choose Show SQL
CREATE Statement.

6. Add a path expression to read the last name of the department assistant (suggested
element name: AssistantName).
a) Adjust the code as follows:

define view entity Z##_C_EmployeeQuery


as select from Z##_R_Employee
{
key EmployeeId,
FirstName,
LastName,
DepartmentID,

_Department.Description as DepartmentDescription,
_Department._Assistant.LastName as AssistantName,

/* Associations */
_Department

7. Activate the data definition and display the SQL CREATE statement again.

How many JOIN statements does the FROM clause contain now?

The FROM clause contains two JOIN statements (one to read the department description,
the other to read the department assistant's name).

a) Press Ctrl + F3 to activate the development object.

b) Right-click anywhere in the source code of the data definition and choose Show SQL
CREATE Statement.

8. Display the query result in the Data Preview tool.


a) Place the cursor anywhere in the data definition and press F8 to invoke the Data
Preview tool.

Task 2: Use Exposed Associations in ABAP SQL


Create a copy of ABAP class /LRN/CL_S4D430_RLT_PATH_EXPR (suggested name:
ZCL_##_PATH_EXPR) and adjust the SELECT statement. Read all fields from the CDS view
entity which you just created (suggested name was: Z##_C_EmployeeQuery). In addition,
implement a path expression in ABAP SQL to read the department head's name.

1. Copy the /LRN/CL_S4D430_RLT_PATH_EXPR class to a class in your own package


(suggested name: ZCL_##_PATH_EXPR, where ## is for your group number).

© Copyright. All rights reserved. 83


Unit 5: Defining Relationships and Associations

a) In the Project Explorer view, right-click the /LRN/CL_S4D430_RLT_PATH_EXP class to


open the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
ZCL_##_PATH_EXP, where ## is your group number.

d) Adjust the description and choose Next.

e) Confirm the transport request and choose Finish.

2. In the IF_OO_ADT_CLASSRUN~MAIN method, change the SELECT statement.


Replace /LRN/C_Employee_Ann in the FROM clause with the name of the CDS view
entity that you have just created (Z##_C_EmployeeQuery).
a) Adjust the code as follows:

SELECT
FROM Z##_C_EmployeeQuery
FIELDS employeeid,

3. At the end of the field list, also read the new view elements DepartmentDescription
and AssistantName.
a) Adjust the code as follows:

SELECT
FROM Z##_C_EmployeeQuery
FIELDS employeeid,
firstname,
lastname,
departmentid,
departmentdescription,
assistantname
INTO TABLE @DATA(result).

4. After the department assistant's name, implement a path expression that reads the last
name of the department head (suggested field name: HEADNAME).

Hint:
Use code-completion where possible. Remember that in ABAP SQL,
association names require a backslash sign (\) as a prefix and that a dash
sign (-) is used between the association name and the element name.

a) Adjust the code as follows:

SELECT
FROM Z##_C_EmployeeQuery
FIELDS employeeid,
firstname,
lastname,
departmentid,
departmentdescription,
assistantname,
\_department\_head-lastname AS headname
INTO TABLE @DATA(result).

5. Activate the global class and execute it as a console app.

© Copyright. All rights reserved. 84


Solution 12: Use Associations in Path Expressions

a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the global class as a console app.

© Copyright. All rights reserved. 85


Unit 6
Exercise 13
Use Expressions in a CDS View

You want to extend your CDS view entity with SQL logic. In a first step, you tag employees as
department heads and assistants and calculate the monthly salary.
Template:

/LRN/C_EMPLOYEE_QRY (Data Definition)

Solution:

/LRN/C_EMPLOYEE_EXP (Data Definition)

For this exercise, you need the CDS view entity you created in a previous exercise (suggested
name was: Z##_C_EmployeeQuery, where ## is your group number). If you have not finished
that exercise, create a copy of the data definition /LRN/C_EMPLOYEE_QRY.

Task 1: Use CASE Distinction


In your CDS view entity for evaluating employee data (suggested name was:
Z##_C_EmployeeQuery, where ## is your group number), define a new view element
(suggested element name: EmployeeRole). Make the element return value 'H' if the
employee is the department head, value ' A' if the employee is the department assistant, and '
' for all other employees.

1. In the element list of your view entity, before the exposed association, add a case
distinction that compares the value of EmployeeID to the value of element HeadID in the
target of association _Department. If the values are identical, return value 'H'.

Is this a simple case or a complex case (searched case)?

2. Add a second branch that compares the value of EmployeeID to the value of element
AssistantID in the target of association _Department. If the values are identical, return
value 'A'.

3. Add an else branch to return value ' '.

4. Close the CASE expression and specify an element name (suggested element name:
EmployeeRole).

5. Add the required annotation to define a label for the calculated field (suggested value:
Employee Role).

Task 2: Use Arithmetic Expression


Based on the employee's annual salary, calculate the monthly salary (suggested element
name: MonthlySalary).

© Copyright. All rights reserved. 86


Exercise 13: Use Expressions in a CDS View

1. Use an arithmetic expression with the / operator to divide the content of AnnualSalary
by 12.

Why do you have to cast the annual salary value to another data type?

Why do you have to specify literal 12 as 12.0?

2. Add the required annotation to define a label for the calculated field (suggested value:
Monthly Salary).

3. Add the CurrencyCode element to the element list and use the
@Semantics.amount.currencyCode annotation to link it to the MonthlySalary element.

Why does the syntax check not enforce the currency code annotation?

4. Activate the CDS data definition.

5. Open the Data Preview and analyze the output.

© Copyright. All rights reserved. 87


Unit 6
Solution 13
Use Expressions in a CDS View

You want to extend your CDS view entity with SQL logic. In a first step, you tag employees as
department heads and assistants and calculate the monthly salary.
Template:

/LRN/C_EMPLOYEE_QRY (Data Definition)

Solution:

/LRN/C_EMPLOYEE_EXP (Data Definition)

For this exercise, you need the CDS view entity you created in a previous exercise (suggested
name was: Z##_C_EmployeeQuery, where ## is your group number). If you have not finished
that exercise, create a copy of the data definition /LRN/C_EMPLOYEE_QRY.

Task 1: Use CASE Distinction


In your CDS view entity for evaluating employee data (suggested name was:
Z##_C_EmployeeQuery, where ## is your group number), define a new view element
(suggested element name: EmployeeRole). Make the element return value 'H' if the
employee is the department head, value ' A' if the employee is the department assistant, and '
' for all other employees.

1. In the element list of your view entity, before the exposed association, add a case
distinction that compares the value of EmployeeID to the value of element HeadID in the
target of association _Department. If the values are identical, return value 'H'.

Is this a simple case or a complex case (searched case)?

This is a simple case because it directly compares fields and values for equality.

a) Adjust the code as follows:

define view entity Z##_C_EmployeeQuery


as select from Z##_R_Employee
{
key EmployeeId,
FirstName,
LastName,
DepartmentId,

_Department.Description as DepartmentDescription,
_Department._Assistant.LastName as AssistantName,

case EmployeeId
when _Department.HeadId then 'H'

© Copyright. All rights reserved. 88


Solution 13: Use Expressions in a CDS View

2. Add a second branch that compares the value of EmployeeID to the value of element
AssistantID in the target of association _Department. If the values are identical, return
value 'A'.
a) Adjust the code as follows:

case EmployeeId
when _Department.HeadId then 'H'
when _Department.AssistantId then 'A'

3. Add an else branch to return value ' '.


a) Adjust the code as follows:

case EmployeeId
when _Department.HeadId then 'H'
when _Department.AssistantId then 'A'
else ' '

4. Close the CASE expression and specify an element name (suggested element name:
EmployeeRole).
a) Adjust the code as follows:

case EmployeeId
when _Department.HeadId then 'H'
when _Department.AssistantId then 'A'
else ' '
end as EmployeeRole,

5. Add the required annotation to define a label for the calculated field (suggested value:
Employee Role).
a) Adjust the code as follows:

@EndUserText.label: 'Employee Role'


case EmployeeId
when _Department.HeadId then 'H'
when _Department.AssistantId then 'A'
else ' '
end as EmployeeRole,

Task 2: Use Arithmetic Expression


Based on the employee's annual salary, calculate the monthly salary (suggested element
name: MonthlySalary).

1. Use an arithmetic expression with the / operator to divide the content of AnnualSalary
by 12.

Why do you have to cast the annual salary value to another data type?

Because the / operator only supports type abap.fltp.

© Copyright. All rights reserved. 89


Unit 6: Using Code Pushdown in CDS Views

Why do you have to specify literal 12 as 12.0?

Because literal 12 is of integer type, while 12.0 is of type abap.fltp.

a) Adjust the code as follows:

@EndUserText.label: 'Employee Role'


case EmployeeId
when _Department.HeadId then 'H'
when _Department.AssistantId then 'A'
else ' '
end as EmployeeRole,

cast( AnnualSalary as abap.fltp ) / 12.0 as MonthlySalary,

2. Add the required annotation to define a label for the calculated field (suggested value:
Monthly Salary).
a) Adjust the code as follows:

@EndUserText.label: 'Employee Role'


case EmployeeId
when _Department.HeadId then 'H'
when _Department.AssistantId then 'A'
else ' '
end as EmployeeRole,

@EndUserText.label: 'Monthly Salary'


cast( AnnualSalary as abap.fltp ) / 12.0 as MonthlySalary,

3. Add the CurrencyCode element to the element list and use the
@Semantics.amount.currencyCode annotation to link it to the MonthlySalary element.

Why does the syntax check not enforce the currency code annotation?

The annotation is only enforced for elements of type abap.cuky but the expression result
is of type abap.fltp.

a) Adjust the code as follows:

@EndUserText.label: 'Monthly Salary'


@Semantics.amount.currencyCode: 'CurrencyCode'
cast( AnnualSalary as abap.fltp ) / 12.0 as MonthlySalary,

CurrencyCode,

4. Activate the CDS data definition.


a) Press Ctrl + F3 to activate the development object.

5. Open the Data Preview and analyze the output.


a) Press F8 to open the Data Preview.

© Copyright. All rights reserved. 90


Unit 6
Exercise 14
Use Built-in Functions in a CDS View

You want to extend your CDS view entity with SQL logic. You use SQL functions to
concatenate first name and last name of the department assistant, convert the monthly
salary to a unique currency and calculate the company affiliation, that is, the number of days
an employee works for the company.
Template:

/LRN/C_EMPLOYEE_EXP (Data Definition)

Solution:

/LRN/C_EMPLOYEE_FCT (Data Definition)

For this exercise, you need the CDS view entity that you worked on in the previous exercise
(suggested name was: Z##_C_EmployeeQuery, where ## is your group number). If you have
not finished the previous exercise, create a copy of data definition /LRN/C_EMPLOYEE_EXP.

Task 1: Use a String Function


In you CDS view entity for evaluating employee data (suggested name was:
Z##_C_EmployeeQuery, where ## is your group number), adjust the definition of the
AssistantName view element. Use a suitable string function to concatenate the first name
and the last name of the department assistant, separated by a single space.

1. Edit the element list of your view entity. Comment the view element that derives the last
name of the department assistant.

2. After the old view element, use code completion to add a call of SQL function
CONCATENATE_WITH_SPACE as a new view element.

3. Replace the placeholders with suitable view elements and literals.

4. Provide the same view element name that was used for the removed view element
(suggested name was: AssistantName).

5. Activate and test the CDS view entity.

Task 2: Use a Date Function


In a new view element (suggested name: CompanyAffiliation), use a suitable date
function to calculate the employee's company affiliation in days, that is, the number of days
between the entry date and today. Then divide the result by the number of days per year to
calculate the employee's company affiliation in years, with a precision of 1 decimal place.

Hint:
The current date is available in session variables $session.user_date and
$session.system_date. For this exercise, use the current system date.
For simplicity, disregard the existence of leap years and assume a year has 365
days.

© Copyright. All rights reserved. 91


Unit 6: Using Code Pushdown in CDS Views

1. Edit the element list of your view entity. Before the exposed association, use code
completion to add a call of SQL function DATS_DAYS_BETWEEN as a new view element.

2. Replace the placeholders with suitable view elements and session variables and specify a
view element name (suggested name: CompanyAffiliation).

3. Use the SQL function division to calculate the company affiliation in years, with a
precision of one decimal place.

4. Activate and test the CDS view entity.

Task 3: Perform a Currency Conversion


In a new view element (suggested name: AnnualSalaryConverted), use a suitable SQL
function to convert the content of view element AnnualSalary to currency US Dollar. Use
the current system date as exchange rate date. Then adjust the calculation of view element
MonthlySalary. Use the converted annual salary as input instead of the unconverted annual
salary.

Hint:
You can re-use calculated view elements of the same view entity by using the
$projection prefix.

1. Remove or comment view element CurrencyCode.

2. In the next code row, define a new view element (suggested name: CurrencyCodeUSD) in
which you convert literal 'USD' to predefined type abap.cuky.

3. Before the MonthlySalary view element, use code completion to insert a call of the SQL
function currency_conversion.

4. Replace the placeholders with values for the parameters. As input, use the annual salary
and the currency code from the source view, own view element CurrencyCodeUSD, and
system variable system_date .

5. Add an element name (suggested name: AnnualSalaryConverted), a label, and the


mandatory Semantics.amount.CurrencyCode annotation.

6. Adjust the calculation of view element MonthlySalary. Instead of AnnualSalary, use


the new view element AnnualSalaryConverted as input.

7. Adjust the view element name (suggested name: MonthlySalaryConverted) and adjust
the mandatory Semantics.amount.CurrencyCode annotation.

8. Activate and test the CDS view entity.

© Copyright. All rights reserved. 92


Unit 6
Solution 14
Use Built-in Functions in a CDS View

You want to extend your CDS view entity with SQL logic. You use SQL functions to
concatenate first name and last name of the department assistant, convert the monthly
salary to a unique currency and calculate the company affiliation, that is, the number of days
an employee works for the company.
Template:

/LRN/C_EMPLOYEE_EXP (Data Definition)

Solution:

/LRN/C_EMPLOYEE_FCT (Data Definition)

For this exercise, you need the CDS view entity that you worked on in the previous exercise
(suggested name was: Z##_C_EmployeeQuery, where ## is your group number). If you have
not finished the previous exercise, create a copy of data definition /LRN/C_EMPLOYEE_EXP.

Task 1: Use a String Function


In you CDS view entity for evaluating employee data (suggested name was:
Z##_C_EmployeeQuery, where ## is your group number), adjust the definition of the
AssistantName view element. Use a suitable string function to concatenate the first name
and the last name of the department assistant, separated by a single space.

1. Edit the element list of your view entity. Comment the view element that derives the last
name of the department assistant.
a) Place the cursor anywhere in the respective code row and press Ctrl + < to add a
comment sign (//) at the beginning of the row.

2. After the old view element, use code completion to add a call of SQL function
CONCATENATE_WITH_SPACE as a new view element.
a) In the code row // _Department._Assistant.LastName as AssistantName,,
place the cursor after the colon and press Enter to insert a new row.

b) Enter con and press Ctrl + Space to invoke code-completion.

c) From the suggestion list, choose concat_with_space(arg1, arg,2, space_cnt) (function)


and press Shift + Enter to insert the full signature.
Result
This should insert the following code:

concat_with_space( arg1, arg2, space_cnt )

3. Replace the placeholders with suitable view elements and literals.

© Copyright. All rights reserved. 93


Unit 6: Using Code Pushdown in CDS Views

a) Adjust the code as follows:

concat_with_space( _Department._Assistant.FirstName,
_Department._Assistant.LastName,
1 )

Note:
We inserted additional line breaks to increase readability in the printed
course material.

4. Provide the same view element name that was used for the removed view element
(suggested name was: AssistantName).
a) Adjust the code as follows:

concat_with_space( _Department._Assistant.FirstName,
_Department._Assistant.LastName,
1 ) as AssistantName,

5. Activate and test the CDS view entity.


a) Press Ctrl + F3 to activate the development object.

b) Press F8 to test the CDS view entity in the Data Preview tool.

Task 2: Use a Date Function


In a new view element (suggested name: CompanyAffiliation), use a suitable date
function to calculate the employee's company affiliation in days, that is, the number of days
between the entry date and today. Then divide the result by the number of days per year to
calculate the employee's company affiliation in years, with a precision of 1 decimal place.

Hint:
The current date is available in session variables $session.user_date and
$session.system_date. For this exercise, use the current system date.
For simplicity, disregard the existence of leap years and assume a year has 365
days.

1. Edit the element list of your view entity. Before the exposed association, use code
completion to add a call of SQL function DATS_DAYS_BETWEEN as a new view element.
a) Place the cursor at the beginning of code row /* Associations */ and press Enter
to insert a new row.

b) In the new code row, enter dats and press Ctrl + Space to invoke code-completion.

c) From the suggestion list, choose dats_days_between( date1, date2 ) (function) and
press Shift + Enter to insert the full signature.
Result
This should insert the following code:

dats_days_between( date1, date2 )

© Copyright. All rights reserved. 94


Solution 14: Use Built-in Functions in a CDS View

2. Replace the placeholders with suitable view elements and session variables and specify a
view element name (suggested name: CompanyAffiliation).
a) Adjust the code as follows:

dats_days_between( EntryDate,
$session.system_date ) as CompanyAffiliation,

Note:
Again, we inserted additional line breaks to increase readability in printed
course material.

3. Use the SQL function division to calculate the company affiliation in years, with a
precision of one decimal place.
a) Adjust the code as follows:

division( dats_days_between( EntryDate,


$session.system_date ),
365,
1 ) as CompanyAffiliation,

4. Activate and test the CDS view entity.


a) Press Ctrl + F3 to activate the development object.

b) Press F8 to test the CDS view entity in the Data Preview tool.

Task 3: Perform a Currency Conversion


In a new view element (suggested name: AnnualSalaryConverted), use a suitable SQL
function to convert the content of view element AnnualSalary to currency US Dollar. Use
the current system date as exchange rate date. Then adjust the calculation of view element
MonthlySalary. Use the converted annual salary as input instead of the unconverted annual
salary.

Hint:
You can re-use calculated view elements of the same view entity by using the
$projection prefix.

1. Remove or comment view element CurrencyCode.


a) Place the cursor in the code row CurrencyCode, and press Ctrl + < to add a
comment sign (//) at the begin of the row.

2. In the next code row, define a new view element (suggested name: CurrencyCodeUSD) in
which you convert literal 'USD' to predefined type abap.cuky.
a) Adjust the code as follows:

// CurrencyCode,
cast( 'USD' as /dmo/currency_code ) as CurrencyCodeUSD,

3. Before the MonthlySalary view element, use code completion to insert a call of the SQL
function currency_conversion.

© Copyright. All rights reserved. 95


Unit 6: Using Code Pushdown in CDS Views

a) In a new code row, enter curr and press Ctrl + Space to invoke code-completion.

b) From the suggestion list, choose the entry starting with currency_conversion( amount
=> amount, ... and press Shift + Enter to insert the full signature.

c) The code should now look as follows:

currency_conversion( amount => amount,


source_currency => source_currency ,
target_currency => target_currency,
exchange_rate_date => exchange_rate_date
)

@EndUserText.label: 'Monthly Salary'


@Semantics.amount.currencyCode: 'CurrencyCode'
cast( AnnualSalary as abap.fltp ) / 12.0 as MonthlySalary,

Note:
We inserted additional line breaks, again.

4. Replace the placeholders with values for the parameters. As input, use the annual salary
and the currency code from the source view, own view element CurrencyCodeUSD, and
system variable system_date .
a) Adjust the code as follows:

currency_conversion( amount => AnnualSalary,


source_currency => CurrencyCode ,
target_currency =>
$projection.CurrencyCodeUSD,
exchange_rate_date => $session.system_date
)

5. Add an element name (suggested name: AnnualSalaryConverted), a label, and the


mandatory Semantics.amount.CurrencyCode annotation.
a) Adjust the code as follows:

@EndUserText.label: 'Annual Salary'


@Semantics.amount.currencyCode: 'CurrencyCodeUSD'
currency_conversion( amount => AnnualSalary,
source_currency => CurrencyCode ,
target_currency =>
$projection.CurrencyCodeUSD,
exchange_rate_date => $session.system_date
) as AnnualSalaryConverted,

6. Adjust the calculation of view element MonthlySalary. Instead of AnnualSalary, use


the new view element AnnualSalaryConverted as input.
a) Adjust the code as follows:

@EndUserText.label: 'Monthly Salary'


@Semantics.amount.currencyCode: 'CurrencyCode'
cast( $projection.AnnualSalaryConverted as abap.fltp )
/ 12.0 as MonthlySalary,

© Copyright. All rights reserved. 96


Solution 14: Use Built-in Functions in a CDS View

7. Adjust the view element name (suggested name: MonthlySalaryConverted) and adjust
the mandatory Semantics.amount.CurrencyCode annotation.
a) Adjust the code as follows:

@EndUserText.label: 'Monthly Salary'


@Semantics.amount.currencyCode: 'CurrencyCodeUSD'
cast( $projection.AnnualSalaryConverted as abap.fltp )
/ 12.0 as MonthlySalaryConverted,

8. Activate and test the CDS view entity.


a) Press Ctrl + F3 to activate the development object.

b) Press F8 to test the CDS view entity in the Data Preview tool.

© Copyright. All rights reserved. 97


Unit 6
Exercise 15
Define and Use a CDS View Entity with Input
Parameters

You extended your CDS view entity with SQL functions and used literals and session variables
as input. Now you replace some literals and session variables with input parameters.
Template:

/LRN/CL_S4D430_RLS_PATH_EXPR (Global Class)

Solution:

/LRN/C_EMPLOYEE_PAR (Data Definition)


/LRN/CL_S4D430_CPS_PARAMETER (Global Class)

Task 1: Define Input Parameters


Create a copy of the CDS view entity that you worked on in the previous exercise (suggested
name: Z##_C_EmployeeQueryP, where ## is your group number).

Note:
If you have not finished the previous exercise, create a copy of CDS data
definition /LRN/C_EMPLOYEE_FNC, instead.

In the new data definition, replace the hard-coded target currency with an input parameter
(suggested name: p_target_curr) and session variable $session.system_field with a
second input parameter (suggested name: p_date).

1. Create a copy of your data definition with SQL functions (suggested name was:
Z##_C_EmployeeQuery, where ## is your group number). Alternatively , copy from data
definition /LRN/C_EMPLOYEE_FNC (suggested name for the new view entity:
Z##_C_EmployeeQueryP).

2. Edit the definition of your view entity. Define an input parameter to replace the hard-coded
currency code for the currency conversion (suggested name: p_target_curr). Use the
same type that is used in the CurrencyCodeUSD view element.

3. Define a second input parameter to replace the usage of session variable


$session.system_date (suggested name: p_date). Use a suitable predefined type.

4. Annotate the second parameter with a label (suggested value: Date of evaluation).

Note:
This is not necessary for the first parameter because that parameter is typed
with a data element.

© Copyright. All rights reserved. 98


Exercise 15: Define and Use a CDS View Entity with Input Parameters

5. In the definition of the CurrencyCodeUSD view element, replace the CAST expression
with the input parameter.

Hint:
Use code-completion to access the parameter.

6. Adjust the name of the CurrencyCodeUSD view element (suggested name:


CurrencyCode).

Note:
Do not forget to also adjust the value of the two
@Semantics.amount.currencyCode annotations.

7. In the currency conversion, replace session variable $session.system_date with the


date parameter.

8. In the calculation of the CompanyAffiliation view element, replace session variable


$session.system_date with the date parameter.

9. Activate and test the CDS view entity.

Which of the parameters are mandatory?

Task 2: Use Input Parameters in ABAP SQL


Create a copy of ABAP class /LRN/CL_S4D430_RLS_PATH_EXPR (suggested name:
ZCL_##_PARAMETER, where ## is your group number). In the new class, adjust the SELECT
statement. In the FROM clause, replace CDS view entity /LRN/C_Employee_Qry with the
CDS view entity that you created in this exercise (suggested name was:
Z##_C_EmployeeQueryP). In the FIELDS list, add some view elements that use the input
parameters.

1. Copy the /LRN/CL_S4D430_RLS_PATH_EXPR class to a class in your own package


(suggested name: ZCL_##_PARAMETER, where ## is for your group number).

2. In the IF_OO_ADT_CLASSRUN~MAIN method, change the SELECT statement. In the FROM


clause, replace /LRN/C_Employee_Qry with the name of the CDS view entity that you
have just created (Z##_C_EmployeeQueryP).

3. Supply the input parameters of the view entity with values. Use a literal for the currency
code (for example, 'JPY') and system field sy-datum for the date parameter.

Hint:
Remember that sy-datum is a host variable and that you have to escape it
with @.

© Copyright. All rights reserved. 99


Unit 6: Using Code Pushdown in CDS Views

4. Add the following view elements to the FIELDS list: MonthlySalaryConverted,


CurrencyCode, CompanyAffiliation.

5. Activate the global class and execute it as a console app.

Task 3: Link Parameter to System Field


Make sure that the ABAP system automatically fills it with the system date when no other
value is specified. Then remove the parameter from the SELECT statement in your ABAP
class.

1. Return to the CDS data definition and annotate the p_date parameter to link it to the
system date. Use code completion to choose the annotation value.

2. Activate and test the CDS view entity.

Which of the parameters are mandatory?

3. Return to your ABAP class and remove or comment the date parameter in the FROM
clause.

4. Activate the global class and execute it as a console app.

© Copyright. All rights reserved. 100


Unit 6
Solution 15
Define and Use a CDS View Entity with Input
Parameters

You extended your CDS view entity with SQL functions and used literals and session variables
as input. Now you replace some literals and session variables with input parameters.
Template:

/LRN/CL_S4D430_RLS_PATH_EXPR (Global Class)

Solution:

/LRN/C_EMPLOYEE_PAR (Data Definition)


/LRN/CL_S4D430_CPS_PARAMETER (Global Class)

Task 1: Define Input Parameters


Create a copy of the CDS view entity that you worked on in the previous exercise (suggested
name: Z##_C_EmployeeQueryP, where ## is your group number).

Note:
If you have not finished the previous exercise, create a copy of CDS data
definition /LRN/C_EMPLOYEE_FNC, instead.

In the new data definition, replace the hard-coded target currency with an input parameter
(suggested name: p_target_curr) and session variable $session.system_field with a
second input parameter (suggested name: p_date).

1. Create a copy of your data definition with SQL functions (suggested name was:
Z##_C_EmployeeQuery, where ## is your group number). Alternatively , copy from data
definition /LRN/C_EMPLOYEE_FNC (suggested name for the new view entity:
Z##_C_EmployeeQueryP).
a) In the Project Explorer view, right-click the Z##_C_EMPLOYEE_QUERY data definition or
the /LRN/C_EMPLOYEE_FUNC data definition to open the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
Z##_C_EmployeeQueryP, where ## stands for your group number.

d) Adjust the description and choose Next.

e) Confirm the transport request and choose Finish.

2. Edit the definition of your view entity. Define an input parameter to replace the hard-coded
currency code for the currency conversion (suggested name: p_target_curr). Use the
same type that is used in the CurrencyCodeUSD view element.

© Copyright. All rights reserved. 101


Unit 6: Using Code Pushdown in CDS Views

a) Adjust the code as follows:

define view entity Z##_C_EmployeeQueryP


with parameters
p_target_curr : /dmo/currency_code
as select from Z##_R_Employee

3. Define a second input parameter to replace the usage of session variable


$session.system_date (suggested name: p_date). Use a suitable predefined type.
a) Adjust the code as follows:

define view entity Z##_C_EmployeeQueryP


with parameters
p_target_curr : /dmo/currency_code,
p_date : abap.dats
as select from Z##_R_Employee

4. Annotate the second parameter with a label (suggested value: Date of evaluation).

Note:
This is not necessary for the first parameter because that parameter is typed
with a data element.

a) Adjust the code as follows:

define view entity Z##_C_EmployeeQueryP


with parameters
p_target_curr : /dmo/currency_code,
@EndUserText.label: 'Date of evaluation'
p_date : abap.dats
as select from Z##_R_Employee

5. In the definition of the CurrencyCodeUSD view element, replace the CAST expression
with the input parameter.

Hint:
Use code-completion to access the parameter.

a) Adjust the code as follows:

// cast( 'USD' as /dmo/currency_code ) as CurrencyCodeUSD,


$parameters.p_target_curr as CurrencyCodeUSD,

6. Adjust the name of the CurrencyCodeUSD view element (suggested name:


CurrencyCode).

Note:
Do not forget to also adjust the value of the two
@Semantics.amount.currencyCode annotations.

© Copyright. All rights reserved. 102


Solution 15: Define and Use a CDS View Entity with Input Parameters

a) Adjust the code as follows:

@EndUserText.label: 'Annual Salary'


@Semantics.amount.currencyCode: 'CurrencyCode'
currency_conversion( amount=> AnnualSalary,
source_currency => CurrencyCode,
target_currency => $projection.CurrencyCode,
exchange_rate_date => $session.system_date
) as AnnualSalaryConverted,

@EndUserText.label: 'Monthly Salary'


@Semantics.amount.currencyCode: 'CurrencyCode'
cast( $projection.AnnualSalaryConverted as abap.fltp )
/ 12.0 as MonthlySalaryConverted,

// CurrencyCode,
// cast( 'USD' as /dmo/currency_code ) as CurrencyCodeUSD,
$parameters.p_target_curr as CurrencyCode,

7. In the currency conversion, replace session variable $session.system_date with the


date parameter.
a) Adjust the code as follows:

@EndUserText.label: 'Annual Salary'


@Semantics.amount.currencyCode: 'CurrencyCode'
currency_conversion( amount => AnnualSalary,
source_currency => CurrencyCode,
target_currency => $projection.CurrencyCode,
exchange_rate_date => $parameters.p_date
) as AnnualSalaryConverted,

8. In the calculation of the CompanyAffiliation view element, replace session variable


$session.system_date with the date parameter.
a) Adjust the code as follows:

division( dats_days_between( EntryDate,


$parameters.p_date ),
365,
1 ) as CompanyAffiliation,

9. Activate and test the CDS view entity.

Which of the parameters are mandatory?

Both parameters are mandatory.

a) Press Ctrl + F3 to activate the development object.

b) Press F8 to test the CDS view entity in the Data Preview tool.

c) Enter values for the two parameters and choose Open Data Preview.

Hint:
Mandatory parameters have an asterisk symbol (*) next to the parameter
name.

© Copyright. All rights reserved. 103


Unit 6: Using Code Pushdown in CDS Views

Task 2: Use Input Parameters in ABAP SQL


Create a copy of ABAP class /LRN/CL_S4D430_RLS_PATH_EXPR (suggested name:
ZCL_##_PARAMETER, where ## is your group number). In the new class, adjust the SELECT
statement. In the FROM clause, replace CDS view entity /LRN/C_Employee_Qry with the
CDS view entity that you created in this exercise (suggested name was:
Z##_C_EmployeeQueryP). In the FIELDS list, add some view elements that use the input
parameters.

1. Copy the /LRN/CL_S4D430_RLS_PATH_EXPR class to a class in your own package


(suggested name: ZCL_##_PARAMETER, where ## is for your group number).
a) In the Project Explorer view, right-click the /LRN/CL_S4D430_RLS_PATH_EXP class to
open the context menu.

b) From the context menu, choose Duplicate ....

c) Enter the name of your package in the Package field. In the Name field, enter the name
ZCL_##_PARAMETER, where ## is your group number.

d) Adjust the description and choose Next.

e) Confirm the transport request and choose Finish.

2. In the IF_OO_ADT_CLASSRUN~MAIN method, change the SELECT statement. In the FROM


clause, replace /LRN/C_Employee_Qry with the name of the CDS view entity that you
have just created (Z##_C_EmployeeQueryP).
a) Adjust the code as follows:

SELECT
FROM Z##C_EmployeeQueryP
FIELDS employeeid,

3. Supply the input parameters of the view entity with values. Use a literal for the currency
code (for example, 'JPY') and system field sy-datum for the date parameter.

Hint:
Remember that sy-datum is a host variable and that you have to escape it
with @.

a) Adjust the code as follows:

SELECT
FROM Z##C_EmployeeQueryP(
p_target_curr = 'JPY',
p_date = @sy-datum )
FIELDS employeeid,

4. Add the following view elements to the FIELDS list: MonthlySalaryConverted,


CurrencyCode, CompanyAffiliation.

© Copyright. All rights reserved. 104


Solution 15: Define and Use a CDS View Entity with Input Parameters

a) Adjust the code as follows:

SELECT
FROM Z##C_EmployeeQueryP(
p_target_curr = 'JPY',
p_date = @sy-datum )
FIELDS employeeid,
firstname,
lastname,
departmentid,

departmentdescription,
assistantname,
\_department\_head-lastname AS headname,

MonthlySalaryConverted,
CurrencyCode,
CompanyAffiliation

INTO TABLE @DATA(result).

5. Activate the global class and execute it as a console app.


a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the global class as a console app.

Task 3: Link Parameter to System Field


Make sure that the ABAP system automatically fills it with the system date when no other
value is specified. Then remove the parameter from the SELECT statement in your ABAP
class.

1. Return to the CDS data definition and annotate the p_date parameter to link it to the
system date. Use code completion to choose the annotation value.
a) Adjust the code as follows:

define view entity Z##_C_EmployeeQueryP


with parameters
p_target_curr : /dmo/currency_code,
@EndUserText.label: 'Date of evaluation'
@Environment.systemField: #SYSTEM_DATE
p_date : abap.dats
as select from Z##_R_Employee

2. Activate and test the CDS view entity.

Which of the parameters are mandatory?

Now only the currency code parameter is mandatory.

a) Press Ctrl + F3 to activate the development object.

b) Press F8 to test the CDS view entity in the Data Preview tool.

c) Enter a value for the currency code parameter and choose Open Data Preview.

© Copyright. All rights reserved. 105


Unit 6: Using Code Pushdown in CDS Views

Hint:
Mandatory parameters have an asterisk symbol (*) next to the parameter
name.

3. Return to your ABAP class and remove or comment the date parameter in the FROM
clause.
a) Adjust the code as follows:

SELECT
FROM /LRN/C_Employee_Par(
p_target_curr = 'JPY'
* , p_date = @sy-datum
)
FIELDS employeeid,

4. Activate the global class and execute it as a console app.


a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the global class as a console app.

© Copyright. All rights reserved. 106


Unit 6
Exercise 16
Process Data Sets in CDS Views

You want to further analyze employee and department data. To do so, you use the DISTINCT
addition, aggregations, grouping, and joins in a CDS view entity.
Template:

n.a.

Solution:

/LRN/C_DEPARTMENT_QRY (Data Definition)

Task 1: Use DISTINCT


Define a new CDS view entity (suggested name: Z##_C_DepartmentQuery) that returns the
ID and description of those departments that have at least one employee assigned to it. As
data source, use your view entity for employee data with functions but without parameters
(suggested name was: Z##_C_EmployeeQuery). Make sure each department is listed only
once.

Note:
If you have not finished the previous exercise, you can let your new view entity
read from view entity /LRN/C_Employee_Fnc.

1. In your own package, create a new data definition (suggested name:


Z##_C_DEPARTMENTQUERY, where ## is your group number). Specify your CDS view
entity Z##_C_EmployeeQuery as Referenced Object and choose the Define View Entity
template to generate the definition statement, some standard annotations and the
element list.

2. Apply source code formatting.

3. Edit the element list of the new data definition. Remove all elements except for
DepartmentID and DepartmentDescription.

4. Activate the data definition and display the query result in the Data Preview tool.

How many data sets are displayed?

5. Edit the data definition and add the DISTINCT addition to the SELECT statement.

6. Activate the data definition and display the query result again.

© Copyright. All rights reserved. 107


Unit 6: Using Code Pushdown in CDS Views

How many data sets are displayed?

Task 2: Use Aggregations and Grouping


For each department, calculate the average company affiliation and the total annual salary of
the employees that are assigned to this department.

1. Remove the DISTINCT addition from your data definition.

2. At the end of the element list, add a new view element (suggested name:
AverageAffiliation). Use aggregate function AVG with argument
CompanyAffiliation.

3. Make sure the result has the same type as the CompanyAffiliation element of the
source view entity.

4. Add a new view element (suggested name: TotalSalary). Use aggregate function SUM
with argument AnnualSalaryConverted.

5. Add the currency code to the element list and annotate the amount field with
@Semantics.amount.currencyCode.

6. Use a quick fix to generate the GROUP BY clause.

7. Activate the data definition and display the query result again.

Task 3: Supply Input Parameters


Replace the data source with your view that provides input parameters (suggested name was:
Z##_C_EmployeeQueryP). To supply the parameters, add the same parameters to your new
view and forward them to the source view.

Note:
If you have not finished the previous exercise, read from CDS view entity /LRN/
C_Employee_Par, instead.

1. In the FROM clause, replace the data source and use your view entity with parameters.
Use code completion to insert the full signature of the data source, that is, the CDS view
entity with its parameters.

2. Define two input parameters for your view. Use the same parameter names, types, and
annotations that are used in the data source.

Hint:
It is easiest if you copy the parameter definitions from the data source.

3. Use the new parameters as input for the data source.

4. In the element list, adjust the name of the currency code element, that is, remove the USD
suffix.

© Copyright. All rights reserved. 108


Exercise 16: Process Data Sets in CDS Views

5. Activate and test the data definition.

Task 4: Use an Outer Join


You want to see all departments, even those which do not have any employees assigned to
them. To achieve this, use an outer join of the current data source and your view entity for
department data (suggested name was: Z##_R_Department).

Note:
If you have not finished the exercise on associations, use CDS view entity /LRN/
C_Department_Rel, instead.

1. In your view entity Z##_C_DepartmentQuery, adjust the FROM clause. At the end of the
clause, add a right outer join of your CDS view entity for department data.

Why is it not possible to use an association here?

2. Define alias names for the two data sources (suggested names: e for employee and d for
department) and add the ON condition.

3. In the element list, read the department ID and the department description from the
department view entity rather than from the employee view entity and make the
department ID a key element.

4. Remove the GROUP BY clause and regenerate it using the quick fix.

5. Add the table alias as a prefix where requested by the syntax check.

6. Activate and test the data definition.

© Copyright. All rights reserved. 109


Unit 6
Solution 16
Process Data Sets in CDS Views

You want to further analyze employee and department data. To do so, you use the DISTINCT
addition, aggregations, grouping, and joins in a CDS view entity.
Template:

n.a.

Solution:

/LRN/C_DEPARTMENT_QRY (Data Definition)

Task 1: Use DISTINCT


Define a new CDS view entity (suggested name: Z##_C_DepartmentQuery) that returns the
ID and description of those departments that have at least one employee assigned to it. As
data source, use your view entity for employee data with functions but without parameters
(suggested name was: Z##_C_EmployeeQuery). Make sure each department is listed only
once.

Note:
If you have not finished the previous exercise, you can let your new view entity
read from view entity /LRN/C_Employee_Fnc.

1. In your own package, create a new data definition (suggested name:


Z##_C_DEPARTMENTQUERY, where ## is your group number). Specify your CDS view
entity Z##_C_EmployeeQuery as Referenced Object and choose the Define View Entity
template to generate the definition statement, some standard annotations and the
element list.
a) In the Project Explorer view, right-click your data definition Z##_C_EMPLOYEEQUERY to
open the context menu.

b) From the context menu, choose New Data Definition.

c) Confirm that the Package field contains the name of your package and that the
Referenced Object field contains the name of your database table definition.

d) In the Name field, enter the name for the CDS view entity (Z##_C_DepartmentQuery,
where ## is your group number).

e) Enter Department (Query) in the Description field and choose Next.

f) Confirm the transport request and choose Next.

© Copyright. All rights reserved. 110


Solution 16: Process Data Sets in CDS Views

Caution:
Make sure you don't choose Finish, yet. If you do, you are not able to
choose the template that you want to use.

g) From the list of Templates, choose Define View Entity, then choose Finish.

2. Apply source code formatting.


a) From the eclipse menu, choose Source Code → Format. Alternatively, choose Shift
+ F1.

3. Edit the element list of the new data definition. Remove all elements except for
DepartmentID and DepartmentDescription.
a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription
}

4. Activate the data definition and display the query result in the Data Preview tool.

How many data sets are displayed?

The Data Preview tool displays 9 rows.

a) Press Ctrl + F3 to activate the development object.

b) Press F8 to invoke the Data Preview tool.

5. Edit the data definition and add the DISTINCT addition to the SELECT statement.
a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select distinct from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription
}

6. Activate the data definition and display the query result again.

How many data sets are displayed?

The Data Preview tool displays 2 rows.

a) Press Ctrl + F3 to activate the development object.

b) Press F8 to invoke the Data Preview tool.

© Copyright. All rights reserved. 111


Unit 6: Using Code Pushdown in CDS Views

Task 2: Use Aggregations and Grouping


For each department, calculate the average company affiliation and the total annual salary of
the employees that are assigned to this department.

1. Remove the DISTINCT addition from your data definition.


a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription
}

2. At the end of the element list, add a new view element (suggested name:
AverageAffiliation). Use aggregate function AVG with argument
CompanyAffiliation.
a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription,
avg( CompanyAffiliation ) as AverageAffiliation
}

3. Make sure the result has the same type as the CompanyAffiliation element of the
source view entity.
a) Place the cursor on CompanyAffiliation and press F2 to display the code element
information. The type of CompanyAffiliation is abap.dec(11,1).

b) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription,
avg( CompanyAffiliation as abap.dec(11,1) ) as AverageAffiliation
}

4. Add a new view element (suggested name: TotalSalary). Use aggregate function SUM
with argument AnnualSalaryConverted.
a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription,
avg( CompanyAffiliation as abap.dec(11,1) ) as
AverageAffiliation ,

sum( AnnualSalaryConverted ) as TotalSalary


}

© Copyright. All rights reserved. 112


Solution 16: Process Data Sets in CDS Views

5. Add the currency code to the element list and annotate the amount field with
@Semantics.amount.currencyCode.
a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription,
avg( CompanyAffiliation as abap.dec(11,1) ) as
AverageAffiliation,
@Semantics.amount.currencyCode: 'CurrencyCodeUSD'
sum( AnnualSalaryConverted ) as TotalSalary,
CurrencyCodeUSD
}

6. Use a quick fix to generate the GROUP BY clause.


a) Place the cursor on select and press Ctrl + 1 to invoke the quick fix. Alternatively,
choose the error icon with a light bulb on the left-hand side of that code row.

b) From the list of available quick fixes, choose Add GROUP BY clause.

c) After applying the quick fix, the code should look as follows:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQuery
{
DepartmentId,
DepartmentDescription,
avg( CompanyAffiliation as abap.dec(11,1) ) as
AverageAffiliation,
@Semantics.amount.currencyCode: 'CurrencyCodeUSD'
sum( AnnualSalaryConverted ) as TotalSalary,
CurrencyCodeUSD
}
group by
DepartmentId,
DepartmentDescription,
CurrencyCodeUSD

7. Activate the data definition and display the query result again.
a) Press Ctrl + F3 to activate the development object.

b) Press F8 to invoke the Data Preview tool.

Task 3: Supply Input Parameters


Replace the data source with your view that provides input parameters (suggested name was:
Z##_C_EmployeeQueryP). To supply the parameters, add the same parameters to your new
view and forward them to the source view.

Note:
If you have not finished the previous exercise, read from CDS view entity /LRN/
C_Employee_Par, instead.

1. In the FROM clause, replace the data source and use your view entity with parameters.
Use code completion to insert the full signature of the data source, that is, the CDS view
entity with its parameters.

© Copyright. All rights reserved. 113


Unit 6: Using Code Pushdown in CDS Views

a) In the FROM clause, replace Z##_C_EmployeeQuery with Z##_C_EmployeeQueryP.


If you used /LRN/C_Employee_Fnc, replace it with /LRN/C_Employee_Par.

b) Place the cursor immediately after the entity name and press Ctrl + Space to
invoke code-completion.

c) Press Shift + Enter to insert the view entity with full signature.

d) Code-completion should adjust the code like this:

define view entity Z##_C_DepartmentQuery


as select from Z##_C_EmployeeQueryP( p_target_curr: , p_date: )

2. Define two input parameters for your view. Use the same parameter names, types, and
annotations that are used in the data source.

Hint:
It is easiest if you copy the parameter definitions from the data source.

a) Hold down the Strg key and choose the view name after FROM to navigate into the
data source.

b) Select the code before as select, including the WITH PARAMETERS addition and
press Ctrl + C to copy the parameter definition to the clipboard.

c) Return to your data definition and insert the parameter definition before as select.

d) The code should now look as follows:

define view entity Z##_C_DepartmentQuery


with parameters
p_target_curr : /dmo/currency_code,
@EndUserText.label: 'Date of evaluation'
@Environment.systemField: #SYSTEM_DATE
p_date : abap.dats
as select from Z##_C_EmployeeQueryP( p_target_curr: , p_date: )

3. Use the new parameters as input for the data source.


a) Adjust the code as follows:

define view entity Z##_C_DepartmentQuery


with parameters
p_target_curr : /dmo/currency_code,
@EndUserText.label: 'Date of evaluation'
@Environment.systemField: #SYSTEM_DATE
p_date : abap.dats
as select from Z##_C_EmployeeQueryP(
p_target_curr: $parameters.p_target_curr,
p_date: $parameters.p_date )

4. In the element list, adjust the name of the currency code element, that is, remove the USD
suffix.

© Copyright. All rights reserved. 114


Solution 16: Process Data Sets in CDS Views

a) adjust the code as follows:

{
DepartmentId,
DepartmentDescription,
avg( CompanyAffiliation as abap.dec(11,1) ) as AverageAffiliation,
@Semantics.amount.currencyCode: 'CurrencyCode'
sum( AnnualSalaryConverted ) as TotalSalary,
CurrencyCode
}

group by
DepartmentId,
DepartmentDescription,
CurrencyCode

5. Activate and test the data definition.


a) Press Ctrl + F3 to activate the development object.

b) Press F8 to invoke the Data Preview tool.

c) Use different values for the P_TARGET_CURR parameter.

Task 4: Use an Outer Join


You want to see all departments, even those which do not have any employees assigned to
them. To achieve this, use an outer join of the current data source and your view entity for
department data (suggested name was: Z##_R_Department).

Note:
If you have not finished the exercise on associations, use CDS view entity /LRN/
C_Department_Rel, instead.

1. In your view entity Z##_C_DepartmentQuery, adjust the FROM clause. At the end of the
clause, add a right outer join of your CDS view entity for department data.

Why is it not possible to use an association here?

Views with input parameters are not supported in path expressions.

a) Adjust the code as follows:

as select
from Z##_C_EmployeeQueryP(
p_target_curr: $parameters.p_target_curr,
p_date: $parameters.p_date )
right outer join Z##_R_Department

2. Define alias names for the two data sources (suggested names: e for employee and d for
department) and add the ON condition.

© Copyright. All rights reserved. 115


Unit 6: Using Code Pushdown in CDS Views

a) Adjust the code as follows:

as select
from Z##_C_EmployeeQueryP(
p_target_curr: $parameters.p_target_curr,
p_date: $parameters.p_date ) as e
right outer join Z##_R_Department as d
on e.DepartmentId = d.Id

3. In the element list, read the department ID and the department description from the
department view entity rather than from the employee view entity and make the
department ID a key element.
a) Adjust the code as follows:

{
d.Id,
d.Description,
avg( CompanyAffiliation as abap.dec(11,1) ) as AverageAffiliation,
@Semantics.amount.currencyCode: 'CurrencyCode'
sum( AnnualSalaryConverted ) as TotalSalary,
CurrencyCode
}

4. Remove the GROUP BY clause and regenerate it using the quick fix.
a) Adjust the code as follows:

group by
d.Id,
d.Description,
CurrencyCode

5. Add the table alias as a prefix where requested by the syntax check.
a) Adjust the code as follows:

{
d.Id,
d.Description,
avg( e.CompanyAffiliation as abap.dec(11,1) ) as
AverageAffiliation,
@Semantics.amount.currencyCode: 'CurrencyCode'
sum( e.AnnualSalaryConverted ) as TotalSalary,
e.CurrencyCode
}
group by
d.Id,
d.Description,
e.CurrencyCode

6. Activate and test the data definition.


a) Press Ctrl + F3 to activate the development object.

b) Press F8 to invoke the Data Preview tool.

© Copyright. All rights reserved. 116


Unit 7
Exercise 17
Create an Authorization Object and CDS
Access Controls

You developed a data model with database tables and CDS view entities. To protect the data
against unauthorized access, you define an authorization field and an authorization object.
Then you create CDS access controls for your CDS view entities.
Template:

n.a.

Solution:

/LRN/DPMNT (Authorization Field)


/LRN/DPMNT (Authorization Object)
/LRN/R_DEPARTMENT_AUT (Access Control)
/LRN/R_EMPLOYEE_AUT (Access Control)
/LRN/C_DEPARTMENT_AUT (Access Control)
/LRN/C_EMPLOYEE_AUT (Access Control)

For this exercise, you need the CDS view entities which you have created in previous
exercises (suggested names were: Z##_R_Department, Z##_R_Employee,
Z##_C_DepartmentQuery, and Z##_C_EmployeeQuery, where ## is your group number). If
you have not finished those exercises, create copies of the four data definitions from
package /LRN/S4D430_EXERCISE, that are ending with _AUT.

Task 1: Define Authorization Object


Define an authorization object to control access to the employee and department data based
on the related department (suggested name: Z##DPMENT, where ## is your group number).
Define the authorization object with two authorization fields: a new authorization field
(suggested name: Z##DPMNT) that is based on your data element for the department ID
(suggested name was: Z##_DEPARTMENT_ID), and the standard authorization field ACTVT
with the default permitted activities.

Note:
If you have not created a data element for the department ID, use the /LRN/
DEPARTMENT_ID data element, instead.

1. Create an authorization field based on the data element for the department ID (suggested
name: Z##DEPMENT).

2. Set your database table for department data as check table (suggested name was:
Z##DEPMENT) and save the authorization field.

© Copyright. All rights reserved. 117


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

Note:
If your authorization field is based on the /LRN/DEPARTMENT_ID data
element, you have to use the database table /LRN/DEPMENT_REL.

3. Create a new authorization object and assign the authorization field to it.

4. Confirm that the new authorization object contains the standard authorization field ACTVT
and the default permitted activities.

5. Save the authorization object.

Task 2: Define Access Controls


Define access controls for your base view entities, that is, the base view entity for department
data (suggested name was: Z##_R_Department) and the base view entity for employee data
(suggested name was: Z##_R_Employee). Use a template that allows you to control the
access based on the authorization object you just created.

Note:
Following a general recommendation, name the access controls after the view
entity they protect.

1. Open your base view entity for department data in the Data Preview tool.

Do you see any data?

2. For this view entity create a CDS access control that defines a CDS role with a PFCG
condition.

3. In the generated code, reference your authorization object.

4. Replace the first placeholder for authorization fields with the name of your authorization
field. Then remove the second placeholder.

5. Use the ACTVT authorization field as a filter field and supply it with the filter value for
activity Display.

6. Reference a suitable entity element to supply the first authorization field. Then remove the
placeholder for a second view element.

7. Activate the access control and refresh the display in the Data Preview tool.

Why does the tool no longer display any data?

© Copyright. All rights reserved. 118


Exercise 17: Create an Authorization Object and CDS Access Controls

8. To see at least some data, edit the CDS access control again and replace your own
authorization object Z##DPMNT with the solution object /LRN/DPMNT and your own
authorization field Z##DPMNT with the authorization field /LRN/DPMNT. For this
authorization object your user already has some authorizations.

Which departments are displayed now?

9. In the same way, create a CDS access control for your base view entity for employee data.

10. Activate the access control.

Task 3: Define Inheriting Access Controls


Define an access control for the view entity with which you query employee data based on two
input parameters (suggested name was: Z##_C_EmployeeQueryP). In the same way, define
an access control for your view entity with which you query and employee data per
department (suggested name was: Z##_C_DepartmentQuery). In both cases, use a
template that allows you to inherit the authorization rules from the underlying view entities.

Note:
Following a general recommendation, name the access controls after the view
entity they protect.

1. Open the definition of your CDS view entity that queries employee data based on two input
parameters.

From which other CDS view entity does the view entity read its data?

2. For the view entity with parameters, create a CDS access control that defines a CDS role
with inherited conditions.

3. In the generated code, reference the view entity the protected entity uses as data source,
that is, Z##_R_Employee.

4. Activate the access control.

5. Open the definition of your CDS view entity that aggregates employee data per
department.

Which is the primary data source of this view entity?

6. Define an access control that inherits the access conditions from the primary data source.

© Copyright. All rights reserved. 119


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

7. Activate the access control.

© Copyright. All rights reserved. 120


Unit 7
Solution 17
Create an Authorization Object and CDS
Access Controls

You developed a data model with database tables and CDS view entities. To protect the data
against unauthorized access, you define an authorization field and an authorization object.
Then you create CDS access controls for your CDS view entities.
Template:

n.a.

Solution:

/LRN/DPMNT (Authorization Field)


/LRN/DPMNT (Authorization Object)
/LRN/R_DEPARTMENT_AUT (Access Control)
/LRN/R_EMPLOYEE_AUT (Access Control)
/LRN/C_DEPARTMENT_AUT (Access Control)
/LRN/C_EMPLOYEE_AUT (Access Control)

For this exercise, you need the CDS view entities which you have created in previous
exercises (suggested names were: Z##_R_Department, Z##_R_Employee,
Z##_C_DepartmentQuery, and Z##_C_EmployeeQuery, where ## is your group number). If
you have not finished those exercises, create copies of the four data definitions from
package /LRN/S4D430_EXERCISE, that are ending with _AUT.

Task 1: Define Authorization Object


Define an authorization object to control access to the employee and department data based
on the related department (suggested name: Z##DPMENT, where ## is your group number).
Define the authorization object with two authorization fields: a new authorization field
(suggested name: Z##DPMNT) that is based on your data element for the department ID
(suggested name was: Z##_DEPARTMENT_ID), and the standard authorization field ACTVT
with the default permitted activities.

Note:
If you have not created a data element for the department ID, use the /LRN/
DEPARTMENT_ID data element, instead.

1. Create an authorization field based on the data element for the department ID (suggested
name: Z##DEPMENT).
a) In the Project Explorer, right-click your package to open the context menu and choose
New → Other ABAP Repository Object.

b) In the filter field, enter au and choose Authorization Field from the suggestion list.

© Copyright. All rights reserved. 121


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

c) Enter Z##DPMNT as Name and Z##_DEPARTMENT_ID as Data Element. Then choose


Next.

d) Confirm the transport request and choose Finish.

2. Set your database table for department data as check table (suggested name was:
Z##DEPMENT) and save the authorization field.

Note:
If your authorization field is based on the /LRN/DEPARTMENT_ID data
element, you have to use the database table /LRN/DEPMENT_REL.

a) Place the cursor in theCheck Table field, enter Z## and press Ctrl + Space to open a
value help.

b) From the value help, choose Z##DEPMENT.

c) Press Ctrl + S to save the authorization field.

3. Create a new authorization object and assign the authorization field to it.
a) In the definition of the authorization field, scroll down to the What's next? section and
choose Create a new Authorization Object and assign the Authorization Field to it.

b) Enter Z##DPMNT as Name and Authorization per department as Description,


then choose Next.

c) Confirm the transport request and choose Finish.

4. Confirm that the new authorization object contains the standard authorization field ACTVT
and the default permitted activities.
a) Inspect the Authorization Fields section which should contain your own authorization
field and the default authorization field ACTVT.

b) Inspect the Permitted Activities section which should contain the four default activities.

5. Save the authorization object.


a) Press Ctrl + S to save the authorization object.

Task 2: Define Access Controls


Define access controls for your base view entities, that is, the base view entity for department
data (suggested name was: Z##_R_Department) and the base view entity for employee data
(suggested name was: Z##_R_Employee). Use a template that allows you to control the
access based on the authorization object you just created.

Note:
Following a general recommendation, name the access controls after the view
entity they protect.

1. Open your base view entity for department data in the Data Preview tool.

© Copyright. All rights reserved. 122


Solution 17: Create an Authorization Object and CDS Access Controls

Do you see any data?

Yes, the tool displays data.

a) Open the definition of the view entity and press F8 to open the Data Preview tool.

2. For this view entity create a CDS access control that defines a CDS role with a PFCG
condition.
a) In the Project Explorer, locate your CDS data definition Z##_R_DEPARTMENT.

b) Right-click the data definition to open the context menu and choose New Access
Control.

c) Copy the name from the Protected Entity field to the Name field.

d) In the Description field, enter Department (Access Control), then choose Next.

e) Confirm the transport request and choose Next.

f) From the list of Templates, choose Define Role with PFCG Aspect, and choose Finish.

3. In the generated code, reference your authorization object.


a) Adjust the code as follows:

define role Z##_R_DEPARTMENT


{
grant select on Z##_R_Department
where (entity_element_1, entity_element_2)
= aspect pfcg_auth(
Z##DPMNT,
authorization_field_1,
authorization_field_2,
filter_field_1 = 'filter_value_1'
);
}

Note:
We introduced additional line-breaks to increase readability in printed
training material.

4. Replace the first placeholder for authorization fields with the name of your authorization
field. Then remove the second placeholder.
a) Adjust the code as follows:

define role Z##_R_DEPARTMENT


{
grant select on Z##_R_Department
where (entity_element_1, entity_element_2)
= aspect pfcg_auth(
Z##DPMNT,
Z##DPMNT,
filter_field_1 = 'filter_value_1'
);
}

© Copyright. All rights reserved. 123


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

5. Use the ACTVT authorization field as a filter field and supply it with the filter value for
activity Display.
a) Adjust the code as follows:

define role Z##_R_DEPARTMENT


{
grant select on Z##_R_Department
where (entity_element_1, entity_element_2)
= aspect pfcg_auth(
Z##DPMNT,
Z##DPMNT,
ACTVT = '03'
);
}

6. Reference a suitable entity element to supply the first authorization field. Then remove the
placeholder for a second view element.
a) Adjust the code as follows:

define role Z##_R_DEPARTMENT


{
grant select on Z##_R_Department
where ( Id )
= aspect pfcg_auth(
Z##DPMNT,
Z##DPMNT,
ACTVT = '03'
);
}

7. Activate the access control and refresh the display in the Data Preview tool.

Why does the tool no longer display any data?

The authorization object is new. Therefore, your user does not have any authorizations for
departments, yet.

a) Press Ctrl + F3 to activate the development object.

b) Return to the Data Preview for the protected entity and choose Refresh.

c) Alternatively, you can press F5 to refresh the displayed data.

8. To see at least some data, edit the CDS access control again and replace your own
authorization object Z##DPMNT with the solution object /LRN/DPMNT and your own
authorization field Z##DPMNT with the authorization field /LRN/DPMNT. For this
authorization object your user already has some authorizations.

Which departments are displayed now?

The department with the department ID ADMIN is displayed now.

a) Return to the source code of your CDS access control.

© Copyright. All rights reserved. 124


Solution 17: Create an Authorization Object and CDS Access Controls

b) Adjust the code as follows:

define role Z##_R_DEPARTMENT


{
grant select on Z##_R_Department
where ( Id )
= aspect pfcg_auth(
/LRN/DPMNT,
/LRN/DPMNT,
ACTVT = '03'
);
}

c) Activate the access control and refresh the display in the Data Preview tool.

9. In the same way, create a CDS access control for your base view entity for employee data.
a) In the project explorer, locate your CDS data definition Z##_R_EMPLOYEE.

b) Right-click the data definition to open the context menu and choose New Access
Control.

c) Copy the name from the Protected Entity field to the Name field.

d) In the Description field, enter Employee (Access Control), then choose Next.

e) Confirm the transport request and choose Next.

f) From the list of Templates, choose Define Role with PFCG Aspect, and choose Finish.

g) Adjust the generated code as follows:

define role Z##_R_EMPLOYEE


{
grant select on Z##_R_Employee
where ( DepartmentId )
= aspect pfcg_auth(
/LRN/DPMNT,
/LRN/DPMNT,
ACTVT = '03'
);
}

10. Activate the access control.


a) Press Ctrl + F3 to activate the development object.

Task 3: Define Inheriting Access Controls


Define an access control for the view entity with which you query employee data based on two
input parameters (suggested name was: Z##_C_EmployeeQueryP). In the same way, define
an access control for your view entity with which you query and employee data per
department (suggested name was: Z##_C_DepartmentQuery). In both cases, use a
template that allows you to inherit the authorization rules from the underlying view entities.

Note:
Following a general recommendation, name the access controls after the view
entity they protect.

© Copyright. All rights reserved. 125


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

1. Open the definition of your CDS view entity that queries employee data based on two input
parameters.

From which other CDS view entity does the view entity read its data?

It reads from the base view entity for employee data, that is, from view entity
Z##_R_Employee.

a) Press Ctrl + Shift + A.

b) Enter the name of the CDS data definition that you want to open, that is
Z##_C_EMPLOYEEQUERYP, and choose OK.

2. For the view entity with parameters, create a CDS access control that defines a CDS role
with inherited conditions.
a) In the Project Explorer, locate your CDS data definition Z##_C_EMPLOYEEQUERYP.

b) Right-click the data definition to open the context menu and choose New Access
Control.

c) Copy the name from the Protected Entity field to the Name field.

d) In the Description field, enter Employee Query (Access Control), then choose
Next.

e) Confirm the transport request and choose Next.

f) From the list of Templates, choose Define Role with Inherited Conditions, and choose
Finish.

3. In the generated code, reference the view entity the protected entity uses as data source,
that is, Z##_R_Employee.
a) Adjust the code as follows:

define role Z##_C_EMPLOYEEQUERYP {


grant select on Z##_C_EmployeeQueryP
where inheriting conditions
from entity Z##_R_Employee;
}

4. Activate the access control.


a) Press Ctrl + F3 to activate the development object.

5. Open the definition of your CDS view entity that aggregates employee data per
department.

Which is the primary data source of this view entity?

In a right outer join, the main data source is on the right-hand side. Therefore, the primary
data source is the base view entity for department data, that is, view entity
Z##_R_Department.

© Copyright. All rights reserved. 126


Solution 17: Create an Authorization Object and CDS Access Controls

a) Press Ctrl + Shift + A.

b) Enter the name of the CDS data definition that you want to open, that is
Z##_C_DEPARTMENTQUERY, and choose OK.

6. Define an access control that inherits the access conditions from the primary data source.
a) In the Project Explorer, locate your CDS data definition Z##_C_DEPARTMENTQUERY.

b) Right-click the data definition to open the context menu and choose New Access
Control.

c) Copy the name from the Protected Entity field to the Name field.

d) In the Description field, enter Department Query (Access Control), then choose
Next.

e) Confirm the transport request and choose Next.

f) From the list of Templates, choose Define Role with Inherited Conditions, and choose
Finish.

g) Adjust the generated code as follows:

define role Z##_C_DEPARTMENTQUERY {


grant select on Z##_C_DepartmentQuery
where inheriting conditions
from entity Z##_R_Department;
}

7. Activate the access control.


a) Press Ctrl + F3 to activate the development object.

© Copyright. All rights reserved. 127


Unit 7
Exercise 18
Extend a Database Table Definition

You want to extend a database table with additional fields. Instead of editing the database
table definition directly, you create an APPEND structure.

Note:
In this exercise, you extend your own database table for employee data
(suggested name was: Z##EMPLOY, where ## is your group number). This is done
for simplicity. To motivate the use of the append technique, you have to pretend
that the database table lies in a different name space and that you are not
authorized to make direct changes to it.

Template:

n.a.

Solution:

/LRN/S_EXT_EMPLOYEE ( Structure Type)

For this exercise, you need the database table definition for employee data that you created in
a previous exercise (suggested name was: Z##EMPLOY, where ## is your group number). If
you have not created that database table, create it now as a copy of database table
definition /LRN/EMPLOY_REL.

Task 1: Enable Extensibility


Adjust the extensibility settings of your database table for employee data (suggested name
was: Z##EMPLOY, where ## is your group number). Allow the extension with fields of flat data
types, that is char-like and numeric fields. Enforce that the names of additional fields end with
the same letters (suggested value: ZEM).

1. Open the definition of your database table for employee data.

2. Adjust the extension category to allow the extension with char-like and numeric fields.

3. Define a mandatory suffix for the additional fields (suggested value: ZEM).

4. Activate the database table.

Task 2: Create Append Structure


Create an append structure (suggested name: Z##_S_EXT_EMPLOYEE, where ## is your
group number) to extend your database table for employee data (suggested name was:
Z##EMPLOY). Add a field for the employee's title (suggested name: ZZTITLE_ZEM) and a field
for the country where the employee is based (suggested name: ZZCOUNTRY_ZEM). Type the
new fields with data elements /DMO/TITLE and LAND1.

1. Use a quick fix to create an append structure for this table (suggested name:
Z##_S_EXT_EMPLOYEE, where ## is your group number) .

© Copyright. All rights reserved. 128


Exercise 18: Extend a Database Table Definition

2. In the component list of the append structure, define a new component (suggested name:
zztitle) with data element /DMO/TITLE as component type.

Would it be possible to name the new component zztitle ?

Would it be possible to name the new component ztitle_zem or just title_zem ?

3. Define a second component (suggested name: zzcountry_zem) with data element


LAND1 as its component type.

4. Activate the append structure.

5. Display the Tooltip Description for the extended database table to confirm that the table
contains the new fields.

Task 3: Fill Extension Fields


In your employee table, fill the extension fields. To do so, create a copy of the ABAP
class /LRN/CL_S4D430_CHECK_AND_FILL and adjust the values of constants c_version
and c_employ_table. Then activate and execute the class as a console app.

1. Create a copy of ABAP class /LRN/CL_S4D430_CHECK_AND_FILL, name it


Z##_S4D430_CHECK_AND_FILL and place it in your package ZS4D430_##.

Note:
Skip this step if you created a copy of /LRN/CL_S4D430_CHECK_AND_FILL in
an earlier exercise.

2. Change the value of constant c_version to lcl_generator=>with_extensions.

Hint:
You can add a comment sign in front of the current definition and remove the
comment sign from the second definition alternative.

3. If necessary, change the value of the c_employ_table constant to the name of your
database table.

Note:
The c_depment_table constant is not needed in this version of the code.

© Copyright. All rights reserved. 129


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

4. Activate the ABAP class and execute it as a console app. If the console output contains
errors, adjust the definition of your database table for employees until it is compatible with
the database table definition /LRN/EMPLOY_EXT.

© Copyright. All rights reserved. 130


Unit 7
Solution 18
Extend a Database Table Definition

You want to extend a database table with additional fields. Instead of editing the database
table definition directly, you create an APPEND structure.

Note:
In this exercise, you extend your own database table for employee data
(suggested name was: Z##EMPLOY, where ## is your group number). This is done
for simplicity. To motivate the use of the append technique, you have to pretend
that the database table lies in a different name space and that you are not
authorized to make direct changes to it.

Template:

n.a.

Solution:

/LRN/S_EXT_EMPLOYEE ( Structure Type)

For this exercise, you need the database table definition for employee data that you created in
a previous exercise (suggested name was: Z##EMPLOY, where ## is your group number). If
you have not created that database table, create it now as a copy of database table
definition /LRN/EMPLOY_REL.

Task 1: Enable Extensibility


Adjust the extensibility settings of your database table for employee data (suggested name
was: Z##EMPLOY, where ## is your group number). Allow the extension with fields of flat data
types, that is char-like and numeric fields. Enforce that the names of additional fields end with
the same letters (suggested value: ZEM).

1. Open the definition of your database table for employee data.


a) Press Ctrl + Shift + A, enter the name of the database table definition and
choose OK.

2. Adjust the extension category to allow the extension with char-like and numeric fields.
a) Change the value of annotation @ABAPCatalog.enhancement.category from
#NOT_EXTENSIBLE to #EXTENSIBLE_CHARACTER_NUMERIC.

3. Define a mandatory suffix for the additional fields (suggested value: ZEM).
a) Add annotation @ABAPCatalog.enhancement.fieldSuffix.

b) Adjust the code as follows:

@AbapCatalog.enhancement.category : #EXTENSIBLE_CHARACTER_NUMERIC
@AbapCatalog.enhancement.fieldSuffix : 'ZEM'

4. Activate the database table.

© Copyright. All rights reserved. 131


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

a) Press Ctrl + F3 to activate the development object.

Task 2: Create Append Structure


Create an append structure (suggested name: Z##_S_EXT_EMPLOYEE, where ## is your
group number) to extend your database table for employee data (suggested name was:
Z##EMPLOY). Add a field for the employee's title (suggested name: ZZTITLE_ZEM) and a field
for the country where the employee is based (suggested name: ZZCOUNTRY_ZEM). Type the
new fields with data elements /DMO/TITLE and LAND1.

1. Use a quick fix to create an append structure for this table (suggested name:
Z##_S_EXT_EMPLOYEE, where ## is your group number) .
a) Place the cursor on the name of the database table and press Ctrl + 1 to invoke the
quick fix.

b) From the list of available quick fixes, choose Create append structure for ....

c) Under Name, enter Z##_S_EXT_EMPLOYEE and under Description, enter Employee


(Append Structure), then choose Next.

d) Assign the append structure to a transport request and choose Finish.

2. In the component list of the append structure, define a new component (suggested name:
zztitle) with data element /DMO/TITLE as component type.

Would it be possible to name the new component zztitle ?

No. The database table definition specifies the mandatory field suffix ZEM.

Would it be possible to name the new component ztitle_zem or just title_zem ?

No. The append structure lies in the customer name space (because its name starts with
Z* or Y*). As a consequence, all components in the append structure have to start with
ZZ* or YY*.

a) Adjust the code as follows:

extend type z##employ with z##_s_ext_employee {


zztitle_zem : /dmo/title;
}

3. Define a second component (suggested name: zzcountry_zem) with data element


LAND1 as its component type.
a) Adjust the code as follows:

extend type z##employ with z##_s_ext_employee {


zztitle_zem : /dmo/title;
zzcountry_zem : land1;
}

4. Activate the append structure.


a) Press Ctrl + F3 to activate the development object.

© Copyright. All rights reserved. 132


Solution 18: Extend a Database Table Definition

5. Display the Tooltip Description for the extended database table to confirm that the table
contains the new fields.
a) In the code row that begins with extend type, place the cursor on z##employ and
press F2.

Task 3: Fill Extension Fields


In your employee table, fill the extension fields. To do so, create a copy of the ABAP
class /LRN/CL_S4D430_CHECK_AND_FILL and adjust the values of constants c_version
and c_employ_table. Then activate and execute the class as a console app.

1. Create a copy of ABAP class /LRN/CL_S4D430_CHECK_AND_FILL, name it


Z##_S4D430_CHECK_AND_FILL and place it in your package ZS4D430_##.

Note:
Skip this step if you created a copy of /LRN/CL_S4D430_CHECK_AND_FILL in
an earlier exercise.

a) In the Project Explorer view, locate the ABAP class in the /LRN/S4D430_EXERCISE
package and right-click it to open the context menu.

b) From the context menu, choose Duplicate.

c) Enter the name of your package, the name for the copy and a description. Then choose
Next.

d) Assign the new object to a transport request and choose Finish.

2. Change the value of constant c_version to lcl_generator=>with_extensions.

Hint:
You can add a comment sign in front of the current definition and remove the
comment sign from the second definition alternative.

a) Adjust the code as follows:

* CONSTANTS c_version TYPE t_version VALUE


lcl_generator=>employee_table_only.
* CONSTANTS c_version TYPE t_version VALUE
lcl_generator=>with_relationships.
CONSTANTS c_version TYPE t_version VALUE
lcl_generator=>with_extensions.

3. If necessary, change the value of the c_employ_table constant to the name of your
database table.

Note:
The c_depment_table constant is not needed in this version of the code.

a) Scroll down to the code row starting with CONSTANTS c_employ_table.

b) If the literal after VALUE still contains ##, replace it with your group number.

© Copyright. All rights reserved. 133


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

4. Activate the ABAP class and execute it as a console app. If the console output contains
errors, adjust the definition of your database table for employees until it is compatible with
the database table definition /LRN/EMPLOY_EXT.
a) Press Ctrl + F3 to activate the development object.

b) Press F9 to execute the ABAP class as console app.

c) Make sure the console output contains the text Filled table ... for the database table.

© Copyright. All rights reserved. 134


Unit 7
Exercise 19
Extend CDS View Entities

You want to extend CDS view entities with additional elements and associations. Instead of
editing the data definitions directly, you create CDS view extensions.

Note:
In this exercise, you extend your own CDS view entities Z##_R_Employee and
Z##_C_EmployeeQueryP, where ## is your group number. This is done for
simplicity. To motivate the use of extensions, you have to pretend that the view
entities lie in a different name space and that you are not authorized to make
direct changes to them.

Template:

n.a.

Solution:

/LRN/EXT_R_EMPLOYEE ( Data Definition)


/LRN/EXT_C_EMPLOYEE ( Data Definition)

For this exercise, you need the base view entity for employee data (suggested name was:
Z##_R_Employee) that developed in previous exercises. If you have not finished those
exercises, create a copy of data definition /LRN/R_EMPLOYEE_AUT.
In addition, you need the view entity with parameters for employee data (suggested name
was: Z##_C_EmployeeQueryP) . If you have not finished the related exercises, create a copy
of data definition /LRN/C_EMPLOYEE_AUT and let it read from your base view entity.

Task 1: Enable Extensibility


Adjust the extensibility settings of your base view entity for employee data (suggested name
was: Z##_R_Employee , where ## is your group number). Allow the extension of the element
list with fields that come from your database table for employee data (suggested name was
Z##_EMPLOY).
In the same way, adjust the extensibility settings of your view entity with parameters for
employee data (suggested name was: Z##_C_EmployeeQueryP , where ## is your group
number). Allow the extension of the element list with elements that come from your base view
entity (suggested name was Z##_R_Employee).

1. Open the definition of your base view entity for employee data.

2. Adjust the view extension category to allow the extension of the element list.

3. Maintain the list of allowed data sources for the extension. Add the database table from
which the view entity reads to this list.

© Copyright. All rights reserved. 135


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

Note:
To add the database table to the list, you need to define an alias name for it
(suggested alias name: Employee).

4. Define a mandatory suffix for the additional fields (suggested value: ZEM).

5. Activate the data definition.

6. Open the definition of your view entity with parameters for employee data.

7. As before, adjust the view extension category, maintain the allowed data sources, and
define the element suffix.

Note:
Use the same data source alias and element suffix as before.

8. Activate the data definition.

Task 2: Extend the Base View Entity


For your base view entity, create a CDS view extension (suggested name:
Z##EXT_R_EMPLOYEE) to add the fields for the employee's title and the country to the
element list (suggested names were: ZZTITLE_ZEM and ZZCOUNTRY_ZEM).

1. Create a CDS view extension for your CDS view entity Z##_R_Employee.

2. Edit the element list of the view extension. Remove the placeholder and use code-
completion to add the employee's title and country.

3. Define alias names for the new view elements (suggested names: ZZTitleZem and
ZZCoutryZem).

4. Activate the view extension.

5. Display the Tooltip Description for the extended view entity to confirm that it contains the
new elements.

Task 3: Extend the Query View Entity


For your query view entity with parameters, create a CDS view extension (suggested name:
Z##EXT_C_EMPLOYEE) to add the elements that you added to the base view (suggested
elements names were: ZZTitleZem and ZZCountryZem). Also add an SQL function to
concatenate the employee's first name and last name, separated by a single blank (suggested
element name: ZZFullNameZem). Finally, extend the view with a flag that tells you if the
employee is based in the European Union or not (suggested element name: ZZEUBasedZem).

Hint:
The country master data contain a flag IsEuropeanUnionMember. To access
this element, you first have to extend the view with an association to CDS view
entity I_Country (suggested association name: _ZZCountryZem). Then add a
path expression to the element list of the view extension.

© Copyright. All rights reserved. 136


Exercise 19: Extend CDS View Entities

1. Create a CDS view extension for your CDS view entity Z##_C_EmployeeQueryP.

2. Edit the element list of the view extension. Remove the placeholder and use code-
completion to add the employee's title and country.

3. Use the concat_with_space function to concatenate the employee's first name and last
name, separated by a single blank.

4. Add a name for this new element (suggested name: ZZFullNameZem) and use the
relevant annotation to provide a label.

5. Extend the view with an association to CDS view entity I_Country (suggested name:
_ZZCountryZem).

Hint:
In the ON condition, use the country code from the element list and the key
element of view entity I_Country.

6. In the element list, add the IsEuropeanUnionMember element of the association target
(suggested name: ZZEUBasedZem).

7. Activate the view extension and display the Tooltip Description for the extended view
entity to confirm that it contains the new elements.

© Copyright. All rights reserved. 137


Unit 7
Solution 19
Extend CDS View Entities

You want to extend CDS view entities with additional elements and associations. Instead of
editing the data definitions directly, you create CDS view extensions.

Note:
In this exercise, you extend your own CDS view entities Z##_R_Employee and
Z##_C_EmployeeQueryP, where ## is your group number. This is done for
simplicity. To motivate the use of extensions, you have to pretend that the view
entities lie in a different name space and that you are not authorized to make
direct changes to them.

Template:

n.a.

Solution:

/LRN/EXT_R_EMPLOYEE ( Data Definition)


/LRN/EXT_C_EMPLOYEE ( Data Definition)

For this exercise, you need the base view entity for employee data (suggested name was:
Z##_R_Employee) that developed in previous exercises. If you have not finished those
exercises, create a copy of data definition /LRN/R_EMPLOYEE_AUT.
In addition, you need the view entity with parameters for employee data (suggested name
was: Z##_C_EmployeeQueryP) . If you have not finished the related exercises, create a copy
of data definition /LRN/C_EMPLOYEE_AUT and let it read from your base view entity.

Task 1: Enable Extensibility


Adjust the extensibility settings of your base view entity for employee data (suggested name
was: Z##_R_Employee , where ## is your group number). Allow the extension of the element
list with fields that come from your database table for employee data (suggested name was
Z##_EMPLOY).
In the same way, adjust the extensibility settings of your view entity with parameters for
employee data (suggested name was: Z##_C_EmployeeQueryP , where ## is your group
number). Allow the extension of the element list with elements that come from your base view
entity (suggested name was Z##_R_Employee).

1. Open the definition of your base view entity for employee data.
a) Press Ctrl + Shift + A, enter the name of the data definition and choose OK.

2. Adjust the view extension category to allow the extension of the element list.
a) Change the value of annotation @ABAPCatalog.viewEnhancementCategory from
#NONE to #PROJECTION_LIST.

© Copyright. All rights reserved. 138


Solution 19: Extend CDS View Entities

3. Maintain the list of allowed data sources for the extension. Add the database table from
which the view entity reads to this list.

Note:
To add the database table to the list, you need to define an alias name for it
(suggested alias name: Employee).

a) Add the @ABAPCatalog.extensibility.dataSources annotation as follows:

@AbapCatalog: {
dataMaintenance: #RESTRICTED,
viewEnhancementCategory: [#PROJECTION_LIST],
extensibility.dataSources: [ 'Employee' ]
}

b) Define the alias for the data source as follows:

define view entity Z##_R_Employee


as select from z##employ as Employee

4. Define a mandatory suffix for the additional fields (suggested value: ZEM).
a) Add annotation @ABAPCatalog.extensibility.elementSuffix as follows:

@AbapCatalog: {
dataMaintenance: #RESTRICTED,
viewEnhancementCategory: [#PROJECTION_LIST],
extensibility.dataSources: [ 'Employee' ],
extensibility.elementSuffix: 'ZEM'
}

5. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

6. Open the definition of your view entity with parameters for employee data.
a) Press Ctrl + Shift + A, enter the name of the data definition and choose OK.

7. As before, adjust the view extension category, maintain the allowed data sources, and
define the element suffix.

Note:
Use the same data source alias and element suffix as before.

a) Adjust the code as follows:

@AbapCatalog: {
dataMaintenance: #RESTRICTED,
viewEnhancementCategory: [#PROJECTION_LIST],
extensibility.dataSources: [ 'Employee' ],
extensibility.elementSuffix: 'ZEM'
}

© Copyright. All rights reserved. 139


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

b) Define the alias for the data source as follows:

define view entity Z##_C_EmployeeQueryP


with parameters
p_target_curr : /dmo/currency_code,
@EndUserText.label: 'Date of evaluation'
@Environment.systemField: #SYSTEM_DATE
p_date : abap.dats
as select from Z##_R_Employee as Employee

8. Activate the data definition.


a) Press Ctrl + F3 to activate the development object.

Task 2: Extend the Base View Entity


For your base view entity, create a CDS view extension (suggested name:
Z##EXT_R_EMPLOYEE) to add the fields for the employee's title and the country to the
element list (suggested names were: ZZTITLE_ZEM and ZZCOUNTRY_ZEM).

1. Create a CDS view extension for your CDS view entity Z##_R_Employee.
a) In the Project Explorer, locate data definition Z##_R_EMPLOYEE, right-click it and
choose New Data Definition.

b) Ensure that the Package field contains the name of your own package.

c) Enter Z##EXT_R_Employee in Name and Extension of Z##_R_Employee in


Description. Then choose Next.

d) Confirm the transport request and choose Next.

Note:
Do not choose Finish yet or you will not be able to choose the correct
template.

e) From the list of Templates, choose Extend View Entity and choose Finish.

2. Edit the element list of the view extension. Remove the placeholder and use code-
completion to add the employee's title and country.
a) In the source code, replace base_data_source_code.element_name. with zz and
press Ctrl + Space to invoke code-completion.

b) From the suggestion list, choose zztitle_zem- z##employ as employee (column) to add
the append field to the element list of the CDS view extension.

c) Repeat to adjust the code as follows:

extend view entity Z##_R_Employee with


{
employ.zztitle_zem,
employ.zzcountry_zem
}

3. Define alias names for the new view elements (suggested names: ZZTitleZem and
ZZCoutryZem).

© Copyright. All rights reserved. 140


Solution 19: Extend CDS View Entities

a) Adjust the code as follows:

extend view entity Z##_R_Employee with


{
employ.zztitle_zem as ZZTitleZem,
employ.zzcountry_zemas ZZCountryZem
}

4. Activate the view extension.


a) Press Ctrl + F3 to activate the development object.

5. Display the Tooltip Description for the extended view entity to confirm that it contains the
new elements.
a) In the code row that begins with extend view entity, place the cursor on
z##_R_Employee and press F2.

Task 3: Extend the Query View Entity


For your query view entity with parameters, create a CDS view extension (suggested name:
Z##EXT_C_EMPLOYEE) to add the elements that you added to the base view (suggested
elements names were: ZZTitleZem and ZZCountryZem). Also add an SQL function to
concatenate the employee's first name and last name, separated by a single blank (suggested
element name: ZZFullNameZem). Finally, extend the view with a flag that tells you if the
employee is based in the European Union or not (suggested element name: ZZEUBasedZem).

Hint:
The country master data contain a flag IsEuropeanUnionMember. To access
this element, you first have to extend the view with an association to CDS view
entity I_Country (suggested association name: _ZZCountryZem). Then add a
path expression to the element list of the view extension.

1. Create a CDS view extension for your CDS view entity Z##_C_EmployeeQueryP.
a) In the Project Explorer, locate data definition Z##_C_EMPLOYEEQUERYP, right-click it
and choose New Data Definition.

b) Ensure that the Package field contains the name of your own package.

c) Enter Z##EXT_C_Employee in Name and Extension of Z##_C_EmployeeQueryP


in Description. Then choose Next.

d) Confirm the transport request and choose Next.

Note:
Do not choose Finish yet or you will not be able to choose the correct
template.

e) From the list of Templates, choose Extend View Entity and choose Finish.

2. Edit the element list of the view extension. Remove the placeholder and use code-
completion to add the employee's title and country.

© Copyright. All rights reserved. 141


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

a) In the source code, replace base_data_source_code.element_name. with zz and


press Ctrl + Space to invoke code-completion.

b) From the suggestion list, choose ZZTitleZem - Z##_R_Employ as Employee (column)


to add the extension field to the element list.

c) Repeat to adjust the code as follows:

extend view entity Z##_C_EmployeeQueryP with


{
Employee.ZZTitleZem,
Employee.ZZContryZem
}

3. Use the concat_with_space function to concatenate the employee's first name and last
name, separated by a single blank.
a) Adjust the code as follows:

extend view entity Z##_C_EmployeeQueryP with


{
Employee.ZZTitleZem,
Employee.ZZContryZem,

concat_with_space( Employee.FirstName, Employee.LastName, 1 )


}

4. Add a name for this new element (suggested name: ZZFullNameZem) and use the
relevant annotation to provide a label.
a) Adjust the code as follows:

extend view entity Z##_C_EmployeeQueryP with


{
Employee.ZZTitleZem,
Employee.ZZContryZem,

@
concat_with_space( Employee.FirstName, Employee.LastName, 1 ) as
ZZFullNameZem
}

5. Extend the view with an association to CDS view entity I_Country (suggested name:
_ZZCountryZem).

Hint:
In the ON condition, use the country code from the element list and the key
element of view entity I_Country.

a) Adjust the code as follows:

extend view entity Z##_C_EmployeeQueryP with


association [1..1] to I_Country as _ZZCountryZem
on $projection.ZZCountryZem = _ZZCountryZem.Country
{
Employee.ZZTitleZem,
Employee.ZZContryZem,

© Copyright. All rights reserved. 142


Solution 19: Extend CDS View Entities

concat_with_space( Employee.FirstName,
Employee.LastName,
1 ) as ZZFullNameZem
}

6. In the element list, add the IsEuropeanUnionMember element of the association target
(suggested name: ZZEUBasedZem).
a) Adjust the code as follows:

extend view entity Z##_C_EmployeeQueryP with


association [1..1] to I_Country as _ZZCountryZem
on $projection.ZZCountryZem = _ZZCountryZem.Country
{
Employee.ZZTitleZem,
Employee.ZZContryZem,

concat_with_space( Employee.FirstName,
Employee.LastName,
1 ) as ZZFullNameZem,

_ZZCountryZem.IsEuropeanUnionMember as ZZEUBasedZem
}

7. Activate the view extension and display the Tooltip Description for the extended view
entity to confirm that it contains the new elements.
a) Press Ctrl + F3 to activate the development object.

b) In the code row that begins with extend view entity, place the cursor on
z##_C_EmployeeQueryP and press F2.

© Copyright. All rights reserved. 143


Unit 7
Exercise 20
Create CDS Metadata Extensions

You want to extend the metadata of one of your view entities. In a first step, you outsource
existing annotations into a CDS metadata extension. You then create a second metadata
extension to add more annotations and overwrite existing ones.
Template:

n.a.

Solution:

/LRN/C_EMPLOYEE_MDX (Data Definition)


/LRN/C_EMPLOYEE_MDX (Metadata Extension)
/LRN/C_EMPLOYEE_MDX2 (Metadata Extension)

For this exercise, you need the view entity with parameters for employee data (suggested
name was: Z##_C_EmployeeQueryP) . If you have not finished the related exercises, create a
copy of data definition /LRN/C_EMPLOYEE_EXT.

Task 1: Extract a Metadata Extension


Adjust the definition of your view entity with parameters for employee data (suggested name
was: Z##_C_EmployeeQueryP) and extract all annotations for which this is allowed into a
new metadata extension of the lowest layer. Use the same name for the data definition and
the metadata extension. After the extraction, use a quick fix to allow the extension of the view
entity.

1. Open the definition of your view entity with parameters for employee data and make sure
it is active.

2. Using a refactoring tool, extract all available annotations into a new metadata extension.

3. Use code-completion to set the layer of your metadata extension to the value with the
lowest priority.

4. Use a quick fix to adjust the annotated view entity so that it allows metadata extensions.

5. Activate the metadata extension and the annotated view entity.

6. Open the annotated view entity in the Active Annotations tool and verify that some of the
annotations now come from the metadata extension.

Task 2: Create a Metadata Extension


Based on an appropriate template, create a second metadata extension for the same view
entity as before (suggested name: Z##_C_EMPLOYEE_QUERYP2) . Choose the metadata layer
with the highest priority, overwrite the label for the P_DATE parameter and add a label for the
AssistantName view element.

1. In the Project Explorer, locate the definition of the view entity that you extended in the
previous task.

© Copyright. All rights reserved. 144


Exercise 20: Create CDS Metadata Extensions

2. For this view entity, create a new CDS metadata extension based on the Annotate View
with Parameters template.

3. Use code-completion to set the layer of your metadata extension to the value with the
highest priority.

4. Replace placeholder parameter_name with p_date and add a new label for this
parameter, for example, Currency Conversion Date.

5. Replace the placeholder element_name with AssistantName and add a label for this
view element, for example, Department Assistant.

6. Activate the new metadata extension.

7. Open the annotated view entity in the Active Annotations tool and verify that the label for
the p_date parameter comes from the new metadata extension.

© Copyright. All rights reserved. 145


Unit 7
Solution 20
Create CDS Metadata Extensions

You want to extend the metadata of one of your view entities. In a first step, you outsource
existing annotations into a CDS metadata extension. You then create a second metadata
extension to add more annotations and overwrite existing ones.
Template:

n.a.

Solution:

/LRN/C_EMPLOYEE_MDX (Data Definition)


/LRN/C_EMPLOYEE_MDX (Metadata Extension)
/LRN/C_EMPLOYEE_MDX2 (Metadata Extension)

For this exercise, you need the view entity with parameters for employee data (suggested
name was: Z##_C_EmployeeQueryP) . If you have not finished the related exercises, create a
copy of data definition /LRN/C_EMPLOYEE_EXT.

Task 1: Extract a Metadata Extension


Adjust the definition of your view entity with parameters for employee data (suggested name
was: Z##_C_EmployeeQueryP) and extract all annotations for which this is allowed into a
new metadata extension of the lowest layer. Use the same name for the data definition and
the metadata extension. After the extraction, use a quick fix to allow the extension of the view
entity.

1. Open the definition of your view entity with parameters for employee data and make sure
it is active.
a) Press Ctrl + Shift + A.

b) In the search field, enter Z##_C_, where ## is your group number.

c) From the list of matching items, select entry Z##_C_EmployeeQueryP and choose OK.

d) Press Ctrl + F3 to activate the development object.

2. Using a refactoring tool, extract all available annotations into a new metadata extension.
a) From the Eclipse menu, choose Source Code → Extract Metadata Extension.

b) In the Extended Entity field, enter Z##_C, press Ctrl + Space and choose the name
of the CDS view entity that you want to extend (Z##_C_EmployeeQueryP).

c) Copy that name from the Extended Entity field to the Name field.

d) Enter a description (for example Employee Query (Metadata)) and choose Next.

e) Confirm the transport request and choose Next.

© Copyright. All rights reserved. 146


Solution 20: Create CDS Metadata Extensions

f) Choose Expand All on the right-hand side and analyze the annotations that can be
extracted.

g) Choose Select All on the right-hand side and Finish on the bottom.

3. Use code-completion to set the layer of your metadata extension to the value with the
lowest priority.
a) In the @Metadata.layer annotation, remove placeholder layer.

b) Press Ctrl + Space to invoke code-completion.

c) From the suggestion list, choose value #CORE as this layer has the lowest priority.

4. Use a quick fix to adjust the annotated view entity so that it allows metadata extensions.
a) Place the cursor in the code row starting with annotate view and press Ctrl + 1 to
invoke the quickfix. Alternatively, you can choose the error icon with light bulb next to
this code row.

b) From the list of available quickfixes, choose Add annotation 'Metadata.allowExtensions'


to base view.

5. Activate the metadata extension and the annotated view entity.


a) Press Ctrl + Shift + F3 to activate all inactive development objects.

b) Choose Select All and OK.

c) Choose Select All and Activate.

6. Open the annotated view entity in the Active Annotations tool and verify that some of the
annotations now come from the metadata extension.
a) Right-click anywhere in the source code and choose Open With → Active Annotations.
Result
For some of the annotations, column Origin Data Source should contain your metadata
extension.

Task 2: Create a Metadata Extension


Based on an appropriate template, create a second metadata extension for the same view
entity as before (suggested name: Z##_C_EMPLOYEE_QUERYP2) . Choose the metadata layer
with the highest priority, overwrite the label for the P_DATE parameter and add a label for the
AssistantName view element.

1. In the Project Explorer, locate the definition of the view entity that you extended in the
previous task.
a) For example, expand the Core Data Services → Data Definitions subnode of your
package ZS4D430_##.

2. For this view entity, create a new CDS metadata extension based on the Annotate View
with Parameters template.
a) Right-click the data definition name to open the context menu and choose New
Metadata Extension.

b) Copy the value from the Extended Entity field to the Name field and add character 2 to
distinguish it from the already existing metadata extension.

© Copyright. All rights reserved. 147


Unit 7: Defining Meta Objects for Dictionary Objects and CDS Views

c) Enter a description (for example Employee Query (Final Metadata)) and choose
Next.

d) Confirm the transport request and choose Next.

e) From the list of available templates select Annotate View with Parameters and choose
Finish.

3. Use code-completion to set the layer of your metadata extension to the value with the
highest priority.
a) In the @Metadata.layer annotation, remove placeholder layer.

b) Press Ctrl + Space to invoke code-completion.

c) From the suggestion list, choose value #CUSTOMER as this layer has the highest
priority.

4. Replace placeholder parameter_name with p_date and add a new label for this
parameter, for example, Currency Conversion Date.
a) Adjust the code as follows:

@Metadata.layer: #CUSTOMER
annotate view Z##_C_EmployeeQueryP
with parameters
@EndUserText.label: 'Currency Conversion Date'
p_date
{
element_name;

5. Replace the placeholder element_name with AssistantName and add a label for this
view element, for example, Department Assistant.
a) Adjust the code as follows:

@Metadata.layer: #CUSTOMER
annotate view Z##_C_EmployeeQueryP
with parameters
@EndUserText.label: 'Currency Conversion Date'
p_date
{
@EndUserText.label: 'Department Assistant'
AssistantName;
}

6. Activate the new metadata extension.


a) Press Ctrl + F3 to activate the development object.

7. Open the annotated view entity in the Active Annotations tool and verify that the label for
the p_date parameter comes from the new metadata extension.
a) Right-click anywhere in the source code and choose Open With → Active Annotations.

© Copyright. All rights reserved. 148

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy