Sie sind auf Seite 1von 129

Introduction to ABAP

- ABAP Dictionary and databases-

Prof. Dr. Heimo H. Adelsberger


Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Table of contents
Table of contents ........................................................................................................................ 2
Table of figures .......................................................................................................................... 4
Copyright .................................................................................................................................... 7
8 ABAP Dictionary and databases ........................................................................................ 8
8.1 Excursus: The Data Browser ....................................................................................... 9
8.1.1 Tasks of the Data Browsers .................................................................................. 9
8.1.2 Exercise: Using the Data Browser ....................................................................... 9
8.2 Types of the ABAP Dictionary ................................................................................. 12
8.2.1 From local to global types .................................................................................. 13
8.2.2 Domains ............................................................................................................. 15
8.2.3 Data elements ..................................................................................................... 17
8.2.4 Structures ............................................................................................................ 19
8.2.5 Table types ......................................................................................................... 21
8.2.6 Type groups and constants ................................................................................. 23
8.2.7 Exercise on global types ..................................................................................... 23
8.2.7.1 Create domains ............................................................................................ 24
8.2.7.2 Creating data elements ................................................................................ 25
8.2.7.3 Creating a structure ..................................................................................... 28
8.2.7.4 Creating a table type ................................................................................... 29
8.2.7.5 Using global types ....................................................................................... 30
8.3 Tables......................................................................................................................... 33
8.3.1 Tables as types ................................................................................................... 34
8.3.2 Include structures ............................................................................................... 34
8.3.3 Exercise: Table structure .................................................................................... 35
8.3.4 Technical settings ............................................................................................... 37
8.3.4.1 Logical Storage parameters ......................................................................... 38
8.3.4.2 Table buffering............................................................................................ 39
8.3.4.3 Logging ....................................................................................................... 40
8.3.5 Exercise: Technical settings ............................................................................... 40
8.4 Accessing tables from ABAP programs .................................................................... 42
8.4.1 Native SQL ......................................................................................................... 42
8.4.2 Open SQL ........................................................................................................... 43
8.4.3 Reading data ....................................................................................................... 43
8.4.3.1 The work area for database tables ............................................................... 44
8.4.3.2 Reading a single record ............................................................................... 45
8.4.4 Reading multiple records ................................................................................... 49
8.4.4.1 Reading records into an internal table......................................................... 49
8.4.4.2 Reading into a work area – SELECT as a loop........................................... 51
8.4.5 Exercise: Displaying contents of a table ............................................................ 52
8.4.6 The SELECT statement in detail ........................................................................ 57
8.4.6.1 The SELECT part ....................................................................................... 58
8.4.6.2 The FROM part ........................................................................................... 60
8.4.6.3 The INTO part ............................................................................................. 64
8.4.6.4 Exercise: SELECT statement ...................................................................... 65
8.4.6.5 The WHERE part ........................................................................................ 65
8.4.6.6 The GROUP BY and HAVING parts ......................................................... 68
8.4.6.7 The ORDER BY part .................................................................................. 68
8.4.6.8 Reading data using a cursor ........................................................................ 69
Page 2
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.7 Exercise: Grouping and aggregate functions...................................................... 70


8.4.1 New Syntax in OpenSQL ................................................................................... 72
8.4.2 Inserting data ...................................................................................................... 72
8.4.3 Changing data ..................................................................................................... 73
8.4.4 Automatic insertion or change ........................................................................... 74
8.4.5 Deleting data ...................................................................................................... 75
8.5 Authorizations ........................................................................................................... 76
8.6 Exercise: Authorizations............................................................................................ 79
8.7 Indices ........................................................................................................................ 82
8.8 Exercise: Creating a secondary index ........................................................................ 83
8.9 Buffering .................................................................................................................... 85
8.9.1 Full buffering...................................................................................................... 85
8.9.2 Generic area buffering ........................................................................................ 86
8.9.3 Buffering single records ..................................................................................... 88
8.9.4 Synchronization of buffers ................................................................................. 88
8.10 Views ..................................................................................................................... 94
8.10.1 Exercise: Creating a view ................................................................................... 94
8.10.2 Maintenance dialogues ....................................................................................... 96
8.10.2.1 Exercise: Maintenance dialogs.................................................................... 97
8.10.2.2 View clusters ............................................................................................. 101
8.11 Special kinds of tables ......................................................................................... 102
8.11.1 Cluster tables and table clusters ....................................................................... 102
As you can see in the figure, only the table cluster is part of the database system. The
tables inside the cluster are only visible within the SAP system. .................................. 103
8.11.2 Pool tables and table pools ............................................................................... 103
8.11.3 Rating of pool and cluster tables ...................................................................... 104
8.12 Changing dictionary objects ................................................................................ 106
8.12.1 Dependencies and activation ............................................................................ 106
8.12.2 Activating objects ............................................................................................. 107
8.12.3 Where-used list exercise ................................................................................... 108
8.12.4 Changing tables ................................................................................................ 110
8.12.5 The conversion process .................................................................................... 112
8.12.6 Conversion exercise ......................................................................................... 117
8.12.7 Extending SAP standard tables ........................................................................ 120
8.12.7.1 Append structures ..................................................................................... 120
8.12.7.2 Customizing Includes ................................................................................ 123
8.12.8 Exercise on appends ......................................................................................... 123
8.13 Performance of database requests ........................................................................ 125
8.13.1 Only read data which you actually need .......................................................... 125
8.13.2 Use complete keys ............................................................................................ 126
8.13.3 Replace repeated similar queries by a single query ......................................... 127
8.13.4 Use joins instead of nested SELECTs .............................................................. 127
8.13.5 Trade-off........................................................................................................... 128
8.13.5.1 Example: Sorting ...................................................................................... 128
8.13.5.2 Example: Calculation of aggregate functions ........................................... 128
8.14 Chapter submission .............................................................................................. 129

Page 3
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Table of figures
Figure 1: Overview of the Dictionary ........................................................................................ 8
Figure 2: A selection screen of the Data Browser: SAP-System-Screenshot .......................... 10
Figure 3: Result list of the Data Browser: SAP-System-Screenshot ....................................... 11
Figure 4: The initial screen of the ABAP Dictionary: SAP-System-Screenshot ..................... 12
Figure 5: External types of the Dictionary: SAP-System-Screenshot ...................................... 13
Figure 6: Basic relationship between types in the Dictionary .................................................. 15
Figure 7: Example domain in the Dictionary: SAP-System-Screenshot .................................. 16
Figure 8: Value range information of the domain: SAP-System-Screenshot .......................... 17
Figure 9: Maintenance of a data element: SAP-System-Screenshot ........................................ 18
Figure 10: The tab for the maintenance of field labels: SAP-System-Screenshot ................... 19
Figure 11: The structure type str_car ....................................................................................... 19
Figure 12: A structure in the ABAP Dictionary: SAP-System-Screenshot ............................. 20
Figure 13: Direct typing of a structure: SAP-System-Screenshot ............................................ 20
Figure 14: A table type in the ABAP Dictionary: SAP-System-Screenshot ............................ 21
Figure 15: Initialization and access settings: SAP-System-Screenshot ................................... 22
Figure 16: Definition of a type group in the ABAP Dictionary: SAP-System-Screenshot ..... 23
Figure 17: Creating a domain in the ABAP Dictionary: SAP-System-Screenshot.................. 24
Figure 18: Definition of the domain in the ABAP Dictionary: SAP-System-Screenshot ....... 25
Figure 19: First step to create a data element: SAP-System-Screenshot ................................. 26
Figure 20: Second step to create a data element: SAP-System-Screenshot ............................. 26
Figure 21: Selecting the technical type for a data element: SAP-System-Screenshot ............. 27
Figure 22: Maintaining field labels: SAP-System-Screenshot ................................................. 27
Figure 23: First step to create a structure in the ABAP Dictionary: SAP-System-Screenshot 28
Figure 24: Second step to create a structure in the ABAP Dictionary: SAP-System-Screenshot
.................................................................................................................................................. 28
Figure 25: Example of a structure for students: SAP-System-Screenshot ............................... 28
Figure 26: First step to create a table type in the ABAP Dictionary: SAP-System-Screenshot
.................................................................................................................................................. 29
Figure 27: Second step to create a table type in the ABAP Dictionary: SAP-System-
Screenshot ................................................................................................................................ 29
Figure 28: Line type selection for the table type: SAP-System-Screenshot ............................ 29
Figure 29: Configuration of the key of a table type: SAP-System-Screenshot ........................ 30
Figure 30: Corrected title: SAP-System-Screenshot ................................................................ 31
Figure 31: Parameter without selection text: SAP-System-Screenshot ................................... 32
Figure 32: Example for a selection text retrieved from the Dictionary: SAP-System-
Screenshot ................................................................................................................................ 32
Figure 33: User interface with a selection text from the ABAP Dictionary: SAP-System-
Screenshot ................................................................................................................................ 32
Figure 34: Different fields, different data elements, same domain .......................................... 34
Figure 35: A structure used as an inclusion in different tables ................................................ 35
Figure 36: Creating a database table: SAP-System-Screenshot ............................................... 35
Figure 37: Fields of the table: SAP-System-Screenshot .......................................................... 36
Figure 38: Expanded include: SAP-System-Screenshot .......................................................... 36
Figure 39: Field list with completed key .................................................................................. 37
Figure 40: Technical settings for a table: SAP-System-Screenshot ......................................... 37
Figure 41: Fragmentation example .......................................................................................... 38
Figure 42: Size categories: SAP-System-Screenshot ............................................................... 39
Figure 43: Buffer ...................................................................................................................... 40
Page 4
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 44: Technical settings of the students table: SAP-System-Screenshot ......................... 41


Figure 45: Structure of a reading database access (overview) ................................................. 44
Figure 46: Query with given set of fields ................................................................................. 46
Figure 47: Explicit specification of target fields ...................................................................... 48
Figure 48: Example for name-based field assignment ............................................................. 49
Figure 49: The array fetch ........................................................................................................ 50
Figure 50: SELECT as a loop .................................................................................................. 51
Figure 51: SELECT loop: SAP-System-Screenshot ................................................................ 52
Figure 52: Program output: SAP-System-Screenshot .............................................................. 53
Figure 53: Selection screen of the flights program: SAP-System-Screenshot ......................... 54
Figure 54: Selection screen including selection text: SAP-System-Screenshot ...................... 54
Figure 55: Creating a function module for reading flights: SAP-System-Screenshot ............. 54
Figure 56: Import parameter of the function module: SAP-System-Screenshot ..................... 55
Figure 57: The table type based on SPFLI: SAP-System-Screenshot ..................................... 55
Figure 58: Using the table type: SAP-System-Screenshot ....................................................... 55
Figure 59: Calling the function module: SAP-System-Screenshot .......................................... 56
Figure 60: New exception: SAP-System-Screenshot ............................................................... 56
Figure 61: Output of a simple error message: SAP-System-Screenshot .................................. 57
Figure 62: Example for a table join ......................................................................................... 61
Figure 63: Output of the join program: SAP-System-Screenshot ............................................ 62
Figure 64: Code of the join program: SAP-System-Screenshot .............................................. 63
Figure 65: Output of the statistic program: SAP-System-Screenshot ...................................... 71
Figure 66: Example of a statistic program: SAP-System-Screenshot ...................................... 71
Figure 67: Overview of the authorization concept ................................................................... 77
Figure 68: The authorization object S_CARRID: SAP-System-Screenshot ........................... 79
Figure 69: Permitted Activities: SAP-System-Screenshot ....................................................... 80
Figure 70: Insert an AUTHORITY-CHECK using the pattern button: SAP-System-Screenshot
.................................................................................................................................................. 80
Figure 71: Code for the authority check: SAP-System-Screenshot ......................................... 81
Figure 72: Access with or without index ................................................................................. 82
Figure 73: Creating an index: SAP-System-Screenshot .......................................................... 83
Figure 74: Maintenance of index properties: SAP-System-Screenshot ................................... 84
Figure 75: Status of the index: SAP-System-Screenshot ......................................................... 84
Figure 76: Full buffering .......................................................................................................... 86
Figure 77: Generic buffering .................................................................................................... 87
Figure 78: Single record buffering ........................................................................................... 88
Figure 79: Buffering in two application servers ....................................................................... 89
Figure 80: Synchronization example, 1/4 ................................................................................ 90
Figure 81: Synchronization example 2/4 ................................................................................. 91
Figure 82: Synchronization example 3/4 ................................................................................. 92
Figure 83: Synchronization example 4/4 ................................................................................. 93
Figure 84: Maintenance view and maintenance dialog ............................................................ 96
Figure 85: Creating a maintenance view: SAP-System-Screenshot ........................................ 97
Figure 86: Relations of the SBUSPART table: SAP-System-Screenshot................................ 98
Figure 87: Automatic join conditions: SAP-System-Screenshot ............................................. 98
Figure 88: Field selection for the maintenance view: SAP-System-Screenshot ...................... 99
Figure 89: Table Maintenance Generator: SAP-System-Screenshot ..................................... 100
Figure 90: Change table type: SAP-System-Screenshot ........................................................ 102
Figure 91: Structure of a table cluster .................................................................................... 103
Figure 92: Structure of a table pool ........................................................................................ 104
Figure 93: Where-used-list ..................................................................................................... 106
Page 5
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 94: Active and inactive version of a structure ............................................................ 107


Figure 95: Selection window for the where-used list: SAP-System-Screenshot ................... 108
Figure 96: Results of the search: SAP-System-Screenshot .................................................... 109
Figure 97: Determine start date: SAP-System-Screenshot..................................................... 109
Figure 98: A background job has been finished: SAP-System-Screenshot ........................... 110
Figure 99: Necessary changes at different places .................................................................. 111
Figure 100: Table conversion 1/5........................................................................................... 112
Figure 101: Table conversion 2/5........................................................................................... 113
Figure 102: Table conversion 3/5........................................................................................... 114
Figure 103: Table conversion 4/5........................................................................................... 115
Figure 104: Table conversion 5/5........................................................................................... 116
Figure 105: Direct typing: SAP-System-Screenshot .............................................................. 117
Figure 106: Fields of the table ZZ####_CONV: SAP-System-Screenshot ........................... 117
Figure 107: Data of the table: SAP-System-Screenshot ........................................................ 118
Figure 108: Error message: SAP-System-Screenshot ............................................................ 118
Figure 109: Error during activation: SAP-System-Screenshot .............................................. 118
Figure 110: Initial screen of the Database Utility: SAP-System-Screenshot ......................... 119
Figure 111: Success message: SAP-System-Screenshot ........................................................ 119
Figure 112: Changed table: SAP-System-Screenshot ............................................................ 119
Figure 113: Table content after the conversion: SAP-System-Screenshot ............................ 120
Figure 114: Append structures ............................................................................................... 121
Figure 115: Appends and new SAP fields ............................................................................. 122
Figure 116: Creating an append structure: SAP-System-Screenshot ..................................... 123
Figure 117: Maintenance of the append structure: SAP-System-Screenshot......................... 123
Figure 118: Append structure in the field list: SAP-System-Screenshot ............................... 124

Page 6
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Copyright
 All screenshots used within this document, even if displayed in extracts, are subject to
the copyright of SAP AG.
 Theoretical explanations are based on the literature listed in the first script.
 Distribution and reproduction of this document or parts of this document in any form
is prohibited without the written permission of Prof. Dr. Heimo H. Adelsberger, Dipl.-
Wirt.-Inf. Pouyan Khatami and Dipl.-Wirt.-Inf. Taymaz Khatami.

Page 7
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8 ABAP Dictionary and databases


The ABAP Dictionary (formerly R/3 Data Dictionary) is a powerful tool of the SAP system.
Its purpose is the maintenance of data and metadata, which is data about data.

Figure 1: Overview of the Dictionary

The figure above displays the basic functions of the ABAP Dictionary. They comprise:

 Type definitions
o Data types – globally available data types (as opposed to the locally defined
types of the TYPES statement)
o Type groups – Groups of data types
o Domains – Domains describe technical properties like value ranges of data
types.
 Services
o The Dictionary contains search helps for the creation of user interfaces with
convenient input masks.
o Descriptions and help can be stored for data types in different languages and
maintained at a central location.
 Management of database objects
o Database tables (tables of the underlying relational data base system) are
maintained in the Dictionary and created, changed, and deleted on the
database.
o Using the ABAP Dictionary, access to the database can be realized without the
need to know which data base system is used (e.g., MS SQL-Server).
o Data bases can be visualized graphically as an entity relationship model.
o The Dictionary contains views (views on the tables which can connect multiple
tables or show only certain parts of tables). They can be views of the
underlying data base system, but this is not required.
o The dictionary contains lock objects to create locks on data base tables.

Page 8
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

o Settings of buffering to increase performance can be maintained in the


dictionary.
o Foreign key relationships for the assurance of consistent input on screens can
be defined.
o A logging of all changes on the database can be activated.

The ABAP Dictionary interacts with the tools of the ABAP Workbench, with the Screen
Interpreter and with the data base interface.

Examples for these interactions are:

 Using data types of the ABAP Dictionary during the creation of source code in the
ABAP Workbench
 Using search helps in a Screen Interface, which were defined in the ABAP Dictionary
 The definition of a table in the ABAP Dictionary, which is created on the data base
system by the Dictionary

8.1 Excursus: The Data Browser


In the SAP system, a flight data example is available for training purposes. Using this
example, all concepts of the ABAP Dictionary can be tested. It contains data about carriers,
connections, flights, bookings, etc.

Some of the tables of the flight data example will be used in the explanations of the ABAP
Dictionary. You will access the contents of these data base tables using the Data Browser.

8.1.1 Tasks of the Data Browsers

You can access the Data Browser using the menu path

Tools -> ABAP Workbench -> Overview -> Data Browser

or the transaction code SE16.

Using this tool, the content of data base tables can be viewed. If the delivery and maintenance
settings allow the full maintenance, new entries can also be added from here. Of course,
functionality to edit entries is also available. Furthermore, you can see entries of
corresponding check tables.

8.1.2 Exercise: Using the Data Browser

Start the Data Browser using the menu path given above or the transaction code SE16.

Enter the Table Name SPFLI and commit. You will see a screen in which the columns of the
table are displayed. This screen is used to define search criteria to select entries of the table.
The SPFLI table contains data of flight connections.
Page 9
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 2: A selection screen of the Data Browser: SAP-System-Screenshot

As a small exercise, your task is to elect the connections of the carriers Delta Airlines and
Lufthansa, which have durations between one and six hours.

For this purpose, enter the ID of Delta Airlines into the field next to CARRID (ID of the
carrier). Use the value help to find out the ID. As you have to select multiple carriers for your
task, a multiple selection has to be used. Hence, click on the -button (Multiple selection)
in the same line as the CARRID input field is located. In the new window, the ID of Delta
Airlines is already entered in the first line. Use the second line to add the ID of Lufthansa.
Again, use the value help to determine the correct ID. Commit by using the -icon (Copy)
or the F8 key. Now, enter 1:00 in the field FLTIME and 6:00 in the to: field next to it. Using
this input, all flights with durations between one and six hours are filtered. Commit the input
by using the -icon (Execute) or by pressing F8.

You should see three flights now that match the criteria defined before. If you should see a
different result, this may be caused by other course participants who wrote to the database.
Please be careful when you write something into the database!

Page 10
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 3: Result list of the Data Browser: SAP-System-Screenshot

Now, leave the Data Browser.

Page 11
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.2 Types of the ABAP Dictionary


The ABAP Dictionary contains some built-in elementary types. These types are based on the
well-known ABAP data types and are used for the definition of data types in the Dictionary.
The resulting data types can be used in all ABAP programs (as opposed to the built-in types).
They are used to define types of input fields in the Screen Painter or in Open SQL (more
information on this topic will follow later).

Figure 4: The initial screen of the ABAP Dictionary: SAP-System-Screenshot

To see the built-in types, open the ABAP Dictionary (transaction code SE11). Click on the
input field next to Data Type and open the value help of this field. Then, click on Search for
Data Elements. You will see a new window. Select the input field next to Data Type and
open the value help. The following window will appear:

Page 12
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 5: External types of the Dictionary: SAP-System-Screenshot

To receive more detailed information, right-click on one of the entries in the list of external
types and select Help from the context menu. Another Window will appear showing
explanations of the selected type. In this window, you will also find a link to an Overview of
the Data Classes. There, you find all external data types with a short explanation.

Have a look at these types. Some of them will be used later in the course again. In these
situations, you can reuse the information of the help texts to find out properties of the data
types.

8.2.1 From local to global types

The following figure already appeared in an earlier chapter of the course. It displays the type
hierarchy of ABAP:

Page 13
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 6: Type hierarchy of ABAP

You have already learned how to define local user defined types:

 Elementary types using a simple TYPES definition


 Structure types using a TYPES definition with BEGIN OF / END OF
 Table types using a TYPES-Definition with TABLE OF

The disadvantage of these local defined types is that they are only available in their respective
program: If you define a type in one program (e.g., you type for cars from the exercise) and a
variable using this type in a different program, this will lead to an error. An obvious idea is to
define the type in both programs. However, this would increase the maintenance cost. Instead,
the SAP system offers the ABAP dictionary, in which global types can be defined and,
thereafter, be used in all programs. There are some more advantages of the Dictionary which
were already mentioned at the beginning of this chapter and you can use to your own
advantage.

The following figure displays the most common connections between different types in the
dictionary. The figure is a bit simplified: It is also possible to define table types that are not
based on a structure type.

Page 14
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 6: Basic relationship between types in the Dictionary

8.2.2 Domains

Domains are used to define technical properties of a data type. It is possible to define a data
type without using a domain, but this is not a good style. You should always use domains.

Domains cannot be used to type data objects in ABAP programs. This requires at least a data
type.

Page 15
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 7: Example domain in the Dictionary: SAP-System-Screenshot

The screenshot shows the definition of a domain. Here, setting of the Format and the Output
Characteristics can be maintained.

First, it is required to select the data type. In this case, it is CHAR. You can select all built-in
types of the Dictionary here that you already saw in sub chapter 8.2. For suitable types, the
number of characters or the number of decimal places can be defined. In the example, the
decimal places field is disabled because the CHAR type does not allow this specification.

Note that fields of type CHAR can have a maximum length of only 255 characters in tables.
For longer texts, the use of the LCHR type is required. This limitation is not valid for
structures.

The output characteristics contain a field for the output length, which determines the length
for input and output. The field Convers. Routine is used to select a Conversion Routine. This
is needed if conversions have to be executed between input and internal representation or
internal representation and output. The Sign field indicates whether negative values are
possible. The Lower Case field activates or inactivates the differentiation between lowercase
and uppercase letters. If it is disabled, lower case letters will, after their input, automatically
be transformed into uppercase letters.

Page 16
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 8: Value range information of the domain: SAP-System-Screenshot

In the tab Value Range, certain fixed values or intervals can be specified as the only possible
values of the domain. This is only possible if the domain is based on one of the built-in types
CHAR, NUMC, DEC, INT1, INT2 or INT4.
The specification of a Value Table is only used for documentation. It serves only to generate a
suggestion for the definition of foreign keys in database tables.

8.2.3 Data elements

You already know local types that were defined by the TYPES statement. The globally
defined data types of the ABAP dictionary can be used similarly in ABAP programs. The
advantages of global types are:

 Central maintenance

 Reuse

Page 17
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

 Specification of further characteristics and field labels

Figure 9: Maintenance of a data element: SAP-System-Screenshot

The figure shows how a data element is defined. The technical properties are taken from the
before defined domain. Alternatively, it is also possible to enter these properties directly in
the data type by choosing a built-in type and a length. This would have the disadvantage that
different data elements sharing the same technical properties could not be maintained
centrally anymore.

A special case of a data type is the definition of a reference type. Here, references to other
data elements, but also generic references of the type ANY, OBJECT, or DATA can be
specified. References of the type ANY can reference objects as well as data. Reference types
will be used in the chapter about ABAP Objects.

As opposed to domains, data elements also describe semantic properties of the type, for
example, the field labels, which are maintained in the tab Field Label:

Page 18
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 10: The tab for the maintenance of field labels: SAP-System-Screenshot

The labels defined here can be reused, e.g., for the creation of graphical user interfaces. The
selection texts for an input field can be automatically retrieved from the Dictionary based on
the used data element. This mechanism supports internationalization, so the user will see texts
in his language. The translations can be created in the Dictionary, too, by choosing the menu
path Goto -> Translation. The specified lengths are maximum lengths, which are relevant for
all languages. Therefore, they should be chosen generously.

The tab Further Characteristics maintains some further settings for the data element. You
can specify search helps here, which will be discussed in detail later during this course.
Furthermore, a Parameter ID can be selected. This is used for GET/SET parameters. They are
used to provide default values for fields that would, otherwise, have to be filled out many
times by the user during a session.

Note that data elements have to be activated! This also applies for other types defined in the
Dictionary.

8.2.4 Structures

So far, we defined structure types in the source code. For example, consider the definition of
str_car:
TYPES: BEGIN OF str_car,
manufacturer(20) TYPE c,
model(20) TYPE c,
color(20) TYPE c,
power TYPE i,
END OF str_car.

These lines define a type that describes the structure of all data objects that represent cars.

Figure 11: The structure type str_car

Like in the TYPES statement, you can also define structure types in the Dictionary. The
following figure shows the definition of a structure in the Dictionary that is based on the local
type.

Page 19
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 12: A structure in the ABAP Dictionary: SAP-System-Screenshot

The column Component type contains a data element of the ABAP Dictionary for each field
of the structure. The content of the Short Description column is retrieved from these data
elements. Furthermore, the technical properties of the data element are used. They can either
be defined in a domain used by the data element or (less elegantly) be defined directly within
the data element.
By clicking on , it is possible to add compontents that do not have a data
element to the structure:

Figure 13: Direct typing of a structure: SAP-System-Screenshot

This makes the columns starting from the Data Type column editable, while the column
Component type is disabled. Now, direct settings of the type based on the built-in types of
the Dictionary are possible. This kind of typing is less elegant, so we recommend not using it.
The globally defined structure can be used in arbitrary ABAP programs to type data objects as
soon as it has been activated. The following line is a simple example:
DATA mycar TYPE zz0000_car.

Page 20
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

A structure is called a deep structure if it contains at least one component that is a table type
(or a reference type or a string). Global table types will be explained in the following section.

8.2.5 Table types

Analogously, it is possible to define global table types in the Dictionary. They can be used in
ABAP programs like local table types for the typing of internal tables.

A table for cars could look like this:

Figure 14: A table type in the ABAP Dictionary: SAP-System-Screenshot

Like in the local definition of a table type, the global table type is also based on a line type.
This is usually a structure, like ZZ####_CAR in this example. You can see that it is a
structure because the -icon is displayed next to the input field for the line type.
If a data element would have been used, the icon would be and each element of the table
would only consist of such a simple element. If another table type would have been used, the
icon would be . In this case, each entry of the table would be a table itself. Similarly to
the local table type definitions, this is a mistake in most cases.
In the tab Initialization and Access, the initial size of the table can be configured (similar to
the INITIAL SIZE for local types), and the type of the table can be chosen.

Page 21
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 15: Initialization and access settings: SAP-System-Screenshot

Here, also the generic options Index Table and Not Specified can be chosen. These options
result in generic types which can be used to type formal parameters of modularization units.

In the Key tab, the key of the table type can be configured:

Figure 16: Key Configuration: SAP-System-Screenshot

The Key category is similar to the UNIQUE / NON UNIQUE definition of local table types.
In the area Key definition, you can choose (eventually using the list below) of which
components the table key should consist. The option Standard key uses the character-typed
components of a structure, and the whole line if the line type is a simple or a reference type.
In case of a table type, the key will be empty. The option Line type uses the line type as the
key; this setting is used for unstructured tables. It is possible to access the key using the
pseudo component TABLE_KEY then.
Note again that data objects that should be typed as internal tables based on a table type may
not be typed using TABLE OF as this would, but instead define a table of tables. Technically
this is possible, but usually it is not intended.
Page 22
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.2.6 Type groups and constants

To define constants in the Dictionary, you first have to create a type group (a type pool).
Names of type groups may contain 5 characters at most. They are a short piece of ABAP
code, which can be used to define constants using the CONSTANTS statement. Types may
also be defined here. Defining types in type groups is a predecessor of today’s global types in
the dictionary1.

Figure 16: Definition of a type group in the ABAP Dictionary: SAP-System-Screenshot

The names of constants and types must start with the name of the type group, followed by an
underscore character.

To use the type group in an ABAP program, it has to be included using the TYPE-POOLS
statement:

TYPE-POOLS ZZ000.

Afterwards, the constants and types defined in the type group can be used in the ABAP
program.

8.2.7 Exercise on global types

In this exercise, another program will be created, which offers functionality to work with the
data of students. As opposed to the cars program from the last course part, it will be based on
global types of the ABAP Dictionary.

1
Keller (2012, p. 87)
Page 23
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

A student shall be described in a structure based on his matriculation number, his first name,
his last name and three other fields of your choice.

As it is recommended for good style, you will create domains first, and then you will use them
to define data types, build a structure type from the data types and define a table type based on
the structure type.

8.2.7.1 Create domains

Open the ABAP Dictionary using the path Tools -> ABAP Workbench -> Development ->
Dictionary from the Easy Access Menu or using the transaction code SE11. We recommend
adding this transaction to your favorites menu.

To create a domain, select the radio button Domain and enter ZZ_####_CHAR20 into the
input field next to it. Then, click on the button Create (see the following figure).

Figure 17: Creating a domain in the ABAP Dictionary: SAP-System-Screenshot

Add a suitable short description. The domain will be used to define data elements for the
name, last name, and field of study later. This requires defining a char domain with 20
characters. Hence, choose the Data Type CHAR and 20 Characters for the No. Characters
and the Output Length as well. Also make sure that lower case letters are available.

Page 24
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 18: Definition of the domain in the ABAP Dictionary: SAP-System-Screenshot

Save, check, and activate the domain.

Now, create a domain called ZZ_####_N10. This domain shall be used for the matriculation
number later. Choose NUMC as the Data Type and 10 for the No. Characters and Output
Length. Save, check, and activate this domain, too.

Now, create further domains for the additional components of a student that you chose to
represent. You need a domain for each of the components if the technical properties differ
from the domains you have already defined. Make sure that the names of your additional
domains start with ZZ_####_.

8.2.7.2 Creating data elements

After the technical properties have been specified using domains, the semantic properties will
be defined by creating suitable data elements.

Choose the entry Data Type from the initial screen of the ABAP Dictionary and enter the
name ZZ_####_ST_NAME. Then, click on Create.

Page 25
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 19: First step to create a data element: SAP-System-Screenshot

After the click on Create, the SAP system needs to know which kind of data type you want to
create. You can choose between Data element, Structure, and Table type. Choose Data
element and commit.

Figure 20: Second step to create a data element: SAP-System-Screenshot

Enter a suitable short description and Choose ZZ_####_CHAR20 for the Domain. If you
commit the domain name using the Enter key, you will see the properties of the domain.

Page 26
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 21: Selecting the technical type for a data element: SAP-System-Screenshot

Now, switch to the tab Field Label and add the corresponding labels.

Figure 22: Maintaining field labels: SAP-System-Screenshot

Save, check, and activate the data element.

Repeat those steps to create a data element ZZ_####_ST_FIRSTNAME and a data element
ZZ_####_ST_MATR for first name and matriculation number. The matriculation number
shall be based on the ZZ_####_N10 domain.

Also create further data elements for the other components of your structure. Make sure the
names of these data elements also start with ZZ_####_ST_.

Page 27
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.2.7.3 Creating a structure

Now, you will create the structure type for a student. As before, use the entry Data type from
the initial screen of the Dictionary and enter the name ZZ####_STUD (Be careful: there is no
underscore between ZZ and ####, because this is technically forbidden here). In the next
window, you select Structure instead of Data element.

Figure 23: First step to create a structure in the ABAP Dictionary: SAP-System-Screenshot

Figure 24: Second step to create a structure in the ABAP Dictionary: SAP-System-Screenshot

Enter a suitable short description and add the components of the structure. For this purpose,
enter the name of the components (NAME, FIRSTNAME, etc.) in the Component column of
the table below and enter the corresponding data element in the Component type column.
The result should be similar to the following figure, but of course you will see the individual
fields you chose for your student structure:

Figure 25: Example of a structure for students: SAP-System-Screenshot

Save, check, and activate your structure. You can ignore the warning about enhancement
categories.

Page 28
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.2.7.4 Creating a table type

In the next step, the table type will be created, which will be used to type an internal table of
students later. Enter the name of the table type in the Data type field of the initial screen of
the ABAP Dictionary, as you did it with the structure type and the data type before. The name
shall be ZZ_####_STUD_TAB. Create the table type by clicking on Create and choosing
Table type in the next window:

Figure 26: First step to create a table type in the ABAP Dictionary: SAP-System-Screenshot

Figure 27: Second step to create a table type in the ABAP Dictionary: SAP-System-Screenshot

Add a suitable short description for the table type and choose your structure ZZ####_STUD
as the Line Type:

Figure 28: Line type selection for the table type: SAP-System-Screenshot

Page 29
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Open the tab Initialization and Access and make sure that the table is a Sorted Table by
choosing the appropriate radio button there. Then, open the tab Key and make sure that the
component for the matriculation number is used as a key (note: the name of the component
may be different in your table). Also make sure that this key is unique:

Figure 29: Configuration of the key of a table type: SAP-System-Screenshot

Save, check, and activate the table type. Then, leave the ABAP Dictionary.

8.2.7.5 Using global types

Now the globally defined types shall be used for the implementation of a simple student
maintenance program. Hence, create a new program named
ZZ_####_STUDENTS_GLOBAL.

Similar to your CARS program from the last course part, data will also be created in this
program using a structure and inserted into an internal table. As opposed to that program, you
do not need any TYPES statements here. Instead, you will use the global types you defined
before.

After that, replace the local types str_student and tab_studentes by their global
equivalents ZZ####_STUD and ZZ_####_STUD_TAB. If the component names of the
local types and the global types differ, you have to change them, too.

Attention: For the typing, you do not need a TABLE OF. The type ZZ_####_STUD_TAB
is itself already a table type. Theoretically, it would be possible to ignore the table type and
use TABLE OF ZZ####_STUD for the typing instead. However, this way the global table
type would not be used. This would mean that additional settings, like the type of table, could
not be maintained centrally in the Dictionary anymore. The other case would also be possible,
theoretically: The work area could be typed with LINE OF ZZ_####_STUD_TAB instead
of the structure type. This would be more difficult to read though.

Now use the work area to create five students and put them into the internal table. Be careful
to remember the difference between INSERT and APPEND, because the table is a sorted table
(the sort order may not be violated). After that, use a loop to print the contents of the internal
table. Again, the output should be formatted in a readable way.

Page 30
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Hint: If there is an error message about a missing cursor for a table, you probably used the
INSERT statement with INTO instead of INTO TABLE.

Save, check, and activate your program. If you test it, the output should be similar to the
following figure:

Figure 30: Corrected title: SAP-System-Screenshot

To demonstrate the usability of semantic properties of a data type from the Dictionary, one of
the components of the student structure shall now be set using a parameter whose selection
text will be retrieved from the ABAP Dictionary.

For this exercise, choose an arbitrary component of the student structure. In our example, we
will choose the degree program; you can use the component of your choice instead.

Insert a parameter at the beginning of the program (i.e., after the initial REPORT statement).
This parameter shall be typed using the data element that was used to type the component of
your choice. If you followed the instructions in this document carefully, this name should
begin with ZZ_####_ST_. You can choose an arbitrary name for the parameter, provided it is
not too long. In our example, the parameter definition could look as follows, assuming there is
a data element ZZ_####_ST_DEGR:

PARAMETERS pa_degr TYPE ZZ_####_ST_DEGR.

Now, change the program in a way that makes sure that all students that are inserted into the
internal table have the value entered into the parameter field by the user for the selected
component. In our example, this means all students shall have the same degree program,
which is entered by the user. Save, check, activate, and test your program. So far, it does not
have a selection text, so the parameter name will be displayed:

Page 31
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 31: Parameter without selection text: SAP-System-Screenshot

To change this, leave the program and choose the menu path Goto -> Text Elements ->
Selection Texts. However, do not enter a selection text here. Instead, the selection text shall
be retrieved from the dictionary. Activate the checkbox in the column Dictionary ref.. If you
now save and activate the selection texts, you will see the text retrieved from the ABAP
Dictionary:

Figure 32: Example for a selection text retrieved from the Dictionary: SAP-System-Screenshot

Now, get back to the source code of your program and test it again. Now, the selection text
from the Dictionary is visible:

Figure 33: User interface with a selection text from the ABAP Dictionary: SAP-System-Screenshot

Page 32
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.3 Tables
In a database-oriented application, tables have a very important role. All data of the system is
stored in tables, which are part of a relational database system. These tables may not be
confused with internal tables (which are just local data structures on the application level).
They are called database tables instead. The platform-independent description of the
database table in the dictionary is also called transparent table2.

Tables consist of data records (lines), which themselves consist of single fields. Tables are
structured by columns, which all have a unique name within the table. One or more fields of a
table uniquely identify the records of a table and are called key fields (primary key). Non-key
fields are also called function fields:

Figure 39: Key fields of a table

Currency fields and other fields with measurements require the specification of a unit. This
unit is defined in a reference field. The assignment is done at runtime.
The typing of table fields can be done using data elements just as the typing of global
structure types. The data elements themselves may rely on domains for their technical
properties. Alternatively, a direct typing based on the built-in types of the Dictionary is
possible as well. Different fields that use different data elements can be based on the same
domain, as it was the case for structure types:

2
Gupta (2011, p. 77)
Page 33
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 34: Different fields, different data elements, same domain

An example for this case is the table SPFLI. This table is part of a flight data example
provided by SAP, which contains flight connections. For each flight connection, the departure
airport and the destination airport are stored. Technically, these fields are equal, so they use
the same domain. Semantically, there is a difference, however, for example, different
selection texts are required. Hence, both fields use different data elements.

Note: The order of the fields in the ABAP Dictionary does not necessarily have to
corresponding to the order in the database system. This saves the effort of a table conversion.

8.3.1 Tables as types

Tables of the ABAP Dictionary can also be used as types, e.g., in an ABAP program. There
they can be used as a structure. This means, the declaration

DATA myvar TYPE SPFLI.

does not, as you might expect, define an internal table. Instead, a work area is defined. A
work area is a structured data object, which represents one line of the database table SPFLI.

If, however, an internal table with the same structure as the database table SPFLI shall be
defined, the addition TABLE OF needs to be used:

DATA myItab TYPE TABLE OF SPFLI.

8.3.2 Include structures

In some cases, the format of a structure appears in multiple tables or other structures. To make
it possible to maintain these elements centrally, the SAP system offers the concept to include
structures. Here, the components of one structure are included in another structure or table.

Page 34
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 35: A structure used as an inclusion in different tables

In an include chain, only one database table may appear. This means, a table cannot include
another table. This limitation does not apply for structures, but a chain of nested includes
structures may at most contain 9 levels3.

It is possible to assign group names and suffixes to includes. Using a group name, the group
can be accessed as a whole. If, for example, a student contains an address structure in the
group ADR, an ABAP program, which uses a student called STUD, could access his address
using STUD-ADR or his street using STUD-ADR-STREET. Suffixes help to ensure the
uniqueness of component names if a structure is included multiple times by adding a suffix to
the names.

8.3.3 Exercise: Table structure

As an example for a table, a table for students shall be defined. For this purpose, open the
initial screen of the ABAP Dictionary and choose the entry Database table. Create the table
similar to the creation of the other Dictionary elements, giving it the name ZZ####_STUDS.

Figure 36: Creating a database table: SAP-System-Screenshot

Add a suitable short description and choose Delivery Class A (Application table, master
and transaction data) and for the field Data Browser/Table View Maint. Choose the value
Display/Maintenance Allowed. This exact setting is important; as it makes sure you can
enter data using the tools of the ABAP Workbench. If these tools should be greyed out for a
table during the course, you should check this setting.
Now, open the tab Field. First, add a field MANDT based on the data element MANDT. This
field represents the client number and is automatically handled by the system. Then, choose

3
Gupta (2011, p. 89)
Page 35
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

the menu path Edit -> Include -> Insert. Choose your structure ZZ####_STUD and let the
other two fields empty. The field list should now look like this:

Figure 37: Fields of the table: SAP-System-Screenshot

To see the content of the include, click on (Expand Include). Now, you can see the
components of the include:

Figure 38: Expanded include: SAP-System-Screenshot

In our example, however, the table should not contain an include. Instead, it should have
regular fields. The include was just a convenient way to copy them from the structure. To get
rid of the include itself, choose the menu path Edit -> Include -> Copy components. Now,
the include components are direct parts of the table.

The matriculation number is required for the key, because the client number is not sufficient
to identify a student uniquely. Mark the line containing the matriculation number by clicking
on the empty button on the left side of the field name of the matriculation number. Cut
this line by clicking on (Cut). Now, mark the line Name and click on (Insert). After
that, the line containing the matriculation number should be located between the client
number line and the name line. If you were not successful, repeat these steps or even delete
the lines using and insert the include again.

Check the checkbox in the Key column for the client and matriculation number to make these
fields key fields. The list should now look approximately as follows:

Page 36
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 39: Field list with completed key

Save and check the table (ignore messages about the enhancement category). You cannot yet
activate the table, because technical settings are missing.

8.3.4 Technical settings

During the definition of a table, some technical settings have to be made that are used for
optimization purposes. They can be found under the menu path Goto->Technical Settings.

Figure 40: Technical settings for a table: SAP-System-Screenshot

Page 37
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.3.4.1 Logical Storage parameters


8.3.4.1.1 Data class

The setting of the data class is only effective for Oracle- and Informix-databases. Here, it
determines the physical area of the database where the table should be stored. There is a
differentiation between various data classes, which you can see in the F4 help of the field. The
most important ones are4:

 Master data is data that is not changed very often, e.g., the address of a customer.
 Transaction data is data that is changed often, e.g., inventory.
 Organization data is data that is entered as a part of the customizing during system
setup. This data is not changed very often, e.g., Country keys.
 System data is data that is used by the SAP system itself. This could be, e.g., the
source code of one of your programs.

8.3.4.1.2 Size category

The size category defines how many data records are expected for the table. This information
is important, because it helps to avoid fragmentation. Fragmentation occurs if the memory
area, which has been reserved for the table when it was created, is not sufficient, and
additional memory areas have to be assigned, which results in different data fragments
distributed in the memory:

Figure 41: Fragmentation example

Fragmentation occurs very often for transaction data and for tables that grow quickly or are
changed very often. This results in performance issues.

The memory area assigned when the table is created is called Initial Extent, while the
following areas are called First Extent, Second Extent, etc.

4
Gupta (2011, p. 114)
Page 38
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The size of the initial extent is the same for all size categories. The size of the other extents is
different for all size categories and also dependent on the used database system.

Fragmented indices can be defragmented by deletion and re-creation. Fragmented tables have
to be converted. Table conversion means that the table is deleted and recreated (the deletion
happens after the recreation of course). The conversion and the recreation of deleted indices
both require lots of calculation, so these operations should not be carried out during times
where there are lots of users accessing the system. During the process of conversion, a table
cannot be accessed at all.

Choosing too large extents leads to a waste of memory; hence, the size category should be
chosen carefully. There are nine different size categories, which are described in the value
help:

Figure 42: Size categories: SAP-System-Screenshot

8.3.4.2 Table buffering

The Table buffering is an intermediate storage in the application server, which shall reduce
the load on the database. The buffer cannot be used for arbitrary database request; for
example, queries using aggregate functions (cf. section 8.4.6.1) are not supported here. The
access of the buffer happens invisibly to the user based on the database interface. This buffer
of the application server is independent of possible buffers of the specific database system on
the database level. Administrators can reset the buffers using the /$TAB command if
inconsistencies occur. Such a reset can take multiple hours and has a high negative impact on
the systems performance.

Page 39
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 43: Buffer

There are three types of buffering. They will be explained in section 8.9, because you need
some understanding of the general access to data first.

8.3.4.3 Logging

Logging is used to record changes on the database. This requires setting the corresponding
property in the technical settings of the database and setting profile parameter “rec/client.”

Possible settings are5:

 rec/client = ALL, to log all clients


 rec/client = 000, [], [] to log selected clients only
 rec/client = OFF, to stop logging system wide

Logging should only be activated if it is absolutely required, because it causes a lot of load on
the database. Firstly, for each write access, an entry in the logging table has to be added.
Secondly, many users access the logging table, so there may be huge waiting times because of
the locks of that table, no matter which tables the users actually access.

Note: The topic of locks will be covered in detail in a later course part.

8.3.5 Exercise: Technical settings

In this exercise, you will edit the technical settings of your table ZZ####_STUDS. Use the
menu path Goto -> Technical settings. Choose the Data Class APPL0 (Master data) and
Size category 0. There should be no buffering and no logging of changes.

5
Gupta (2011, p. 120)
Page 40
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 44: Technical settings of the students table: SAP-System-Screenshot

Save the technical settings and go back to the table. Activate the table now. As usual, ignore
the warning about the missing enhancement category (this topic will be covered later during
this course).

Page 41
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4 Accessing tables from ABAP programs


Access to database tables is usually not performed directly from an ABAP program. Instead,
the Dictionary is used as a convenient interface. However, direct access is possible in general
and, therefore, there is a differentiation between Open SQL and Native SQL.

Native SQL allows using specific commands of the underlying database system. The language
for queries is dependent on the database system that is used. Changing the database system
may require changes in the code. The advantage of native SQL is that database specific
features can be used.

In contrast, Open SQL is a standard that is independent of the actual installed database
system. It does not support all specific features of the different database system, hence you
might miss some features you know from a specific database system. The database interface
translates Open SQL queries into the native SQL of the database system that is used.

In the following section, Native SQL is presented briefly, but the focus is on Open SQL,
because this access method is used for the rest of the course and is much more relevant in
practice. The Native SQL explanations are, hence, only added for completeness. Please use
Open SQL for all your programs in this course.

8.4.1 Native SQL

To be able to use specific functionality of the underlying database system, the Native SQL
interface of the ABAP system can be used. This provides a frame in which specific
commands of the database management system can be used. These commands are not part of
the ABAP language. Nevertheless, ABAP provides some language elements in Native SQL to
enable the connection between SQL and the surrounding code. The tables used in Native SQL
do not have to be defined in the ABAP Dictionary. It is sufficient if they exist in the database
system.

The syntax for embedding Native SQL is:


EXEC SQL.
...
ENDEXEC.

In the area indicated by the tree dots, Native SQL statements can be used. This area is not
inspected completely by the syntax checker, as it is dependent on the syntax of the
corresponding database system.

The SQL statements are transported to the database system without changes in most cases. An
exception are host variables, which are variables of the surrounding ABAP code used within
the SQL statements, e.g., to transport data to the database or to receive results of a query.
These variables are indicated in Native SQL by adding a colon in front of their names.

Page 42
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

This code displays an example:


PARAMETERS p_carrid TYPE s_carr_id.
DATA carrname TYPE s_carrname.

EXEC SQL.
SELECT carrname FROM scarr INTO :carrname WHERE carrid = :p_carrid
ENDEXEC.

WRITE carrname.

Here, a variable (carrname) and a parameter (p_carrid) of the surrounding ABAP program are
used within Native SQL. The program outputs the full name of an airline if the corresponding
acronym is entered by the user.

8.4.2 Open SQL

Open SQL is the subset of the ABAP statement, which allows accessing the central database
of the ABAP system. The ABAP system translates the statements into the database specific
commands. This has the advantage that applications accessing the database do not have to be
changed if the database system is replaced by a different one. The disadvantage is that
database system specific extensions cannot be used, so you cannot use all kinds of queries that
you might be used to from other systems. Nevertheless, it is possible to use views that have
been defined in the ABAP Dictionary.

The following statements belong to Open SQL:

 SELECT
 OPEN CURSOR, FETCH, CLOSE CURSOR
 INSERT
 UPDATE
 MODIFY
 DELETE

This list is not complete. There are further statements to ensure consistency, which will be
discussed separately later.

The operations will be presented in the following sections. Participants who are experienced
with SQL will recognize many concepts from regular SQL. Nevertheless, this knowledge is
not required for this course, and there are several differences between usual SQL and Open
SQL.

8.4.3 Reading data

The SELECT statement is used to read data from a table or from multiple tables and / or
views.

The following figure displays the general structure of a reading access to the database:

Page 43
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 45: Structure of a reading database access (overview)

 In the SELECT part, those columns are defined that shall be part of the result.
Furthermore, it is possible to specify aggregate functions here.

 In the FROM part, the source of the data is defined. Here, one or multiple tables or
views can be specified.

 In the INTO part, it is specified to where the data shall be transported. Hence, the
corresponding data objects of the ABAP program are given here.

 In the WHERE part, the number of selected lines is restricted by logical conditions to
reduce the solution set to the lines of interest.

 There are further possible parts (clauses) of a SELECT statement, which will be
presented later. This description shall simply serve as an overview, made especially
for those of you who do not have any SQL experience yet.

The syntactical variations of the SELECT statements are diverse. Therefore, the use of the
statement is explained by examples for illustration.

8.4.3.1 The work area for database tables

In section 8.3.1, we already explained that tables could be used to type data objects. This
property is very useful when working with Open SQL, because a suitable work area can be
defined straightforward. This work area can then be used to represent a single entry of the
database table, similar to the work areas you already know from the exercises on internal
tables. In the database context, there are some limitations on the type. The data type may not
be a deep structure (but strings are allowed) and has to be at least as long as the structure of
the database table. Remember, a type is called deep if the contents of its data objects are
references that refer to the actual content. This comprises strings, reference variables, and
internal tables as well as structures that contain at least one deep component.

In the simplest case, the work area has the same structure as the database table. By using the
database table to type the work area, not all fields have to be written down explicitly, and the
work area is robust for changes of the database structure (again, this shows the advantages of
the centralized type maintenance in the Dictionary).

An example is the following definition:


DATA wa TYPE spfli.

Here, spfli is the name of a database table. wa does not become an internal table. Instead, a
structured date object is defined. Hence, each database table provides a line type by its
column definitions, which can be used to define a suitable work area into which records of the
database table, spfli in this case, can be read afterwards.

Page 44
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

If spfli would have been a table type, defined locally by TYPES … TYPE TABLE OF …
or by a definition of a global type in the Dictionary, wa would be an internal table. In this
case, wa would not be a good choice of a name. However, it would be possible to type a work
area using the syntax LINE OF tabletype.

In the following examples, we assume that there is a work area wa defined which matches the
table(s) given in the FROM part.

8.4.3.2 Reading a single record

The following code reads a single record from the database:

SELECT SINGLE *

FROM spfli

INTO wa

WHERE carrid = 'LH' AND connid = '0400'.

The keyword combination SELECT SINGLE serves to indicate that only one single record
should be read. To identify the correct record, the whole key has to be given in the WHERE
part. However, this is not syntactically enforced – if the key is incomplete, just any record is
retrieved, which matches the logical condition in the WHERE part. An exception is the client
field: Because of the large number of client-dependent tables, this field is automatically filled
with the current client if it exists. If you want to specify a client explicitly, you have to add
CLIENT SPECIFIED to the statement.

The INTO part serves to specify the data objects into which the result shall be written. This
data object has to have a type structure similar to the table or the field selection of the
SELECT part in its leftmost fields.

You can check the value of sy-subrc to determine whether the statement was successful or
not. If it was successful, the value is 0.

The columns in the SELECT part as well as the fields in the INTO part can be given
explicitly, as it is shown in the following example. In the current example, a star is used. This
indicates that all columns of the result set shall be taken over. In this case, the result is based
on just one table, so it contains exactly the columns of that table. As the work area is typed
with the same table, the condition to have a similar field structure in the leftmost fields is
matched trivially.

Page 45
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.3.2.1 Explicit specification of columns

DATA: BEGIN OF wa,

carrier TYPE spfli-carrid,

connection TYPE spfli-connid,

from TYPE spfli-cityfrom,

to TYPE spfli-cityto,

END OF wa.

SELECT SINGLE carrid connid cityfrom cityto

FROM spfli

INTO wa

WHERE carrid = 'LH' AND connid = '0400'.

In this example, a work area is built that does not have exactly the same structure as the
database table. The individual fields do not even have the same names as the fields in the
database. However, they are suitably typed. In the OpenSQL statement, only four columns of
the database table are selected and transported to the fields of the work area. Please note that
the order of fields must be correct here.

The following figure displays the query from above:

Figure 46: Query with given set of fields

Page 46
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.3.2.2 Explicit specification of target fields

In the previous example, the order of the target fields and the order of the fields of the result
set were identical. However, it is also possible to assign the fields manually to have a different
order. The following code contains an example:

DATA: BEGIN OF wa,

connection TYPE spfli-connid,

carrier TYPE spfli-carrid,

from TYPE spfli-cityfrom,

to TYPE spfli-cityto,

END OF wa.

SELECT SINGLE carrid connid cityfrom cityto

FROM spfli

INTO (wa-carrier, wa-connection, wa-from, wa-to)

WHERE carrid = 'LH' AND connid = '0400'.

As opposed to the previous code, the first two fields are in opposite order. The individual
columns are assigned explicitly to the specified variables. In this case, all target variables are
fields of the same work area, but this is not necessarily the case. You could also specify other
variables. The following figure displays the query graphically.

Page 47
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 47: Explicit specification of target fields

8.4.3.2.3 Automatic assignment of fields

In many situations you will have a work area, in which the fields do not have different names
than those of the database table as in the previous example. In this case, you do not need to do
an explicit assignment of field names. Instead, you can let the system assign the fields of the
database to the fields of your work area automatically based on the identity of the field names.
In this case, the addition INTO CORRESPONDING FIELDS OF has to be used. The
following code displays an example:

DATA wa TYPE spfli.

SELECT SINGLE cityfrom cityto

FROM spfli

INTO CORRESPONDING FIELDS OF wa

WHERE carrid = 'LH' AND connid = '0400'.

Here, the columns read from the database are assigned to the fields of the work area which
have the same name. The order is not important in this case, but the types should match. The
advantage of this syntax is its robustness to changes: If the order of fields in the target
structure is changed or fields are added, the Open SQL code does not have to be changed. The
figure displays the query:

Page 48
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 48: Example for name-based field assignment

8.4.4 Reading multiple records

In many cases, as opposed to the previous examples, multiple records are required instead of
just a single one. To achieve this, there are two general possibilities. The records can be
loaded into an internal table, or they can be read into the work area and be processed one after
another. These two options differ a lot: In the latter case, SELECT becomes a loop construct.
Both possibilities are described in the following two sections:

8.4.4.1 Reading records into an internal table

The possibility to read multiple records into an internal table at once using a single SELECT
statement is also called array fetch.

Page 49
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 49: The array fetch

For the array fetch, the target has to be prefixed by INTO TABLE, as it is the case in the
following example:

DATA itab TYPE TABLE OF spfli.

SELECT *

FROM spfli

INTO TABLE itab

WHERE carrid = 'LH'.

In this example, all flight connections of Lufthansa are transported into the internal table.
Note that the table key is incomplete here.

The array fetch is a recommended access technique because it is very efficient. Data records
can be read block wise from the database. The structure of the internal table has to match the
database table similar to the work area during single record requests, so the columns starting
from the left have to be similar. Otherwise, the construct INTO CORRESPONDING
FIELDS OF TABLE can be used, which acts analogously to INTO CORRESPONDING
FIELDS. Columns with the same name should have the same type, too, because, otherwise,
conversions are required that require calculation effort.

Page 50
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

If APPENDING is used instead of INTO, existing data from the internal table will not be
deleted by the statement.

8.4.4.2 Reading into a work area – SELECT as a loop

If no array fetch is used, SELECT acts like a loop, which successively reads the data records
from the database table into the work area (or its explicitly specified fields).

Figure 50: SELECT as a loop

The head of the loop is represented by the SELECT statement itself. The end of the loop is
marked by the statement ENDSELECT. The following code shows an example:

DATA wa TYPE spfli.

SELECT *

FROM spfli

INTO wa

WHERE carrid = 'LH'.

" Here you would place statements

" which process the individual result in wa

ENDSELECT.

Page 51
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Attention: Note that the ENDSELECT statement is only required (and allowed) for this
specific case of a loop-like fetching of data. Especially the array fetch does not contain an
ENDSELECT. If you want to read entries into an internal table, but get a syntax error about a
missing ENDSELECT, you most probably forgot the INTO TABLE part.

The data records are read by the database interface in packages, but assigned individually to
the work area. After the last data record, the loop is left and the number of read data records
can be retrieved from the system field sy-dbcnt. The field sy-subrc contains the value 0
if at least one record could be retrieved. These system fields are also available for the array
fetch.

8.4.5 Exercise: Displaying contents of a table

You already know the SPFLI table from the exercise about the Data Browser and the View
exercise. If you are not yet familiar with its columns, have a look at the table structure in the
ABAP Dictionary.

In this exercise, a program will be created which prints data from this database table.

Open the Object Navigator and open your package ZZ_####. Create a new program
ZZ_####_FLIGHTS. The status shall be as usual. Use your package and your request as
before.

Create a suitable work area wa. For the typing, you can spfli here. You see how useful the
ABAP Dictionary is, because you can simply reuse the structure of the database table. Note
that the work area is not an internal table but a structure.

Now, you have to read the records from the database table SPFLI. Use the SELECT statement
to do this. As you are working with a work area and there are multiple entries in the database
table, you need a select-loop with ENDSELECT. In the body of the loop, print the id of the
airline, the flight number, and both cities and countries.

Your code in this section could look like this. Note the “/” that creates a new line:

Figure 51: SELECT loop: SAP-System-Screenshot

Save, check, and activate your program. The output should look like this:

Page 52
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 52: Program output: SAP-System-Screenshot

You can see another helpful feature: The lengths of the fields are not only used as a limitation
for the stored values, they are also respected during output. Hence, you see the output in a
well-aligned way.

As you have learned during the last sections on Open SQL, it is possible to read records as
blocks or completely into internal tables (array fetch). One of the reasons for this syntax is the
different speed of access. Reading the entries of an internal table is a lot faster than accessing
the database table. Therefore, you will change your program now to read the records into an
internal table before you output them using a LOOP loop.

Create an internal table itab typed with TABLE OF spfli, which shall receive the flight
data.

Comment the existing SELECT loop by inserting double quotes ( " ) at the beginning of each
of its lines.

Instead, add a SELECT statement for an array fetch, which reads all entries at once. This
SELECT statement does not contain an ENDSELECT, because no processing of individual
records is performed here. If you do not remember the correct syntax, please look back at the
theory parts.

As the output is not done in a select loop anymore, you must create an additional loop
construct for the output. Hence, create a LOOP that stores a line of the internal table into the
work area wa in each iteration. Print this work area using WRITE statements, which you
previously used in the select loop.

Save, check, and activate your program. Then test it. The output should be similar to the
previous version of the program.

In the next step, your program shall be changed in a way that it does not display all flights, but
only those of a specific airline. The ID of the Carrier shall become selectable on a selection
screen by the user.

Add a parameter pa_carr to your program. Use spfli-carrid to type it.


Then, use the parameter in the WHERE part of your SELECT statement.
Save, check, and activate your program. It has a selection screen now:

Page 53
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 53: Selection screen of the flights program: SAP-System-Screenshot

For the selection screen, the selection text of the parameter should be changed. Choose the
menu path Goto -> Text Elements -> Selection texts. Again, you have the advantage that the
parameter has been typed by a global type from the ABAP Dictionary. Hence, you can use the
selection text defined there by activating the checkbox in the Dictionary ref. column and
committing with the Enter key.
Save, check, and activate your program. During activation, make sure also the selection texts
are activated.

Figure 54: Selection screen including selection text: SAP-System-Screenshot

SAP recommends encapsulating database accesses in reuse components (modularization units


that can be reused). This will be done now using a function module.

Open your function group ZZ_####_FGR and add another function module called
Z_####_GET_FLIGHTS.

Figure 55: Creating a function module for reading flights: SAP-System-Screenshot

Add an import parameter that receives the ID of the carrier:

Page 54
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 56: Import parameter of the function module: SAP-System-Screenshot

For returning the flights, you need a suitable table type. Open a new session for the ABAP
Dictionary (using or the prefix “/o“ in the command field). Note: By pressing F1 in the
command field, you can see more possible inputs, e.g., for closing sessions). In the
dictionary, create a new table type called ZZ_####_FLIST. Enter a suitable short description,
choose SPFLI for the line type and save.

Figure 57: The table type based on SPFLI: SAP-System-Screenshot

Check and activate the table type and go back to the session containing your function module.
Add an export parameter called EX_LIST and use your new table type to type it:

Figure 58: Using the table type: SAP-System-Screenshot

Save and go to the Source code tab. Add the SELECT statement from your program here.
Adapt the names in the INTO and WHERE part to the names of the parameters of the function
module. Save, check, and activate the function module afterwards.

Now, open your program ZZ_####_FLIGHTS again. Remove the SELECT statement and
replace it by a call of your function module. The simplest way to add the function module call
is using the drag-and-drop function from the navigation tree or the pattern button you already
know from previous exercises.

Page 55
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Add the name of the selection screen parameter and the internal table on the right side of the
parameter assignment. Do not forget to uncomment the lines for the export parameter by
removing the star symbols. Also make sure not to delete the trailing dot of the function
module call.

Figure 59: Calling the function module: SAP-System-Screenshot

Save, check, activate, and test your program. The output should still be the same as before.

In the current state, the program has some drawback: If an invalid airline ID is entered or if
the id of an airline without any offered flights is entered, there is no output. Hence, you
should implement an appropriate error handling now. As you know, the SELECT statement
sets the system variable sy-subrc to a value other than 0 in case of an error. This can be
checked to make sure if an error a message is displayed instead of an empty result.

Open your function module and go to the Exceptions tab. Define a new exception named
SQL_ERROR.

Figure 60: New exception: SAP-System-Screenshot

Then open the source code of the function module. After the select statement, add an IF-
construct (confer the section about control structures). If sy-subrc has a value other than 0,
the exception shall be raised. You know how to raise exceptions from the first course part.

Save, check, and activate your function module. Then open your main program again. You
must implement the exception handling there. Add the EXCEPTIONS part of the function
module call and assign a value, e.g., 5, to the exception you defined in the function module.

After that, add an IF-ELSE-construct around the output: If sy-subrc has the value 0, the LOOP
shall be executed. Otherwise (if it has the value you defined for the exception), using a
WRITE statement, a suitable error message of your choice shall be displayed.

Page 56
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Save, check, and activate your program. If you want to test the part of your code that displays
the error message, choose a carrier ID, which does not exist. In this case, your error message
should appear. In later sections, you will learn how to define “real” error messages of the
system. The textual output is only used for simplification here.

Figure 61: Output of a simple error message: SAP-System-Screenshot

You have now written a program that is able to read records from a database table using a
function module and to print the results on the screen. You have used predefined data
elements to automatically receive a selection text, and you have used the predefined search
help. You have used the system field sy-subrc to determine the success of a database
query.

8.4.6 The SELECT statement in detail

The syntax of the SELECT statement is quite complex and can be described as follows and
explained in more detail in the following sections6. However, some parts of the syntax require
further explanation.
SELECT result
FROM source
INTO|APPENDING target
[[FOR ALL ENTRIES IN itab] WHERE cond]
[GROUP BY cols] [HAVING group_cond]
[ORDER BY sort_args].
...
[ENDSELECT.]

The result set is read from the tables given in source according to the structure result
and stored into target. GROUP BY cols condenses multiple lines based on equal values
in given columns. HAVING group_cond restricts the selection of condensed lines, while
WHERE cond restricts the result set. ORDER BY sort_args is used to sort the results.

6
Keller (2012, p. 1064)
Page 57
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.6.1 The SELECT part

The syntax of result consists of lines and columns.

The syntax of lines is:

... { SINGLE [FOR UPDATE] }


| [DISTINCT] ...

SINGLE makes sure that the result set contains only one line. If the remainder of the query
produces more than one line, only the first of these lines will be used. In this case, no
ENDSELECT is required, because there is no iteration on multiple result items.

FOR UPDATE is used to set a write lock for the read line in the database system.

When reading multiple lines, the DISTINCT addition can be used to remove duplicate entries
from the result.

The syntax of columns is7:


... *
| { { col1 | agg( [DISTINCT] col1) } [AS a1]
{ col2 | agg( [DISTINCT] col2) } [AS a2] ...
}
| (column_syntax) ...

Static column choice

If the star is used to select the columns, all columns will be taken into the result. If multiple
tables are used in the FROM- part (see below), multiple columns with the same name will
appear in the result set.

Alternatively, single columns (col1, col2, ...) can be given. This can be done
directly or by using an aggregate function, which is represented by agg in the above syntax
diagram. The addition AS can be used during the static specification of columns to give a
column an alternative name. This renaming is also effective for the INTO / APPENDING
CORRESPONDING FIELDS and ORDER BY additions. The new name a1 may have 14
characters at most.

The name of the column has to be unique. If the same column name appears in more than one
of the tables used in the FROM part, the table name has to be given, too. It is separated from
the column name by a tilde symbol (~).

Example: dtab1~col1 names the column col1 from the table dtab1.

If the table appears more than one time in the FROM part, the corresponding alias name of the
table has to be given.

7
Keller (2012, p. 1068)
Page 58
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Aggregate functions

The addition DISTINCT causes duplicates to be ignored by aggregate functions.

The following aggregate functions are available in Open SQL:

 AVG( [DISTINCT] col1 ) calculates the average of the values in the given
column of the result set (or, if HAVING is used, of the current group)
 COUNT( DISTINCT col1 ) calculates the number of different values in the given
column of the result set (or, if HAVING is used, of the current group)
 COUNT(*) counts the number of rows in the result set (or, if HAVING is used, in the
current group)
 MAX( [DISTINCT] col1 ) calculates the maximum of the values in the given
column of the result set (or, if HAVING is used, of the current group)
 MIN( [DISTINCT] col1 ) calculates the minimum of the values in the given
column of the result set (or, if HAVING is used, of the current group)
 SUM( [DISTINCT] col1 ) calculates the sum of the values in the given column
of the result set (or, if HAVING is used, of the current group)

As for usual SQL, if aggregate functions are used, all columns that are not used in aggregate
functions have to be grouped by the GROUP BY part.

If only aggregate functions are used in the SELECT part, the grouping is not required. In this
case, the result does only consist of one line.
NULL-values are not used in the calculations of the aggregate functions (NULL is not the
number zero, it represents an empty field in the table). Only if all values are NULL, the result
of the aggregate function will have the value NULL.

It should be noticed that appropriate types should be selected for the result variables. For the
aggregate function AVG, the result might be rounded if it is assigned to an integral variable,
for the function SUM, there might occur overflows.

Dynamic column choice

Columns can be chosen dynamically by a braced data object (column_syntax).


column_syntax must be a character-like data object or an internal table with a character-
like data type, which contains the syntax of a static column choice at runtime. If an internal
table is used to specify the column choice, the syntax may be split to multiple lines. Casing is
not respected8.

8
Keller (2012, pp. 1073 f.)
Page 59
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.6.2 The FROM part

The FROM part of a query defines the underlying data (which database tables to be used) and
has the following syntax9:
... FROM {
{dbtab [AS tabalias] }
| join
| { (dbtab_syntax) [AS tabalias]}}
[ UP TO n ROWS]
[CLIENT SPECIFIED]
[BYPASSING BUFFER] ...

8.4.6.2.1 Choosing a single table

Using dbtab [AS tabalias], only a single table of the database is chosen. By the
addition of AS tabalias, the table can be assigned an alias name, which then can be used
to access this table in other parts of the query. However, if single tables are used, alias names
are not required at all.

8.4.6.2.2 Joining tables

By using joins, multiple tables can be combined with each other. The join syntax is:
... [(] { dbtab_left [AS tabalias_left]}
| join
{ { [INNER] JOIN } | {LEFT [OUTER] JOIN} }
{dbtab_right [AS tabalias_right]
ON join_cond} [)] ...

As you can see from the element join itself in the syntax diagram, join expressions can be
nested.

A join always consists of two sides. The left side can be a table or another join, while the right
side is always a table. Views can be used instead of tables and are, therefore, not discussed
separately. The next parts are the conditions in the join_cond part. They determine which
entries should be contained in the join.

8.4.6.2.3 Types of joins

In Open SQL, inner joins and left outer joins can be used.

In an inner join, the columns of the left and the right table are connected in a way that the
result set consists of the columns of both tables. For each line of the left table the lines of the
right table for which the condition join_cond is fulfilled are determined. The
correspondingly connected lines are added to the solution set. Hence, in the solution set, lines
of the left or the right table can occur multiple times if multiple connections match the
condition.

If no lines match the condition join_cond, the result set is empty.

9
Keller (2012, p. 1074)
Page 60
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The left outer join is similar to the inner join. The columns of the result set are the same, but
in addition to the previously determined lines, the result set also contains lines for all lines of
the left table that did not find any “partner“ in the right table. The columns of the result set
that belong to the left table are filled accordingly for these entries, while the columns of the
rights table will be filled with NULL values for these lines.

The only logical operator that can be used in the ON condition is AND. Each comparison in
the ON condition has to contain a field of the right table. In the WHERE part, however, no
fields of the right table may be used. More information on this topic can be found in the
ABAP documentation.

If there are equal column names in multiple tables of the join expression, they have to be
addressed by the table name in other parts of the query (using the table~column syntax).
If the same table is used, aliases have to be defined to be able to use them in other parts of the
query (AS tabalias_left or AS tabalias_right).

8.4.6.2.4 Example join

An example for a join of two tables is the selection of flights from the SFLIGHT table; if,
additionally, the time of the flight is required. This information is stored in the PFLI table.
Hence, both tables have to be connected using a join.

Figure 62: Example for a table join

It is easier to define joins using views in the ABAP Dictionary than to define them in ABAP
source code. These views can then be used like a normal table to read data without having to
specify the join condition or the selected columns again each time.

Page 61
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.6.2.5 Exercise: Implementing a join in ABAP

In this exercise, you will implement the join shown above in an ABAP program. For this
purpose, create a new program called ZZ_####_JOIN. As always, it should be a test program
without TOP include in your package ZZ_#### and your request.

For the description of the result, define a local structure type str_join. This type shall
contain the fields CARRID, CONNID, CITYFROM, and CARRNAME. Hint: the latter is part
of the SCARR table which contains the airlines. To type the fields of this type, you can use
LIKE and access the corresponding fields of the database tables.

Then, define a work area typed with the type you defined above. Use a SELECT loop to read
one line after another into the work area. Name the columns in the SELECT part explicitly.
As both tables contain a CARRID field, you have to precede the name with one of the tables,
followed by a tilde sign. The tilde notation is also required for the join condition in the FROM
part. There, connect the two tables SPFLI and SCARR using an INNER JOIN.

Print out the content of the work area in the body of the SELECT loop, using a new line for
each entry.

Save, check, test, and activate your program. The result should look approximately like this:

Figure 63: Output of the join program: SAP-System-Screenshot

The code used for the screenshot above is given in the following figure and should be similar
to your code:

Page 62
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 64: Code of the join program: SAP-System-Screenshot

As the code can become quite confusing if many complex joins are used, it is useful to create
a suitable view in the Dictionary instead of writing codes like this. The view can then be used
to read data like from a usual table. Defining views will be discussed in detail in sub chapter
8.10.

8.4.6.2.6 Dynamic choice of tables

The third way to select tables is the dynamic specification of table names. This is done like
the dynamic specification of column names in the SELECT part of the query by using a char-
like data object in brackets:
...(dtab_syntax) [AS tabalias] ...

At runtime of the program, the field dtab_syntax must contain the syntax for the choice of
the tables. Again, casing is not respected. The addition AS can only be specified if
dtab_syntax contains only the name of one single table.

Within dtab_syntax after the element IN (see next section), only a list of fields but no
selection table may be used. Additionally, no tables with column types STRING,
RAWSTRING or SSTRING may occur in the tables10.

8.4.6.2.7 Further options

By adding UP TO n ROWS, the number of entries in the result set is limited. N is expected
to be a data element of type i. If it has the value 0, all lines will be added to the result set. If it
has a negative value, a non-treatable exception is caused.

10
Keller (2012, p. 1074)
Page 63
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

By CLIENT SPECIFIED, the automatic client handling of Open SQL can be disabled.
Client dependent tables have a first column containing the client. This field can be used if
CLIENT SPECIFIED is given to do selections in the WHERE part, or to sort the results in
the ORDER BY part (see below).

BYPASSING BUFFER causes a bypassing of the database buffer in the application server, so
it is ensured that an actual access to the database is performed. This avoids reading existing
data from the buffer that might be outdated. Further information on the principles of buffering
will follow in a later section of this course part, as announced above.

8.4.6.3 The INTO part

The INTO part (in the above syntax diagram of the SELECT statement: the target element)
determines where to store the results of the query.

The syntax is11:


... { INTO
{ [CORRESPONDING FIELDS OF] wa}
| (dobj1, dobj2, ...)}
| {INTO|APPENDING
[CORRESPONDING FIELDS OF] TABLE itab
[PACKAGE SIZE n]
...

The first possibility is using the syntax CORRESPONDING FIELDS OF wa. Here, wa is a
work area. If the result set contains more than one line, the ENDSELECT statement described
above has to be used, and line by line the result will be stored in the work area, and the
commands between SELECT and ENDSELECT will be executed. Behind ENDSELECT, wa
will still contain the last read line. Attention: This sometimes leads to mistakes, when people
use a select loop even though the loop body is empty, and only the last record is used after the
end of the loop.

By using the CORRESPONDING FIELDS syntax, only the contents of columns will be
stored for which wa contains a component with the same name. For columns which appear
multiple times, the alias names will be used; otherwise, the last column with the
corresponding name will be used.

Without CORRESPONDING FIELDS, the column contents will be stored in the order they
are specified in the SELECT part.

The second way is the specification of individual data objects (dobj1, dobj2, ...).
This is only possible if the SELECT part contains explicit column selections or the number of
data object matches the number of columns. The order of data corresponds to the order in the
SELECT part. For multi-line result sets, it is necessary to use ENDSELECT, and an iteration
will be carried out.

11
Keller (2012, p. 1081)
Page 64
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The third way is the use of an internal table into which all lines of the result set are read. If
INTO is used, the table will be initialized first. If APPEND is used instead, the existing entries
(if any) will be preserved, and the result set of the query will be appended to the existing
table. For each entry in the internal table, a data element of the corresponding line type is
created first. Then, the corresponding values will be assigned to this object. Here, the same
rules about the use of CORRESPONDING FIELDS apply as already described above.

8.4.6.4 Exercise: SELECT statement

The following code fragment reads the columns cityfrom and cityto. Hence, departure
and destination are stored in the work area wa by explicitly naming the components of wa. As
the result consists of multiple lines, ENDSELECT is used. Each element of the result set is
printed to the screen using a WRITE- statement. After the loop, wa-cityfrom and wa-
cityto still contain the last entries of the result set.

The example represents the “second way” described above.


DATA wa TYPE spfli.
SELECT cityfrom cityto
FROM spfli
INTO (wa-cityfrom, wa-cityto).

WRITE: / wa-cityfrom,
wa-cityto.

ENDSELECT.

Test the output of these lines. For this purpose, create a new program called ZZ_####_SQL.
It shall not contain a TOP include, be a test program, and be stored using your package and
request. Save, check, and activate the program after you have entered the lines given above.
Test the program and have a look at the output.

Now, further information about the flights shall be printed. As you do not know the
corresponding column names of the spfli table yet, you have to look at the structure of the
table. You could open the dictionary, but there is a simpler way. Instead, you simply double-
click on spfli. If your program has not been saved so far, you can do this now by
committing the system message. Otherwise, you will be taken directly to the table structure.
Using the F3 key, you can get back to your source code. Extend the program such that at least
one further column is printed out to the screen. Do not forget to save, check, and activate your
program.

8.4.6.5 The WHERE part

In the WHERE part of the statement, the result set is restricted.

Page 65
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The syntax is12:


...[FOR ALL ENTRIES IN itab] WHERE cond...

The syntax FOR ALL ENTRIES IN itab is an obsolete one. In earlier days, not all
databases that were used by SAP supported joins. Hence, this option was implemented as a
replacement, which defines some kind of join between an internal table and a database table.
Like this, nested SELECT loops can be avoided. The internal table should be non-empty,
because otherwise all records of the database table are taken over for the result set 13.
Generally, you should try not to use this construct. It is more efficient to create joins on the
database level. Furthermore, the system has to build up appropriate database queries based on
the data given, which may result in multiple queries again.

cond contains logical expressions that correspond mostly to the general logical expressions.
Here, columns are compared to each other and to ABAP data objects. At least one column has
to be part of the expression. Like in the SELECT part, table names can be given alongside the
column names using the tilde notation (~) if necessary.

The allowed comparison operators are = (EQ), <> (NE), < (LT), > (GT), <= (LE) and >=
(GE).

Logical expressions can be built using the AND and OR operators, or a proceeding NOT for
negation.

Furthermore, there are some special operators14:

Interval membership

Membership in an interval can be checked by


...col [NOT] BETWEEN dobj1 AND dobj2 ...

The expression is true (or untrue, if NOT is used) if the value of col is between the values of
dobj1 and dobj2.

Character comparisons

Character strings can be compared like this:


...col1 [NOT] LIKE dobj [ESCAPE esc]...

Here it is checked whether the value in the column col1 matches a pattern given in dobj.
dobj may not be a column, as it has to be a char-like data object instead. A pattern may
consist of usual characters, the masking character %, which represents an arbitrary character
sequence (which may be empty), and the masking character _, which represents a single
arbitrary character. Casing is respected for the pattern comparison, but closing whitespace in
dobj is ignored.

12
Keller (2012, p. 1092)
13
Keller and Krüger (2011, p. 729)
14
Keller(2012, p. 1096)
Page 66
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Using the ESCAPE addition, a character can be defined as an escape character. esc has to be
a char-like data object of length 1. The escape symbol may only precede a mask sign or the
escape sign itself. In the latter case, the escape sign loses its special meaning.

NULL comparison

The comparison with the NULL value is done like this:


col1 IS [NOT] NULL

Dynamic logical expressions


Also, dynamic, logical expressions may be used. The syntax is analog to the other dynamic
elements; a char-like variable in brackets is used, which contains the logical expression at
runtime.

Sub queries

Logical expressions can contain sub queries whose results can be used in the expression. The
syntax is15:
... ( SELECT result
FROM source
[WHERE cond]
[GROUP BY cols]
[HAVING group_cond] ) ...

The sub query can be used similarly to the usual SELECT statement, but there are some
restrictions. For example, there is no INTO or ORDER BY. Sub queries are called correlated
sub queries, if they reuse columns of the surrounding query.

Sub queries are used in expressions like these:

 ... [NOT] EXISTS subquery is true if the expression has no (at least one)
result.
 ... col [NOT] IN subquery ... is true if the value of the column col is
(not) contained in the results of the sub query. This requires the sub query to have only
one column.
 ... col operator {ALL|ANY|SOME} subquery ... is true if the
comparison of col with the results of the sub query is true for all/at least one value.
Similarly, the sub query may contain only one column. If it results in just one value,
ALL/ANY/SOME can be left out. ANY and SOME are equivalent.

Sub queries used in combination with NOT are usually not very efficient; hence, they should
not be used. In many cases, sub queries can be replaced by joins. However, they cannot be
given a general recommendation, because the performance can be very different and has to be
determined for each single case.

15
Keller (2012, p. 1101)
Page 67
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.6.6 The GROUP BY and HAVING parts

The GROUP BY part is used to condense groups of lines that have equal values in the given
columns. The syntax of this part is16:
... GROUP BY { {col1 col2 ...} | (column_syntax) } ...

If GROUP BY is used, the GROUP BY part has to contain all columns that occur in the
SELECT part without an aggregate function. By using an aggregate function, the values of the
other columns are determined for each group. If no aggregate function were used and there
were more columns than those that were mentioned in the GROUP BY part, these columns
would have multiple values for the same column and line, which is not allowed in the
relational database model.

Besides a static listing of the columns col1, col2 ..., the columns can also be determined
dynamically using the well-known scheme.

The HAVING part restricts the grouped lines for the result set. The syntax is similar to the
WHERE part:
... HAVING group_cond ...

As opposed to the WHERE part, grouped lines are filtered here instead of single lines of the
initial set of lines.

8.4.6.7 The ORDER BY part

The ORDER BY part is used to sort the result set. The syntax is17:

... ORDER BY { {PRIMARY KEY}


| { { col1 | a1} [ASCENDING|DESCENDING]
{ col2 | a2} [ASCENDING|DESCENDING]
| (column_syntax)
}

Sorting by the primary key, using the PRIMARY KEY keywords is only possible if the
SELECT part contains all columns of the primary key, either explicitly or using the star
notation (SELECT *), and the FROM part does not contain a view or a join.

However, otherwise, it is still possible to sort by arbitrary columns. They have to be named
explicitly as col1, col2,.... Alternatively, the alias names a1, a2,... can be used.
ASCENDING means that the sorting should be in ascending order, while DESCENDING
causes the sorting to be in descending order.

Using (column_syntax), a dynamic column selection is possible, which works similar to


the other dynamic parts.

16
Keller (2012, p. 1108)
17
Keller (2012, p. 1111)
Page 68
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.6.8 Reading data using a cursor

The previously shown use of the SELECT statement used a combination of the selection of
objects from the database and their storage into ABAP data objects as one single statement. It
is possible to separate these steps by using a cursor.

First, a cursor has to be opened and a query has to be sent. The syntax to do this is18:
OPEN CURSOR [WITH HOLD] dbcur FOR
SELECT result
FROM source
[[FOR ALL ENTRIES IN itab] WHERE cond]
[GROUP BY cols ]
[HAVING group_cond]
[ORDR BY sort_args].

The syntax of the query (starting from SELECT) is similar to the well-known SELECT
statement, but there may not be a SINGLE, INTO, or APPENDING keyword.
dbcur must be a variable of the special, predefined type cursor. The statement opens the
cursor and executes the query. The cursor then points to the first line of the result set.

To be able to access the selected results, i.e., to assign the data of the result set to ABAP data
objects, the FETCH statement is used. Its syntax is19:
FETCH NEXT CURSOR dbcur [INTO|APPENDING] target.

dbcur is the cursor that has been opened before. The syntax of target is similar to the
usual SELECT statement. This means that it can contain data objects which can store one
single element of the result set as well as internal tables, which store all or at least as many
lines as specified in the PACKAGE SIZE. This determines whether the FETCH statement
reads one, multiple, or all lines.
The cursor is moved forward by as many lines as there were lines read by the FETCH
statement. If the end of the result set has been reached, every following try to read data will
cause the sy-subrc system variable to receive the value 4, but the values of the variables
behind INTO/APPEND will not be changed anymore20.

During the fetching process, the system variable sy-dbcnt is set to the number of lines read
from the result set so far.

By
CLOSE CURSOR dbcur.

the cursor is closed again. It is recommended to do this, because there is a limitation on the
number of cursors that may be opened at once.

18
Keller (2012, p. 1114)
19
Keller (2012, p. 1115)
20
Keller (2012, p. 1116)
Page 69
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.7 Exercise: Grouping and aggregate functions

In this exercise, you will select some statistical data from the flight database and print it out
on the screen.

Open the Object Navigator and create a new Program called ZZ_####_STATISTIC. As
usual, it should be a test program and not contain a TOP Include, it should be part of your
package and your request. At the end of this exercise, you will find an example solution,
because this exercise is not trivial if you are new to SQL. However, you should try to do the
exercise on your own and not jump to the solution immediately. The duration of the course is
calculated in a way that should leave enough time to try things out and to make mistakes and
correct them.

For every flight carrier, its ID, name, and the duration of the longest scheduled flight
connection shall be printed. Carriers without any scheduled flight connections shall not be
printed. Furthermore, no carriers shall be printed whose longest scheduled flight connection
takes less than 7 hours.

In the table SPFLI, you can find information on the flight type in the field FLTYPE. Here, it
is described if the flight is a chartered flight ('X') or a scheduled flight (' ').

First, create a local structure type stat_type, containing the fields carrid, carrname,
and duration. Type the fields by using the corresponding fields of the tables SPFLI or
SCARR, respectively. Create an internal table of your structure type.

Now, create the SELECT statement. When you use aggregate functions, make sure that there
is a space between the parentheses and the content.

In the FROM part, you need the SCARR table as well as the SPFLI table, because the SCARR
table contains the carriers name, while the SPFLI table contains the data of the flight
connections.

In the INTO part, you can use CORRESPONDING FIELDS OF TABLE if you use
accordant column names for your structure type.

Use the WHERE part to restrict the query to scheduled flights.

In the GROUP BY part, you must group on all columns that are not part of aggregate
functions in the SELECT part.

In the HAVING part, you define a lower limit on the flight duration of 420, because the flight
duration is given in minutes.

Sort the result in descending order of the flight duration.

Finally, the result can be printed to the screen. For this purpose, create a variable of your
previously defined structure type. Use this variable to transport the result elements from the
internal table using a LOOP and print each result on the screen.

Page 70
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Save, check, and activate your program. If your program is correct, the output should look as
follows:

Figure 65: Output of the statistic program: SAP-System-Screenshot

If your result should not be as intended, first try to find the reason in your code. The learning
effect is much bigger if you try to find your mistakes on your own.

If you do not know how to do this exercise or if you want to compare your solution, have a
look at the solution example in the following figure.

Figure 66: Example of a statistic program: SAP-System-Screenshot


Page 71
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.1 New Syntax in OpenSQL

In the conditions of the WHERE part, when columns of the used database tables have the
same name as the local data objects used for the comparison, the classical OpenSQL syntax
might be confusing and difficult to read. Confer the following example:
SELECT carrid connid

FROM spfli

INTO CORRESPONDING FIELDS OF TABLE itab

WHERE carrid = carrid AND

connid = connid

Here, carrid and connid on the left side of the equals sign represend columns of the database
table, while they represent local variables of the ABAP program to which the column should
be compared on the right side of the equals sign. Toa void misunderstanding and make the
code more readable, SAP introduced a new syntax for OpenSQL. In this new syntax, ABAP
host variables, i.e. variables of the ABAP program that are used inside the OpenSQL
statement, are preceded by an @ symbol. Furthermore, the field list in the SELECT part is
separated by commas:

SELECT carrid, connid

FROM spfli

INTO CORRESPONDING FIELDS OF TABLE @itab

WHERE carrid = @carrid AND

connid = @connid.

8.4.2 Inserting data

To insert data into a database table, the INSERT statement is used.

Its syntax is:


INSERT { {INTO target VALUES wa}
| {target FROM { wa | TABLE itab }}
}.

target determines into which database table the new entries shall be stored. This
information can be given by a static name of a table or dynamically, using a braced variable,
which contains the name of the table (or the name of the view) at runtime.

The table or the view must be defined in the ABAP Dictionary and a write access has to be
possible. Views that consist of multiple database tables cannot be used for write access. If a
view is used which does not contain all columns of the original table, the missing columns are
filled with the initial value if such a value has been specified or, otherwise, with NULL
values.

Page 72
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Using the addition CLIENT SPECIFIED after the table name, the automatic client handling
is disabled. If this addition is not present, the current client will be used, even if the data given
in source have different values for the client field.

wa is a work area. If FROM is given, an internal table can be given instead of a work area,
using TABLE itab. In this case, all entries of the internal table are inserted into the
database table. If the internal table contains entries that would lead to duplicate key values in
the database table, the behavior depends on the addition ACCEPTING DUPLICATE KEYS.
If this addition is given, the entries of the internal table that would lead to duplicate keys are
ignored, but the other entries will be inserted. Otherwise, if the addition is not given, no lines
will be inserted and the exception CX_SY_OPEN_SQL_DB is raised.

8.4.3 Changing data

Changing data of a database table is possible using the UPDATE statement. It has the
following syntax:
UPDATE target source.

Defining the Target

By target, the database table (or the view) is selected in which the changes should take
place. This information can be given statically or dynamically using a braced char-like
variable that contains the name of the table or the name of the view at runtime.

If the addition CLIENT SPECIFIED is given, the automatic client handling is disabled
similarly to the INSERT statement.

Defining the source

The syntax of source is21:


...{ set_expression
| {FROM wa | {TABLE itab} } } ...

Hereby, it is defined which columns and which rows should be changed in what way.
The option to use a set_expression is the simplest. Here, assignments of the following
forms may be used:

 col1 = f1 col2 = f2 ... assigns the values f1, f2, ... to the columns col1,
col2.... f1, f2, ... can be ABAP data objects or other columns. The table name can
be given using the tilde notation.
 col1 = col1 + f1 col2 = col2 + f2 ... adds the values of f1, f2, ...
to col1, col2 ... and is, otherwise, similar to the form above.
 col1 = col1 - f1 col2 = col2 - f2 ... subtracts the values of f1, f2,
... from col1, col2 ... accordingly.

21
Keller (2012, p. 1124)
Page 73
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

 (expr_syntax1) (expr_syntax2) ... is the dynamic version, in which the


variable expr_syntax1 or expr_syntax2 contain the assignment formulation at
runtime.

The second option is overwriting complete lines of the database table. This can be done by
providing a work area using FROM wa or by providing an internal table using FROM TABLE
itab. If a work area is used, the system searches for a line whose primary key is similar to
the corresponding values of the fields of the work area, and the line is overwritten by the
content of the work area. If an internal table is used, the same is applied to every line of the
internal table.

8.4.4 Automatic insertion or change

There may be situations in which, during inserting of new data, it is unclear whether a line for
a certain record already exists in the database table that just needs to be updated.

It would be cumbersome to first use a SELECT statement and then, depending on the
existence of a line of the table, to execute an insert or update operation. In a situation like this,
the MODIFY statement can be used. Its syntax is:
MODIFY target FROM source.

Defining the target

The target is defined by target using this syntax22:


... {dbtab | (dbtab_syntax)] [CLIENT SPECIFIED] ...

By dbtab, a table can be specified statically, while (dbtab_syntax) allows using the
well-known dynamic formulation. CLIENT SPECIFIED disables the automatic client
handling.

Defining the source

The syntax of the source specification in source is23:


... FROM wa | {TABLE itab} ...

If a work area wa is given, the database table is searched for a record whose primary key
matches the corresponding columns of the work area. If such a record is found, it is changed
according to the rules of the UPDATE statement. If no record is found, the work area is
inserted using the INSERT statement.

If an internal table itab is given, all lines will be processed like the work area described
before, one by one.

22
Keller (2012, p. 1130)
23
Keller (2012, S. 1130)
Page 74
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.4.5 Deleting data

Do delete lines of a table, use the DELETE statement. Its syntax is24:
DELETE { { FROM target [WHERE cond] }
| {target FROM source} }.

target defines the table or view in which the records that have to be deleted are located.
This can be a static table name (or view name), or a dynamic specification in a braced
variable. The addition CLIENT SPECIFIED to disable the automatic client handling is also
allowed here.

The lines that shall be deleted can be determined using a WHERE part or based on the
source part. The WHERE requires the specification of a logic condition cond. All lines of
the table for which the logic expression cond is true will be deleted from the database table.
The source specification contains a work area or an internal table. If a work area is used, all
lines of the database table will be deleted that have a primary key similar to the corresponding
fields of the work area. If an internal table is used, this operation is performed for each line of
the internal table.

24
Keller (2012, p. 1132)
Page 75
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.5 Authorizations
To protect the contents of database tables from unauthorized access, the SAP system contains
an authorization concept. This concept can be used by developers to implement an
authorization control.

For the understanding of authorization checks in ABAP programs, a basic comprehension of


the authorization concept in the SAP system is necessary. This authorization concept by SAP
is based on authorization objects. The authorization objects are ordered by certain criteria in
object classes. These object classes can be seen by authorized users in the transaction SU21.
An authorization object itself does not grant the access of an SAP user to a certain object or
activity. Instead, the authorization object defines a set of parameters that are relevant to
determine the actual authorization. This is in particular the parameter ACTVT, which
represents the activity of the user. Nevertheless, many further parameters may be added to the
authorization object.

Each user of the system has a user master record, in which authorizations are assigned to
him. These authorizations refer to a certain authorization object and determine which actual
authorizations the user does have in the context of the authorization object. Here, multiple
authorizations may exist for the same authorization object. The authorizations are not
assigned directly to the user. Instead, they are collected in profiles. Single profiles and
composite profiles can be distinguished, where the latter contain profiles themselves. A more
recent technology to assign authorizations is roles. These represent specific tasks of a user in
the system, based on which the corresponding profiles with the appropriate authorizations can
be generated

Page 76
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 67: Overview of the authorization concept


.

The fact that there is a specific authorization object defined in the system does not imply that
there is an actual authorization check if someone accesses the corresponding activity. Such a
check must be implemented by the developer explicitly. This is done using the AUTHORITY-
CHECK statement. This statement checks whether there is an authorization for the access or
not, and sets the value of sy-subrc accordingly. It is the task of the developer to read this value
and to send an error message if there is no authorization (preventing the access).

The AUTHORITY-CHECK statement accesses the user master record first to check whether an
authorization is available. Depending on the result, the value of sy-subrc is set:
 sy-subrc = 0: Authorization exists, the operation can be performed.

 sy-subrc <> 0: Authorization does not exist. The activity should be canceled and
the user should be informed.

Page 77
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Creating an authorization object is usually the task of the one who creates the database table.
In case of the flight data example, the predefined object S_CARRID can be used.

The task of the profile management and maintenance of the user master records is a task of
the administrator.

Page 78
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.6 Exercise: Authorizations


Open your program ZZ_####_FLIGHTS in the Object Navigator. Click on the -button
(Other Object). Navigate to the tab More… using the -buttons and select Authorization
object. Enter the name S_CARRID and commit. You can see the authorization object now:

Figure 68: The authorization object S_CARRID: SAP-System-Screenshot

You see that this object has two fields: The ID of the carrier and an activity field. Click on the
button Permitted Activities to see the possible values for the activity field.

Page 79
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 69: Permitted Activities: SAP-System-Screenshot

Open your function module Z_####_GET_FL. Go to the tab Exceptions and add another
exception called no_auth, which will be used for the case of a missing authorization and add
a suitable short text. Save and go to the source code tab. Position the cursor into the line
before the SELECT statement and click on the Pattern button. There, choose AUTHORITY-
CHECK and enter S_CARRID.

Figure 70: Insert an AUTHORITY-CHECK using the pattern button: SAP-System-Screenshot

Now, a pattern for the statement appears in your source code. Replace the values on the right
side of FIELD by im_carrid (which is the parameter) and '03', respectively (03 is the
activity for displaying. The single quotes are required because the type is character-like).
Make sure you do not have any quotes around im_carrid, because then you would transfer
the expression “im_carrid” instead of the value of the parameter with this name.
Add a check of the sy-subrc value, which raises an exception if there is no authorization
(using the RAISE statement).

Page 80
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Your code should now contain the following statements:

Figure 71: Code for the authority check: SAP-System-Screenshot

Save, check, and activate your function module. Then, open your program
ZZ_####_FLIGHTS and add another exception value in the EXCEPTIONS of the function
module call, for example:

EXCEPTIONS
NO_AUTH = 7

Check the new value also by extending your IF-construct, which is already checking the sy-
subrc. Print an error message on the screen instead of the flight data if the value 7 has been
found.

Save, check, and activate your program. If you test it, you should see a difference depending
on the Airline entered. Usually we configure your user in a way that you are only allowed to
see flights of Lufthansa (LH), while the authorization is missing for other airlines.

Please note that this new exception (no authorization) will also appear if you enter a non-
existing flight, as your authorization is strictly limited to LH. This is a design decision:
Should a user be able to find out if a record exists or not, even if he is not allowed to access
it? If you want to change this behavior, you must take the AUTHORITY CHECK and its
corresponding IF statement and move both below the other IF statement. Then the existence
error will appear also for non-authorized airlines if they don’t exist.

Page 81
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.7 Indices
Indexes are used to make it possible to find certain records in a database table more quickly.
They can be seen as a shortened representation of the table, from which it is possible to access
the complete record in the original table easily based on a corresponding pointer. This process
can be compared to an index in a printed book, where the page number displayed is the
pointer to the complete entry. For a table, it is possible to define multiple indexes, which exist
independently. The decision whether or not and which index to use is the task of the
optimizer. The efficiency and the used indexes may be different depending on the database
system used. It is possible to analyze which indexes are actually used based on traces.

There are two types of indexes: primary and secondary indexes. The primary index is an
index based on the primary key of the table. It is automatically created by the system as soon
as a table is created. Secondary indexes are additional indexes which must be created
explicitly by the user. Creating indexes is useful if there are certain fields in a table which are
often used in the WHERE part of database queries, and where it hence seems promising to try
for a performance gain. An index can be marked as a unique index. This means that for each
entry of the index, there may only be one entry in the original table.

Figure 72: Access with or without index

It is important to think before creating useless or too many indexes 25: It should be made sure
to maintain a proper order of fields in the index, where the first field has identical fields for
multiple database records, and it should be made sure only necessary indexes are created,

25
Gupta (2011, p. 122)
Page 82
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

because they have to be maintained. This means, the database system must refresh them
constantly.

Indexes are described by a three-character ID. On the database level, the name of the index
consists of the name of the original table and the ID, separated by a tilde. The naming
conventions of the SAP system must also be respected for indexes.

8.8 Exercise: Creating a secondary index


Open the ABAP Dictionary and select your table ZZ####_STUDS. In this exercise, a
secondary index for the name and first name fields shall be created, as it can be expected that
many queries will use these fields in their WHERE part.

Choose the menu path Goto -> Indexes. Then, click on the Create button and Create
Index. The system now asks for the index name (which is the ID described before).

Figure 73: Creating an index: SAP-System-Screenshot

Choose the index name Z1 and commit. On the next screen, choose a suitable short
description and enter the fields for name and first name in the table at the bottom.
The index shall be non-unique, because it is possible that there are two students with the
same name.

Page 83
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 74: Maintenance of index properties: SAP-System-Screenshot

Save, check and activate the index. The status information changes accordingly:

Figure 75: Status of the index: SAP-System-Screenshot

Page 84
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.9 Buffering
After you have gained some knowledge about the selection of data records, now the topic of
buffering will be deepened.

In the buffer, records are ordered by their key values. If secondary indexes have been defined,
they are also used for sorting. Queries to the buffer can only be performed up to the last key
field. If the first key field is missing in the query, the complete table has to be traversed
sequentially to determine the result set (“Full Table Scan”)26.

If, however, the decision has been made to buffer a table, there are still three different types of
buffering to choose from:

 Full buffering: Here, all records of the table should be loaded into the buffer as
soon as one record of the table is accessed.
 Generic area buffering: Here, during access to a record, all records of the database
whose left-aligned part of the key matches the selected record should be buffered.
 Buffering single records: Here, only the record that has been accessed is buffered.

8.9.1 Full buffering

A fully buffered table can either exist completely in the buffer or not at all. During access of
one record of the database, all records are loaded into the buffer.

The following figure depicts the process using the SPFLI table. The Client field and some
other fields have been left out to simplify the presentation.

26
Gupta (2011, p. 117)
Page 85
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 76: Full buffering

A full buffering is recommended for tables which27

 are small

 are being read often

 contain many queries that lead to an empty result (access to non-existing records).
Because all records exist in the buffer, the non-existence can be decided based
only on the buffer.

8.9.2 Generic area buffering

The generic area buffering does not load all records of the database table into the buffer.
Instead, only those records are loaded whose generic key fields match those of the selected
record. The generic key is the part of the key that is selected when the generic area buffering
is configured. It consists of a left-aligned part of the key of the table.

27
Gupta (2011, p. 118)
Page 86
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The generic area buffering is useful if many accesses to specific, generic areas of the database
table occur. For client-dependent tables (tables containing the MANDT field), the system
automatically uses a generic buffering based on the client field even if full buffering is used,
because it can be assumed that there is no parallel access to records of multiple clients.
Another example where generic buffering is useful is the buffering of language dependent
tables28.

The following figure shows an example of generic area buffering, assuming CARRID is part
of the generic key:

Figure 77: Generic buffering

The choice of the generic key determines the number of areas that exist in the buffer. If the
key is chosen too small, too many areas will appear; in this case, a full buffering may be more
efficient. However, a too large generic key might also be a problem, because too much data
must be loaded into the buffer29.

28
Gupta (2011, p. 118)
29
Gupta (2011, p. 118)
Page 87
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.9.3 Buffering single records

The smallest amount of data is buffered in single record buffering. The buffering of single
records is only applied to the access with SELECT SINGLE and buffers the record that has
been accessed. All other queries directly access the database. Single record buffering is
recommended for large tables with record sizes between 100 and 200 KB. For small tables, it
is not efficient30.

The single record buffering can also be demonstrated using the example from above:

Figure 78: Single record buffering

8.9.4 Synchronization of buffers

There is a problem if data is changed that is still buffered in the buffer of an application
server. There can be multiple application servers, which have their own buffers, in a system.
In these cases, inconsistencies must be prevented.

30
Gupta (2011, p. 119)
Page 88
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 79: Buffering in two application servers

For these scenarios, a synchronization of buffers is necessary. In SAP, this is realized by the
synchronization table DDLOG. In regular intervals, the system checks if there are changes in
this table and which application server caused them.

The configuration of this process is done by profile parameters. The parameter


“rdisp/bufrefmode” enables or disables synchronization (e.g., if there is just one application
server). The parameter “rdisp/bufreftime” selects the duration between two synchronizations.
The default value of this parameter is 60 seconds31.

The principle of synchronization can be exemplified using an example that consists of two
application servers32. In the initial situation, they both have already read data from table
zz_mytab, so the buffers do already contain records of these tables. We assume that full
buffering is selected.

31
Schneider (2002, pp. 288 f.)
32
Cf. Example of Schneider (2002, pp. 287 f.)
Page 89
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 80: Synchronization example, 1/4

In step 1, application server 1 accesses and changes the database table zz_mytab. In step 2, the
database interface fills the local buffer of this server with the changed data. In the third step,
the database interface adds an entry to the DDLOG table, which indicates that there have been
changes on the table zz_mytab.

Page 90
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 81: Synchronization example 2/4

In the current state, inconsistencies could occur because the buffer of application server 2
contains data that has been changed in between. These inconsistencies can occur despite the
synchronization process. A permanent synchronization of all buffers would be too inefficient.
However, at the next synchronization time, the buffer of application server 2 is marked as
invalid (step 4 in the figure above), because of the entry in the DDLOG table.

Page 91
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 82: Synchronization example 3/4

Assume now that a program on application server 2 wants to access the table. The DB
interface recognizes that the buffered version is invalidated (5), so the query is performed on
the database (6).

Page 92
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 83: Synchronization example 4/4

In the last step (7), the buffer of application server 2 is filled with the data from the database
table. Now, both buffers represent the current state of the database table.

Page 93
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.10 Views
Views represent certain perspectives on one or multiple tables of the database system. They
can be used to provide only the required data for an application that may be accessed by this
application. Furthermore, views can be based on several tables that are connected using a join.
If an application requires the same join very often, the creation of a view is a simplification,
because it can be accessed in Open SQL just like a regular database table.

Because of this, similar use of views and tables, the names of views, and the names of tables
may not overlap. It is recommended to choose a name that indicates that it is a view to avoid
confusion.

Advantages of database views are:

 Usability in multiple programs


 Possibility to search for a certain, already defined view using the well-known search
techniques
 If views consist of multiple tables connected by a join, common fields have to be
transferred only once from the database in a query.
 Due to the use of inner joins, unnecessary records are left out for which no suitable
record is found in the other table.

Using selection conditions, the set of records in a view can be restricted. By specifying join
conditions, it can be determined which records of which database table should become part of
the view or not. This way, a subset of the cross product of all records is described. You
already know join conditions from the formulation in Open SQL. Here, you will do something
similar in the context of a view definition in the Dictionary. Database views are built by inner
joins. Outer joins will be used for maintenance views.

8.10.1 Exercise: Creating a view

In this exercise, a view shall be created which is based on the exercise about the use of the
Data Browser.

Open the ABAP Dictionary (transaction code SE11). Choose View and enter
ZZ_####_VIEW_FL into the text field. Then, click on the create button.

The system asks for the kind of view now. Here, four possible choices are available:

 Database view: These views exist as real views created on the underlying database
system.
 Projection view: These views are used for the masking of particular columns of a
table.
 Maintenance view: These views are used if objects that are one unit, from the user’s
perspective, are split up into different tables on the database level.
 Help view: These views are only relevant for the help system.

For this example, choose the Database view option, and then enter a suitable short
description.

Page 94
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Go to the tab Table/Join Conditions. On the left side, enter the table SPFLI into the list of
tables. On the right side, joins can be defined. This is not necessary for this exercise. Instead,
go to the tab View Flds. Here, the columns are defined that will become part of the view, and
alias names can be defined. In the first line, enter SPFLI as the Table and MANDT as the
Field (not View Field), and use the value help for this task! The other columns are filled
automatically now. It would be possible now to choose a different alias name in the View
field column.

Now, use the same scheme to add further fields for AIRPFROM, AIRPTO, CARRID,
CITYFROM, CITYTO, COUNTRYFR, COUNTRYTO, and CONNID. Alternatively, you
can add the fields using the Table Fields button, which offers a simple selection of fields.

Now, go to the tab Selection Conditions. Here, the conditions are specified to which the lines
of the result set have to match. The conditions that were used in the Data Browser exercise
shall also be used here. This requires adding four lines on this tab. The first line contains the
table SPFLI, the field name CARRID, the operator EQ (equals), and the comparison value
'LH'. This causes Lufthansa flights to be shown. Enter OR in the last column to make the next
line or-connected to this line. The second line should be similar to the first, but CARRID 'DL'
must be used and the AND/OR column must contain AND, because the following restrictions
of the flight duration shall be and-connected. In this case, consider the higher binding power
of the OR. OR connections are only allowed between field comparisons of the same column.

The next two entries are used to constrain the flight duration. The lower bound is entered
using the GE operator (greater or equal) and comparison value 60, while the upper bound is
entered using the LE operator (less or equal) and comparison value 360. In the first of these
conditions, enter AND in the AND/OR column. The flight durations are defined in minutes
here.

Now, go to the Maint. Status tab. Here, it is defined if the view can be accessed for writing
statements. Leave the settings unchanged. Save, check, and activate your view.

Now, go to the Data Browser (transaction code SE16). Enter the name of your view as the
table name (ZZ_####_VIEW_FL) and do not enter any further constraints. Instead, commit
using F8 directly. As in the Data Browser exercise, you see three flights that match the
criteria defined as selection criteria for the view. They are projected to the columns that were
defined as view fields.

Page 95
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.10.2 Maintenance dialogues

Often objects of the real world are spread over multiple tables in the database. However, the
user is interested to maintain the objects as a whole in most cases, which means he or she
wants to be able to create, update, or delete the objects without having to edit multiple tables
in the database.

For this purpose, the SAP system offers maintenance views. A maintenance view is a special
kind of view, which is used to maintain objects that are spread over multiple tables in a
convenient way. The definition of a maintenance view is combined with the definition of a
corresponding user interface that is called the maintenance dialog. The generation of this
dialog is initiated from the view maintenance or directly using the transaction code SE54. The
function modules that realize the data distribution between the different are generated
automatically.

Figure 84: Maintenance view and maintenance dialog

The key fields of the tables (including the client field) should be part of the view and be
placed consecutively at the beginning. A violation of this requirement causes a warning
during activation.

Maintenance views are not intended to be used for the data maintenance in production
systems, because data inconsistencies may occur. Using maintenance views, medium-sized

Page 96
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

amounts of data for customizing and customer tables can be entered in which there are no
interferences possible.

The configuration of a maintenance dialog is explained practically using the following


example.

8.10.2.1 Exercise: Maintenance dialogs

In this exercise, a maintenance dialog for the tables SBUSPART and STRAVELAG shall be
created. The table SBUSPART contains data about business partners. As business partners
may be flight customers and travel agencies as well, there are separate tables for the specific
attributes in the database. The maintenance dialog shall make it possible to maintain the
specific attributes from the STRAVELAG table together with the general attributes from the
SBUSPART table. Before you start, use the ABAP Dictionary or the Date Browser to get an
idea of the structure of these tables.

Open the ABAP Dictionary and choose the View entry. In the text field, enter the name
ZZ####_PARTNER. Create the view and choose Maintenance View as the type.

Figure 85: Creating a maintenance view: SAP-System-Screenshot

Choose a suitable short description and select the table SBUSPART in the table column on
the left. Commit this entry using the Enter key. In a maintenance view, only those tables can
be contained that are connected to the primary table (which you just entered) by a foreign key.
To see these tables and to be able to select them, put the cursor into the field with the primary
table name and click on (on the bottom left). A window containing
all relationships of the table appears:

Page 97
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 86: Relations of the SBUSPART table: SAP-System-Screenshot

If a table contains relations that have a cardinality, which is not allowed for a maintenance
view, the corresponding tables will be listed separately. Activate the checkbox in front of
STRAVELAG and commit by clicking on Copy. Now, you can see that the system
automatically determines the join conditions:

Figure 87: Automatic join conditions: SAP-System-Screenshot

These automatic join conditions were generated based on the foreign key relationship of the
tables.

It is also possible to add tables that are not related to the primary table based on a foreign key
relationship, but instead have such a relation with one of the other tables that are part of the
view. The method to add these tables is similar to the one for the primary table described
above. However, for our exercise, the two tables SBUSPART and STRAVELAG are
sufficient.

In the next step, the fields of the view have to be determined. This is done using the tab View
Flds.

Page 98
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The key fields are already entered there. They have to be part of the maintenance view. The
same applies to possible key fields of secondary tables that are not already contained in the
view due to a join condition with a key field that is part of the view.

To add further fields, click on . In the next window, choose SBUSPART and
in the following window, choose all fields of the table and commit (Copy).

Figure 88: Field selection for the maintenance view: SAP-System-Screenshot


Repeat these steps for the fields of the STRAVELAG table, except the fields MANDT and
AGENCYNUM. These are the fields used to create the relationship.

Now, go to the tab Selection Conditions. Here, conditions can be specified to restrict the set
of data that is available from the view. In our example, all data shall be available, so this tab
stays unchanged. Instead, open the tab Maint.Status. Here, it can be defined how view can be
accessed from the View Maintenance (transaction code SM30). Make sure that the values
read, change, delete, and insert are selected in the Access section.

Save, check, and activate the view.

Now, the maintenance dialog shall be configured. For this purpose, choose the menu path
Utilities(M) -> Table Maintenance Generator.

Page 99
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 89: Table Maintenance Generator: SAP-System-Screenshot

Here, several settings can be configured:

Authorization Group: This field is used to determine which user is allowed to maintain the
view. Enter SUNI into this field.

Function Group: This field determines in which function group the function modules
described above shall be created. Enter ZZ_####_FGP here. This function group will be
created automatically later, because it does not exist.

Maintenance Type: Here, a one-step or a two-step user interface can be chosen. The one-step
version consists of only one screen in which the contents are displayed as a table. In the two-
step version, the first screen shows the key fields and text fields with a length of more than 20
characters. In a detailed perspective (2nd view), all data is available. For this example, choose
the one-step version.

Maint. Screen No.: Here, the internal number of the screen can be specified. For our
example, enter 0100 (as the overview screen).

Now, the maintenance dialog must be saved, which is done using the -button. In this case,
do not choose your regular package. Instead, choose $TMP. This name represents local
objects. Local objects are not transported into other systems, which is useful for this
temporary tool. Important note: Make sure not to use $TMP for the following exercises!

Page 100
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

To test the maintenance dialog, choose the menu path System -> Services -> Table
Maintenance -> Extended Table Maintenance or use the transaction code SM30. Enter
ZZ####_PARTNER as the Table/View and select Display. Now, you see a list of business
partners, and, if the business partner is a travel agency, also the specific fields are visible (you
have to scroll vertically and horizontally to see this).

8.10.2.2 View clusters

As described above, maintenance views are restricted to 1:N relationships. To be able to


represent more complex relationships, view clusters are used. They consist of individual
maintenance views that maintain data that belongs together from a technical or business
perspective. Also maintenance dialogs without key dependencies can be combined to a view
cluster. Within the cluster, consistency is maintained. For example, if data is deleted on one
level, dependent data on other levels is deleted, too33.

First, the individual maintenance dialogs have to be generated. Then, they are connected to a
view cluster using transaction code SE54. Within the view cluster, navigation between
different maintenance views is available.

33
Gupta (2011, p. 250)
Page 101
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.11 Special kinds of tables


So far, for the presented tables, there was a corresponding counterpart with the same name in
the database system for every logic representation in the ABAP Dictionary. These Tables are
called transparent tables. However, there are also cluster- and pool tables, which are
special kinds of tables for which there is no similar 1:1 relation. For these tables, multiple
tables from the ABAP Dictionary are condensed into one table of the database system.

8.11.1 Cluster tables and table clusters

Multiple tables that have some parts of their key in common (functional dependent tables) can
be combined to form a table cluster. For this purpose, the tables are first created as regular,
transparent tables. Then the table type can be changed using the menu path Extra -> Change
table category.

Figure 90: Change table type: SAP-System-Screenshot

After the change of the table type, the Delivery and Maintenance tab contains an additional
field to select the table cluster the table shall be assigned to.

This table cluster is represented as a table in the database system containing the following
fields34:

 Fields for the common key components

 PAGENO: A number to distinguish continuation records, if one row is not enough for
representation

 TIMESTAMP: A time stamp for administrative purposes

 PAGELG: Length of the VARDATA field

 VARDATA: String which contains all other fields of the cluster tables. Hence, the
data is not directly accessible outside the SAP system

The following figure depicts the structure of a table cluster.

34
Gupta (2011, pp. 80 f.)
Page 102
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 91: Structure of a table cluster 35

As you can see in the figure, only the table cluster is part of the database system. The tables
inside the cluster are only visible within the SAP system.

8.11.2 Pool tables and table pools

Table clusters can only be used for tables with common key components. For tables that do
not match this requirement, table pools are available. The effect is similar to that of defining a
table cluster: small tables of the application layer (the pool tables) shall be combined to a
single, large database table (the table pool).

The table pool consists of the following fields36:

 TABNAME: Name of the pool table to which the record belongs

 VARKEY: Character-typed field (maximum length 110), which contains the key
fields of the pool table

 DATALN: Length of the VARDATA field

 VARDATA: String that contains all other fields of the pool table

35
Cf. Gupta (2011, p. 81)
36
Gupta (2011, p. 79)
Page 103
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The following figure depicts a table pool consisting of two pool tables.

Figure 92: Structure of a table pool37

8.11.3 Rating of pool and cluster tables

Advantages of pool and cluster tables are:

 Simplification on the database level (fewer tables to administer)

 Compression of VARDATA fields possible

 Fewer database queries due to the simultaneous retrieval of coherent data from cluster
tables

On the other hand, there are several disadvantages38:

 No secondary indexes possible

 No select distinct or group by/ order by only for primary key fields

 No access with Native SQL

37
Cf. Gupta (2011, p. 80)
38
Some from Gupta (2011, p. 82)
Page 104
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

 Selection in cluster tables is limited to cluster key fields

 Unused length of key field for pool tables with shorter keys

Page 105
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.12 Changing dictionary objects


Due to the mutual use of dictionary and repository objects, there are many dependencies in
the SAP system. For example, a data type defined by you uses a previously defined domain.
In this case, the data type is dependent on the domain. Often these dependencies occur across
multiple levels, e.g., your data type could itself be part of a table type which is then in turn
dependent on the other two objects.

8.12.1 Dependencies and activation

Especially in cases where you modify an object that is used many times by different other
objects, you should be very careful. In such a case, changing the object will cause lots of
changes in the dependent objects. There is even a threat that dependent objects may become
inconsistent. For example, a program might be unable to work after a certain data type has
been changed, which is used by the program. Hence, it is recommended to get an overview of
which objects will be affected by a change before this change is actually performed in the
system.

Figure 93: Where-used-list

To analyze the situation of dependencies between objects, the SAP system offers the
functionality of a where-used-list. Using this functionality, all objects can be determined that
use a certain object. Here it is not only possible to find Dictionary objects, but also, e.g.,
programs in which the Dictionary object to be changed is currently used. Furthermore,
indirect dependencies can be displayed. This includes objects using objects that use the
currently looked at object. The SAP system also offers possibilities to restrict the search of
dependent objects to specific areas. For example, it is possible to search in a defined package
or to limit the search to a certain type of object.

Page 106
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.12.2 Activating objects

When you perform a change of an object, this change is not immediately effective in the
whole SAP system. Instead, a second version of the object is created, which exists in parallel
and is only visible to the developer. The two versions are called the active version and the
inactive version of the object, respectively. Only the active version is the version that is used
by most system components (ABAP runtime environment, database interface). By activating
the inactive Version, the currently active version is replaced by the inactive version. If there
are dependent objects of the object that has been activated, they must also be re-activated
during this process. These dependent activations are triggered automatically by the system.
Please note that the activation can be time-consuming if there are many dependent objects in
the system. Because of the threads that come with the activation of an incorrect object, the
activation also triggers a check. Problems which occur during the process of activation are
stored in the activation protocol. The developer gets a notice about the problem. You have
seen warnings about activation problems in the exercises already (the messages about missing
enhancement categories). When a changed version is saved but not yet activated, no check is
necessary, because other parts of the system are not influenced by this version.

Figure 94: Active and inactive version of a structure

The figure displays an example of activation. The developer changes a structure by removing
one of the fields. This modified version is inactive and exists in parallel without changing the
currently active one. The activation replaces the active version by the previously inactive one.

Furthermore, a runtime object is generated during the activation. This runtime object
contains all properties which are necessary to use the object. This may include information
Page 107
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

that is theoretically part of a different, used object. The runtime object is used internally by
the ABAP runtime. Nevertheless, it is possible to display the object using functions of the
Dictionary.

8.12.3 Where-used list exercise

Open the initial screen of the ABAP Dictionary. Select Data Type, enter S_CONN_ID, and
click on the -button.

Now, you see the data element that is used for the description of flight numbers. Click on the
-button (Where-Used List).

The following window appears:

Figure 95: Selection window for the where-used list: SAP-System-Screenshot

Make sure that only the usage in table fields is used for the search and commit your input.
Now, you see a large list of tables in which the data element S_CONN_ID is used (see the
next figure).

By using a double-click, you can have a look at each table.

Page 108
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 96: Results of the search: SAP-System-Screenshot

If you assume that there are many users (many objects which use the current object), you
should execute the search in the background.
Open the data element S_CONN_ID again and click on the -button (Where-Used List)
again. In the following window, select Table Fields and Struct. Fields. This time, do not
commit using the green check mark. Instead, use the -button.

Figure 97: Determine start date: SAP-System-Screenshot

In the window shown in the figure, select Immediately, and commit. The System executes
the search in the background while you can continue your dialog processing.
You will be noticed when the search has been finished. However, this happens only when you
communicate with the System the next time using your SAP GUI. Hence, choose a different
screen, e.g., by simply leaving the data element by pressing F3. Now, the following window

Page 109
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

should appear. If not, your background job has not been finished and you have to call another
(arbitrary) screen.

Figure 98: A background job has been finished: SAP-System-Screenshot

In this window, click on the -icon (not ). The result list appears, which has the same
structure as the list seen before; there should only be more hits in the list as the search area
has been larger.

8.12.4 Changing tables

Changes of database tables (i.e., changes of the structure of the table, as we are not talking
about simple changes of the contents of a table), are a complex task. Here, it must be noticed
that there is not just a representation on the application server that has to be changed
(Dictionary/ runtime object). Instead, the actual table in the database system has to be
changed, too. The latter can be difficult.

Page 110
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 99: Necessary changes at different places

A special difficulty occurs as soon as the table already contains data, which might be affected
by the change of the table structure. Hence, changes of existing tables should be avoided if
possible. This applies in particular for production systems, because during the process of
change, the tables are not available in the system and problems can occur if programs try to
access the tables in this period of time.

There are three general ways to apply changes to a database table:

Changing the table using built-in means of the database system. Using the SQL statement
ALTER TABLE, it is possible to apply certain changes on the database level. Here the data of
the table is kept. However, the possibilities to use ALTER TABLE are limited. There are
changes that cannot be performed this way by the database system and that have to be done
using one of the other ways instead.

Deleting and recreating the table. The possibility to delete and recreate the table is available
in any case. The most important disadvantage of this solution is that all data stored in the table
will be lost. However, if the table is empty, this is not a problem and the technique can be
used.

Using a table conversion. The process of table conversion is partially similar to the previous
one (deleting and recreating the table). The difference is that the old version of the table is not
deleted immediately. Instead, it is renamed and kept. Then the new table is created and
afterwards the data of the renamed old table is moved to the new table. This process is
Page 111
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

controlled by the SAP system. On an attempt to activate a changed database table, the SAP
system informs the user if a table conversion is necessary. The disadvantage of this solution is
the high effort and memory requirement due to the storage of the original version of the table.

It depends on different factors, which possibly can be applied in a specific case. For example,
the contents of the table, the kind of structure change, and also the type of database system
used are relevant here. There are some exceptional cases though in which no change on the
database level is required at all: This is the case if only the order of non-key-fields shall be
modified. In this situation, it is sufficient to apply the change in the dictionary, whereas the
database table remains unchanged. Hence, the order of fields in the dictionary does not have
to correspond to the field order on the database level.

8.12.5 The conversion process

In the following description, the process of a table conversion is explained step-by-step using
a simple example39.

Figure 100: Table conversion 1/5

It is assumed that there is a table ZZMYTAB, which has been activated already and hence
also exists in the database. It also contains some data already. Furthermore, there are two
indexes for the table. In the dictionary, the table has been modified (the length of one of the

39
Steps according to Gupta (2011, pp. 376 ff.)
Page 112
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

fields has been changed). The modified version has been saved, but not yet activated. Hence,
it exists in parallel together with the active version as an inactive version in the dictionary.
The figure above shows the initial situation.

Figure 101: Table conversion 2/5

Now, a lock is set for the table in the dictionary. Further changes or access to the table is now
impossible though. In the database, the table is renamed by adding QCM to the beginning of
the name. The existing indexes are deleted.

Page 113
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 102: Table conversion 3/5

In the next step, the modified table is activated in the Dictionary. The lock is still active,
because the data is not yet accessible. Because of the activation, a new table named ZZ;YTAB
is created in the database. This table has the structure of the modified version, but it does not
contain any data.

Page 114
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 103: Table conversion 4/5

The data from the backup table QCMZZMYTAB is now copied into the newly created table
ZZMYTAB. Here, the ABAP statement MOVE-CORRESPONDING is used, which
transports data to fields with the same name. If types are different, the usual conversion rules
are applied here. This should be noticed, especially in cases like the one described here, where
a field is made smaller. If key fields are made smaller, records can be lost due to duplicate key
values after the shortening. Further information on the statement can be found in the keyword
documentation.

Page 115
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 104: Table conversion 5/5

After the data has been copied to the new table, the indexes are also recreated. The temporary
table QCMZZMYTAB is deleted, and finally the lock in the Dictionary is released. The table
is usable again and has the modified structure now.

It may happen that there are errors during the process of table conversion, which cause the
process to be terminated. One possible reason is a lack of memory: During the conversion
process, there is a period of time when both tables, the old and the new one, exist in the
database and contain data. Hence, a certain amount of space is required. It is recommended to
check the availability of memory in the table space before a complex conversion is initiated.
If a table conversion process terminates unexpectedly, this is written to specific log files. The
conversion can then be continued using the database utility (transaction code SE14). It is also
possible just to release the lock, but this can cause major problems depending on the step of
the conversion process where the error occurred. In any case, the table conversion process
requires a certain amount of time in which the table is not available. This should make clear
why a table conversion should not be executed during productive runtime of a system.

Page 116
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.12.6 Conversion exercise

For this exercise, you will have to define another table. Generally, the conversion could also
be exemplified using the students’ table, but in case of a failure during the conversion, you
could not work with this table anymore.

Hence, open the dictionary and create a table ZZ####_CONV. Add a suitable short
description, select Delivery Class A and Display/Maintenance Allowed. Switch to the tab
Fields. First, enter the field MANDT with the data element MANDT. Commit this field using
the Enter key and then click on . Now, you can directly enter the type of the
following fields; the corresponding input fields become editable:

Figure 105: Direct typing: SAP-System-Screenshot

Add a field THEKEY of type NUMC with length 10 and a field THEVALUE of type CHAR
with length 20. Make MANDT and THEKEY key fields and save the table. Make sure that
your package ZZ_#### is used and not $TMP!

Figure 106: Fields of the table ZZ####_CONV: SAP-System-Screenshot

Go to the technical settings using the menu path Goto -> Technical Settings. Choose Data
class APPL0 and the smallest Size category. Save the technical settings and go back to the
table. Activate the table.

Now, choose the menu path Utilities(M) -> Table Contents -> Create Entries. If this entry
is greyed out, your maintenance settings are probably wrong.

Enter a key (consisting of numerical characters) and a short value and save the record. Repeat
this process for some more entries.

Page 117
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Go back to the table now. Choose the menu path Utilities(M) -> Table Contents -> Display
to look at your records (simply commit the search mask).

Figure 107: Data of the table: SAP-System-Screenshot

Go back to your table, choose the tab Fields, and change the length of the THEVALUE field
from 20 to 18 characters. If the field is not editable, you have to click on
first. Save your table and try to activate it. An error message (as opposed to the usual
warnings) is displayed:

Figure 108: Error message: SAP-System-Screenshot

Close the window using the X symbol. The activation protocol is displayed (otherwise,
choose Utilities -> Activation Log). You should see these lines:

Figure 109: Error during activation: SAP-System-Screenshot


The system noticed that an adaptation of the database table using the ALTER TABLE
command is not possible, hence, a conversion is necessary. Leave the transaction and open the
Database Utility instead (transaction code SE14).

Page 118
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 110: Initial screen of the Database Utility: SAP-System-Screenshot

Enter the name of your table as the Obj. Name and choose Tables in the Dictionary objects
section. Then, click on the Edit button.

Make sure that Save data is selected at the bottom and click on
. As ALTER TABLE is not possible, this initiates the
table conversion. Commit the confirmation dialog.

The system should inform you about the success:

Figure 111: Success message: SAP-System-Screenshot

Leave the Database Utility and go back to the ABAP Dictionary. Open the table
ZZ####_CONV again. You see that the table is active again and the THEVALUE field has
the correct length:

Figure 112: Changed table: SAP-System-Screenshot

Page 119
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Open the menu path Utilities(M) -> Table Contents -> Display and commit the search mask
as before. You see that the data survived the change of the table structure due to the
conversion process:

Figure 113: Table content after the conversion: SAP-System-Screenshot

8.12.7 Extending SAP standard tables

In this section, you will learn about possibilities to enhance SAP standard tables without the
need for a modification. This includes an explanation of the warning you have seen during the
activation of some Dictionary objects in the previous exercises.

8.12.7.1 Append structures

As explained in the previous section, it can be very difficult and risky to make a change of a
table. This is in particular relevant for predefined tables outside the customer namespace
(SAP standard tables), for which it is even impossible to perform any changes without a
corresponding modification key. However, there may be situations where there are good
reasons to at least extend an existing table by additional fields. This may be the case if a
customer wants to store an additional property of a business object, for example. The SAP
system offers append structures for this kind of problem, which offer the possibility to extend
tables (but also structures) of the Dictionary by additional fields. Such an append structure can
be used independent of the table being in the customer namespace or not. However, the
developer of the original Dictionary object can specify limitations on the extensibility of the
object. These are the enhancement categories, which were missing for the previously defined
Dictionary objects in the exercises, causing a warning message during activation.

Page 120
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 114: Append structures

An append structure can only be assigned to exactly one table. On the other hand, one table
may have multiple append structures. During activation, the additional fields of the append
are appended at the end of the table in the database system. Now it could happen that a new
version of the original Dictionary object contains a new field, which has the same name as a
field of an append. This would cause an error during activation. Hence, the names of fields in
appends should also be part of the customer namespace to make name conflicts impossible.
This is however not enforced by the SAP system.

Page 121
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 115: Appends and new SAP fields

If the SAP developer adds another field to the original Dictionary object, this is not a problem
for the database. On the database, this field is simply appended at the end of the table, after
the fields that came from the append. As you already know, the order of fields does not have
to be identical between the database and the Dictionary.

Nevertheless, enhancing tables by appends can still cause problems because of dependencies.
For example, the properties of a type might be changed due to an append. If an append
contains a reference typed field for example, a flat type can become a deep type. This could in
turn have an effect on a program which uses that type. It may be helpful to look at the where-
used-list before enhancing a Dictionary object. Furthermore, a suitable enhancement category
should be selected for each Dictionary object. This is done using the menu path Extras ->
Enhancement Category.

The following enhancement categories are available:

 Can be enhanced (deep): This enhancement category allows arbitrary append


structures.
 Can be enhanced (character-type or numeric): This enhancement category does
only allow character or numeric types, but no deep types.
 Can be enhanced (character-type): This enhancement category only allows
character-type components in the append structure.
 Cannot be enhanced: This category forbids using append structures for the object.

Page 122
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

 Not classified: This value means that the enhancement category has not been selected
yet.

8.12.7.2 Customizing Includes

Another way to enhance SAP tables is Customizing Includes. These are special structures
whose name starts with CI, but which are part of the customer namespace and are prepared by
SAP. They can be used in multiple tables, as opposed to append structures40.

Enhancing development objects of SAP will be covered in more detail in the advanced ABAP
course.

8.12.8 Exercise on appends

Go to the ABAP Dictionary and open your table ZZ####_CONV in changing mode. Choose
the menu path Goto -> Append Structure…

Figure 116: Creating an append structure: SAP-System-Screenshot

Commit the possible information message and enter ZAZZ####_CONV as the Append
Name. Choose a suitable short description and add a field named ZZNEW. The field shall be
typed using the built-in type INT4. Click on to make the corresponding
column editable.

Figure 117: Maintenance of the append structure: SAP-System-Screenshot

Save the append structure, check, and activate it. Then, go back to the table ZZ####_CONV.
The table is active and the field list contains a link to the append structure:

40
Gupta (2011, pp. 132 f.)
Page 123
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 118: Append structure in the field list: SAP-System-Screenshot

Using the -button, you can display the field of the append.

Leave the ABAP Dictionary.

Page 124
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.13 Performance of database requests


The access to the database can have a crucial role for the performance of an application. Most
probably you will not notice these effects in the programs which you create during this
course. The reason for this is that the examples are not too large in the course, and there are
not as many users as in a productive scenario accessing the program. However, generally you
should think about the performance of your applications, to make sure they do not require too
many resources in a production scenario.

When looking at the performance of database requests, there are different aspects to consider.
The behavior of the system as a whole depends on the load on the database server, on the
amount of data that is transferred between database and application server, and finally also the
load on the application server itself. In some cases, this is a trade-off, where no general rule
for optimal statements can be given. Some basic rules for efficient database access can be
given though.

The decision of how a specific access to a table is realized (e.g., whether an index is actually
used or a full table scan is executed) is part of the database system. There is a component
called optimizer, which creates an execution plan for each query. There may be differences in
the execution of identical queries on different database systems.

8.13.1 Only read data which you actually need

If you read records from the database, you should think in advance about the set of fields you
want to access If you need just one or two fields from a table, but use a SELECT * which
includes all fields of the table in the result, there is a huge amount of data which is transported
from the database to the application server even though it is not required. Furthermore, in
column-oriented databases like SAP HANA, the lines have to be reconstructed costly.

Example of bad code:

SELECT * FROM SPFLI INTO wa.

WRITE: / wa-carrid, wa-connid.

ENDSELECT.

Example of better code:

SELECT carrid connid FROM SPFLI INTO wa.

WRITE: / wa-carrid, wa-connid.

ENDSELECT.

Page 125
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Another example of useless data transfer is leaving out conditions in the WHERE part of the
query. In this case, it is not the number of columns which causes the problem. Instead, there
are too many rows of the table transferred to the application server.

Example of bad code:

SELECT carrid connid FROM SPFLI INTO wa.

IF wa-carrid = 'LH' OR wa-carrid = 'AA'.

WRITE: / wa-carrid, wa-connid.

ENDIF.

ENDSELECT.

Example of better code:

SELECT carrid connid fltime FROM SPFLI INTO wa WHERE carrid =


'LH' OR carrid = 'AA'.

WRITE: / wa-carrid, wa-connid.

ENDSELECT.

8.13.2 Use complete keys

For the access to database tables, primary keys or indexes should be used if possible. This
makes the search for the records faster, as explained before. However, this only works if the
specified key does not contain any wholes. If there is a key consisting of the three fields f1,
f2, and f3, the field f2 should not be left out if it is known.

Example of bad code:

SELECT * FROM sflight INTO wa WHERE connid = '0401'.

...

Example of better code:

SELECT * FROM sflight INTO wa WHERE carrid = 'LH' AND connid =


'0401'.

...

Note that the client field is automatically supplied (but do not use CLIENT SPECIFIED
without specifying the client field!)

Page 126
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.13.3 Replace repeated similar queries by a single query

If you want to read multiple records from the database, it is not efficient to do this using
multiple, nearly identical SELECT statements, because each SELECT requires an individual
database access.

Example of bad code:

SELECT SINGLE * FROM SPFLI INTO ... WHERE CARRID='LH' AND


CONNID='0400'.

...

SELECT SINGLE * FROM SPFLI INTO ... WHERE CARRID='LH' AND


CONNID='0401'.

...

SELECT SINGLE * FROM SPFLI INTO ... WHERE CARRID='LH' AND


CONNID='0402'.

Example of better code:

SELECT * FROM SPFLI INTO ... WHERE CARRID='LH'.

...

ENDSELECT.

Furthermore, it could be helpful to buffer the data in an internal table using INTO TABLE in
this example.

8.13.4 Use joins instead of nested SELECTs

If you need data that is stored across multiple, dependent tables, you should connect the tables
on the database level using a suitable join.

Example of bad code:

SELECT field1 FROM table1 INTO wa.

SELECT field2 FROM table2 INTO wa2 WHERE wa1-field1=...

...

ENDSELECT.

ENDSELECT.

Example of better code:

SELECT feld1, feld2 FROM tabelle1 INNER JOIN tabelle2 ON ...


Page 127
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

...

ENDSELECT.

This way a huge number of individual requests can be prevented.

8.13.5 Trade-off

In some cases, there is a trade-off between load on the application server and load on the
database server.

8.13.5.1 Example: Sorting

Version 1:

SELECT * FROM ... INTO TABLE itab ORDER BY feld1.

Version 2:

SELECT * FROM ... INTO TABLE itab.

SORT itab ...

In the first version, the load of calculation the sorting is executed on the database, while the
second version does this task on the application server.

8.13.5.2 Example: Calculation of aggregate functions

Version 1:

SELECT feld1 SUM( feld2 ) INTO TABLE itab FROM ... GROUP BY
feld1.

Version 2:

SELECT feld1 feld2 INTO TABLE itab FROM ...

LOOP AT itab INTO wa.

...

ENDLOOP.

In the first version, the sum is calculated using an aggregate function of the database. For the
second version, more data has to be transferred, but the calculation of the sum is done on the
application server. In cases like this, there is a trade-off between the advantages and
disadvantages depending on the actual scenario.

Page 128
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

8.14 Chapter submission


You are now at the end of this part of the course. Please consider the following things before
you send the e-mail described below:

1. Make sure you did all exercises, including those that are not part of a chapter
explicitly named “exercise.”

2. Make sure all your repository objects are working correctly

3. Make sure all your repository objects are activated. To find objects which are
not yet activated, select Inactive Objects from the drop down menu above the
navigation tree in the Object Navigator. Enter your user name USER#-### into
the field below and commit. After that, the inactive objects are displayed in the
navigation tree. Activate them now. Please note that you may have to expand
the branches of the navigation trees completely. To get back to your package
afterwards, select Package from the drop down menu and commit your
package name by clicking on the Display button.

4. Make sure the names of your repository objects are exactly the same as
described in this document. If you mistyped a program name, right-click on it
in the navigation tree of the Object Navigator and select Rename… from the
menu.

These notes are also relevant for all following chapters.

You are now at the end of this part of the course. Before you send the e-mail described
below, make sure that all your repository objects are working correctly and are
activated. You can see that an object is inactive by its blue color in the navigation tree
and the corresponding notice next to the program name in the ABAP Editor. Also make
sure that the names of your repository objects are exactly the same as described in this
document. Make sure that you did all exercises, including those that are not part of a
chapter named “exercise.” These notes are also relevant for all following chapters.

If you completed the course so far, send an e-mail to your tutor using the subject
“ABAP: Finished Chapter 8 User ####” (The quotes are not part of the subject). You
will then receive feedback: Either in the progress report if everything was correct, or by e-
mail if you have to correct something. Make sure that you enter the subject exactly as
described above to ensure an efficient processing of your e-mail.

If you have any questions, please use a separate e-mail, because the e-mails used for finished
chapters are usually only processed based on their subjects, and no content is read.

Page 129
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami

Das könnte Ihnen auch gefallen