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

Introduction to ABAP

- First Steps with ABAP-

Prof. Dr. Heimo H. Adelsberger


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

Table of contents
Table of contents ........................................................................................................................ 2
Table of figures .......................................................................................................................... 5
Table of tables ............................................................................................................................ 8
Copyright .................................................................................................................................... 9
4 Further structure of the course ......................................................................................... 10
5 First steps with ABAP ...................................................................................................... 11
5.1 Development within the SAP system ........................................................................ 11
5.2 System logon ............................................................................................................. 11
5.3 First steps with the Object Navigator ........................................................................ 11
5.3.1 Creation of package and workbench request ...................................................... 11
5.3.2 Packages, requests and the transport system ...................................................... 13
5.3.3 Creating your first program ................................................................................ 14
5.3.4 Definition: Developer Key ................................................................................. 15
5.3.5 Definition: Modification Key ............................................................................. 15
5.3.6 Writing your first ABAP statement .................................................................... 16
5.3.7 Using the Pretty Printer ...................................................................................... 17
5.3.8 Activation of the Program .................................................................................. 19
5.3.9 Program execution.............................................................................................. 20
5.4 First steps with the transport system.......................................................................... 21
5.4.1 Release of your Task .......................................................................................... 21
5.4.2 Release of your request ...................................................................................... 22
5.5 Note: Free testing....................................................................................................... 23
6 Tools of the development environment ............................................................................ 24
6.1 Structure of the development environment ............................................................... 24
6.1.1 ABAP Editor ...................................................................................................... 24
6.1.2 Screen Painter ..................................................................................................... 25
6.1.3 Menu Painter ...................................................................................................... 26
6.1.4 Function Builder ................................................................................................. 27
6.1.5 Class Builder ...................................................................................................... 28
6.1.6 Debugger ............................................................................................................ 28
6.1.7 Object Navigator ................................................................................................ 29
6.1.8 Repository Infosystem ........................................................................................ 29
6.2 Exercise: The development environment .................................................................. 29
6.2.1 Display mode vs. change mode .......................................................................... 29
6.2.2 The ABAP keyword documentation .................................................................. 30
6.2.3 The pattern button .............................................................................................. 31
6.2.4 Version Management (Part 1) ............................................................................ 34
6.2.5 Using the debugger ............................................................................................. 35
6.2.5.1 Old vs. new debugger ................................................................................. 36
6.2.5.1 Control of execution ................................................................................... 37
6.2.5.2 Watchpoints ................................................................................................ 39
6.2.5.3 Breakpoints ................................................................................................. 40
6.2.5.4 Important hint for debugging ...................................................................... 41
6.2.6 Version Management (Part 2) ............................................................................ 41
7 Basic concepts of ABAP .................................................................................................. 44
7.1 Data types .................................................................................................................. 44
7.1.1 Built-in standard types ....................................................................................... 45
7.1.1.1 Character string (type C) ............................................................................. 46
Page 2
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

7.1.1.2 Numerical string (type N) ........................................................................... 46


7.1.1.3 Time (type T) .............................................................................................. 46
7.1.1.4 Example for formatted output of time ........................................................ 46
7.1.1.5 Date (type D) ............................................................................................... 47
7.1.1.6 Example for date formatting ....................................................................... 47
7.1.1.7 Floating point number (types F, DECFLOAT16, and DECFLOAT34) ..... 47
7.1.1.8 Integer (type I) ............................................................................................ 48
7.1.1.9 Packed number (type P) .............................................................................. 48
7.1.1.10 Hexadecimal string (type X) ....................................................................... 48
7.1.1.11 Character strings with dynamic length (type STRING) ............................. 48
7.1.1.12 Hexadecimal string with dynamic length (type XSTRING) ....................... 48
7.1.2 Completeness ..................................................................................................... 49
7.1.3 Defining simple data objects .............................................................................. 49
7.1.4 Examples for simple data object definitions ...................................................... 49
7.1.5 Basics of data manipulation ............................................................................... 49
7.1.6 User-defined simple data types .......................................................................... 50
7.1.7 Statement chains ................................................................................................. 50
7.1.8 Complex data objects ......................................................................................... 51
7.1.8.1 Structures and structure types ..................................................................... 52
7.1.8.2 Reusing structures to define other structures .............................................. 53
7.1.8.3 Flat and deep structures .............................................................................. 54
7.1.8.4 Exercise: Structures and structure types ..................................................... 54
7.1.8.5 Internal tables and table types ..................................................................... 57
7.1.8.6 Example: local table types .......................................................................... 59
7.1.8.7 Operations on internal tables....................................................................... 60
7.1.8.8 Accessing single lines ................................................................................. 60
7.1.8.9 Excursus: The sy-subrc ............................................................................... 64
7.1.8.10 Accessing multiple lines ............................................................................. 66
7.1.8.11 Condensed insertion .................................................................................... 67
7.1.8.12 Sorting internal tables ................................................................................. 70
7.1.8.13 Initialization of internal tables and other data objects ................................ 71
7.1.8.14 Internal tables with header line ................................................................... 72
7.2 Exercise on internal tables and table types ................................................................ 74
7.3 Excursus: Old vs. new Editor .................................................................................... 76
7.4 Constants ................................................................................................................... 79
7.5 Text symbols.............................................................................................................. 79
7.6 Parameters ................................................................................................................. 80
7.7 Comments .................................................................................................................. 81
7.8 The system structure sy / syst .................................................................................... 82
7.9 Operators ................................................................................................................... 83
7.9.1 Arithmetic operators ........................................................................................... 83
7.9.1.1 Integer arithmetic ........................................................................................ 84
7.9.1.2 Floating point arithmetic ............................................................................. 84
7.9.1.3 Fixed-point arithmetic ................................................................................. 84
7.9.2 Operations on character strings .......................................................................... 84
7.9.2.1 Concatenation ............................................................................................. 84
7.9.2.2 Searching..................................................................................................... 85
7.9.2.3 Replacing characters ................................................................................... 86
7.9.2.4 Split character strings .................................................................................. 87
7.9.2.5 Condensing character strings ...................................................................... 88
7.9.2.6 Translate character strings .......................................................................... 88
Page 3
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

7.9.3 Operators for comparison ................................................................................... 88


7.9.3.1 Comparison of arbitrary data types ............................................................. 88
7.9.3.2 Comparison operators for character types .................................................. 89
7.10 Control structures ................................................................................................... 90
7.10.1 Unconditional loops ........................................................................................... 90
7.10.2 Conditional loops ............................................................................................... 90
7.10.3 Loop for internal tables ...................................................................................... 91
7.10.4 Loops for database tables ................................................................................... 91
7.10.5 Leaving loops ..................................................................................................... 91
7.10.5.1 The EXIT statement .................................................................................... 91
7.10.5.2 The CONTINUE statement......................................................................... 91
7.10.5.3 The CHECK statement ............................................................................... 91
7.10.6 Conditional branches .......................................................................................... 92
7.10.6.1 The IF construct .......................................................................................... 92
7.10.6.2 The CASE construct ................................................................................... 92
7.11 Modularization in ABAP ....................................................................................... 94
7.11.1 Include files ........................................................................................................ 94
7.11.1.1 Example include.......................................................................................... 95
7.11.2 Subroutines (form routines) ............................................................................... 98
7.11.2.1 Call by reference ......................................................................................... 98
7.11.2.2 Call by value ............................................................................................... 99
7.11.2.3 Typing ......................................................................................................... 99
7.11.2.4 Propagating exceptions ............................................................................... 99
7.11.2.5 Calling subroutines (form routines) ............................................................ 99
7.11.2.6 Visibility ................................................................................................... 100
7.11.2.7 Subroutine example .................................................................................. 100
7.11.3 Function modules ............................................................................................. 102
7.11.3.1 Function module interfaces ....................................................................... 103
7.11.3.2 Calling function modules .......................................................................... 104
7.11.3.3 Static parameter passing ........................................................................... 104
7.11.3.4 Dynamic parameter passing ...................................................................... 105
7.12 Exercise on basic concepts................................................................................... 105
7.12.1 The favorites menu ........................................................................................... 105
7.12.2 Selection screens and control structures ........................................................... 107
7.12.3 Implementing a function module ..................................................................... 109
7.12.4 Exception handling ........................................................................................... 114
7.13 Repository and Repository Infosystem ................................................................ 116
7.13.1 SAP Application hierarchy............................................................................... 117
7.13.2 The Repository Information System ................................................................ 118
7.13.3 Program specific search ................................................................................... 120
7.14 Chapter submission .............................................................................................. 121

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

Table of figures
Figure 1: Entering the package name: SAP-System-Screenshot ............................................. 12
Figure 2: Creating the package: SAP-System-Screenshot ....................................................... 12
Figure 3: Selection of workbench request: SAP-System-Screenshot ...................................... 13
Figure 4: Create program: SAP-System-Screenshot ................................................................ 14
Figure 5: Properties of the program: SAP-System-Screenshot ................................................ 16
Figure 6: First source code: SAP-System-Screenshot.............................................................. 17
Figure 7: Configuring the Pretty Printer: SAP-System-Screenshot ......................................... 18
Figure 8: Inactive Program: SAP-System-Screenshot ............................................................. 19
Figure 9: Inactive Program in the navigation tree: SAP-System-Screenshot .......................... 19
Figure 10: Active Program in the navigation tree: SAP-System-Screenshot........................... 19
Figure 11: Program output: SAP-System-Screenshot .............................................................. 20
Figure 12: Transport Organizer: SAP-System-Screenshot ...................................................... 21
Figure 13: Initial screen of the ABAP Editor: SAP-System-Screenshot ................................. 25
Figure 14: Initial screen of the screen painter: SAP-System-Screenshot ................................. 26
Figure 15: Initial screen of the Menu Painter: SAP-System-Screenshot ................................. 27
Figure 16: Initial screen of the Function Builders: SAP-System-Screenshot .......................... 28
Figure 17: The Object Navigator: SAP-System-Screenshot .................................................... 29
Figure 18: Keyword documentation of NEW-LINE: SAP-System-Screenshot ...................... 30
Figure 19: Insertion of patterns: SAP-System-Screenshot ....................................................... 31
Figure 20: WRITE patterns: SAP-System-Screenshot............................................................. 32
Figure 21: Error message: SAP-System-Screenshot ................................................................ 32
Figure 22: Changed code: SAP-System-Screenshot ................................................................ 33
Figure 23: Output of the symbol: SAP-System-Screenshot ..................................................... 33
Figure 24: Version Management: SAP-System-Screenshot .................................................... 34
Figure 25: Your version in the version database: SAP-System-Screenshot ............................ 35
Figure 26: Some lines of code: SAP-System-Screenshot ........................................................ 36
Figure 27: The new Debugger: SAP-System-Screenshot ........................................................ 37
Figure 28: Navigation icons of the debugger: SAP-System-Screenshot .................................. 37
Figure 29: Observing variables in the debugger: SAP-System-Screenshot ............................. 38
Figure 30: A zero division exception has occurred: SAP-System-Screenshot ........................ 38
Figure 31: Icon to create Watchpoints: SAP-System-Screenshot ............................................ 39
Figure 32: Creating a watchpoint: SAP-System-Screenshot .................................................... 39
Figure 33: The watchpoint has been reached: SAP-System-Screenshot .................................. 40
Figure 34: Watchpoint list: SAP-System-Screenshot .............................................................. 40
Figure 35: Dynamic breakpoint in the editor: SAP-System-Screenshot .................................. 41
Figure 36: Dynamic breakpoint in the debugger: SAP-System-Screenshot ............................ 41
Figure 37: Versions of your program: SAP-System-Screenshot ............................................. 42
Figure 38: Basic Structure of ABAP Types ............................................................................. 45
Figure 39: The structure type str_car ....................................................................................... 52
Figure 40: Possible output of your program: SAP-System-Screenshot ................................... 56
Figure 41: Single components in the debugger: SAP-System-Screenshot .............................. 56
Figure 42: Structure in the variable list: SAP-System-Screenshot .......................................... 56
Figure 43: Detailed view of the structure: SAP-System-Screenshot ....................................... 57
Figure 44: Kinds of tables ........................................................................................................ 58
Figure 45: Accessing lines of internal tables............................................................................ 60
Figure 46: Error message (INTO instead of INTO TABLE): SAP-System-Screenshot .......... 62
Figure 47: Internal table vs. database table .............................................................................. 62
Figure 48: Processing multiple lines of internal tables ............................................................ 66
Page 5
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 49: Condensed insertion of lines ................................................................................... 68


Figure 50: Kilometer output: SAP-System-Screenshot ........................................................... 69
Figure 51: The internal table in the debugger: SAP-System-Screenshot ................................. 70
Figure 52: Empty table: SAP-System-Screenshot ................................................................... 70
Figure 53: Header line vs. work area ....................................................................................... 72
Figure 54: The three variables in the debugger: SAP-System-Screenshot .............................. 73
Figure 55: Header line in the debugger: SAP-System-Screenshot........................................... 74
Figure 56: Output of a program using internal tables: SAP-System-Screenshot ..................... 75
Figure 57: Table view in the debugger: SAP-System-Screenshot ........................................... 75
Figure 58: Multiple desktops in the new debugger: SAP-System-Screenshot ......................... 75
Figure 59: Editor choice: SAP-System-Screenshot ................................................................. 77
Figure 60: Example code in the old editor: SAP-System-Screenshot ...................................... 78
Figure 61: Simple auto completion: SAP-System-Screenshot ................................................. 79
Figure 62: Completed keyword WHILE: SAP-System-Screenshot ........................................ 79
Figure 63: Generated while loop structure: SAP-System-Screenshot ..................................... 79
Figure 64: Automatically generated selection screen: SAP-System-Screenshot ..................... 81
Figure 65: Floating point arithmetic......................................................................................... 84
Figure 66: Creating a program: SAP-System-Screenshot ........................................................ 95
Figure 67: Input of net value: SAP-System-Screenshot........................................................... 95
Figure 68: Output of the VAT program: SAP-System-Screenshot .......................................... 96
Figure 69: Solution example: SAP-System-Screenshot ........................................................... 96
Figure 70: Notice about INCLUDE statement: SAP-System-Screenshot ............................... 96
Figure 71: Inactive objects: SAP-System-Screenshot .............................................................. 97
Figure 72: Include statement: SAP-System-Screenshot........................................................... 97
Figure 73: Copying a program: SAP-System-Screenshot ...................................................... 100
Figure 74: Output of the program: SAP-System-Screenshot ................................................. 101
Figure 75: Subroutine in the navigation tree: SAP-System-Screenshot ................................ 101
Figure 76: Subroutine call pattern: SAP-System-Screenshot................................................. 102
Figure 77: Depiction of a function group ............................................................................... 103
Figure 78: Selecting your package: SAP-System-Screenshot ................................................ 106
Figure 79: Adding a favorite: SAP-System-Screenshot ......................................................... 106
Figure 80: Commitment: SAP-System-Screenshot ................................................................ 106
Figure 81: The favorites menu: SAP-System-Screenshot ...................................................... 106
Figure 82: Editing favorites: SAP-System-Screenshot .......................................................... 107
Figure 83: Entering selection texts: SAP-System-Screenshot ............................................... 108
Figure 84:User interface of the program: SAP-System-Screenshot ....................................... 109
Figure 85: Output of the result: SAP-System-Screenshot ...................................................... 109
Figure 86: Parameters of the function module: SAP-System-Screenshot .............................. 110
Figure 87: Predefined comments: SAP-System-Screenshot .................................................. 110
Figure 88: Automatically generated mask for testing: SAP-System-Screenshot ................... 111
Figure 89: Result of the function module test: SAP-System-Screenshot ............................... 111
Figure 90: Viewing the function module documentation: SAP-System-Screenshot ............. 113
Figure 91: Short dump caused by zero division: SAP-System-Screenshot ........................... 114
Figure 92: Definition of exceptions: SAP-System-Screenshot .............................................. 114
Figure 93: Another runtime error: SAP-System-Screenshot .................................................. 115
Figure 94: Assignment of exceptions and numbers: SAP-System-Screenshot ...................... 115
Figure 95: Example error message: SAP-System-Screenshot ............................................... 116
Figure 96: Highlighted part of the application hierarchy: SAP-System-Screenshot ............. 118
Figure 97: Displaying the transaction code: SAP-System-Screenshot .................................. 118
Figure 98: Program search mask: SAP-System-Screenshot .................................................. 119
Figure 99: Example search result: SAP-System-Screenshot .................................................. 119
Page 6
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

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

Table of tables
Table 1: Control functions of the debugger ............................................................................. 38
Table 2: Predefined data types in ABAP ................................................................................. 46
Table 3: Components of the sy structure .................................................................................. 82
Table 4: Arithmetic operations in ABAP ................................................................................. 83

Page 8
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 9
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

4 Further structure of the course


After you have been provided with the most important information, the course will now focus
ABAP programming itself.

The further structure of the course is as follows: First, the basic concepts of ABAP and the
process of developing software within SAP ERP are taught. Other content comprises the
powerful type concept of ABAP and the modularization of programs. Later, working with the
Data Dictionary and databases, and different ways to create graphical user interfaces are
focused. These contents are conjoined with background information about the underlying
technologies.
The different aspects of programming with ABAP will be taught using several examples
(small exercises), in which you will be programming within the SAP system. Later, you will
have to apply the learned knowledge in more complex tasks in the case study chapter. The
level of detail of the instructions will decrease, so the case study chapter will not contain a
step-by-step-guide.
The final chapter of the course is a small outlook on ABAP Objects, which is the object-
oriented programming extension of ABAP.

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

5 First steps with ABAP


At the beginning, we do not want to bore you with theoretical explanations of the language
ABAP. Instead, you will immediately get in touch with practical programming using the SAP
system. You will get to know the development environment and its basic functions; especially
the organization of development objects using packages and the transport system.

5.1 Development within the SAP system


Some general facts are important to know before programming in ABAP. ABAP programs
are written within the SAP system. This means that you will not create any code in a locally
installed development environment as you are used to from other programming languages,
like in Eclipse, Visual Studio, etc. The development environment for ABAP is itself part of
the SAP ERP system. Usually, ABAP programs are written in large development teams,
whose users are working with the same SAP ERP system. Hence, special concepts for the
organization of the development objects have been created. They may seem a bit bulky for the
creation of small programs like in our course, but in large projects, they proved their
effectiveness.

5.2 System logon


To start with the development, open your SAP GUI and log on to the system in the
development client (cf. How-to-start document) using your user name "USER##-##" and the
corresponding initial password. The four # symbols represent your individual participant
number. Enter this number in all places that are indicated by #### in the course documents.
The number always has four digits. The hyphen (minus) is not part of the number.

Example: Your user name is USER12-34. Then your number is 1234.

Change your password after logging in. You can also do this at any later time using the menu
path System -> User Profile -> Own Data -> Password.

5.3 First steps with the Object Navigator


The Object Navigator is the most important transaction for development tasks in the SAP
system. It integrates several development tools that are necessary to create ABAP programs.
These tools will be presented in more detail later. At this stage, you will first get a practical
impression.

Open the ABAP development environment using the menu path Tools -> ABAP Workbench
-> Overview -> Object Navigator or directly enter the transaction code SE80.

5.3.1 Creation of package and workbench request

From the Object Navigator, choose the object type Package if it is not already selected, and
enter the name of the new package in the text field below. The name should be ZZ_####.
(Please be careful that you use your user number as explained in chapter 5.1. Do not use a
different number! Do not copy the number from the screenshots!
Page 11
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 1: Entering the package name: SAP-System-Screenshot

Confirm the package name using Enter. The system will ask you if you want to create a new
package. Confirm this question with yes. In the following window, enter “Package of John
Doe,” replacing John Doe by your own first and last name in the field short description.
Leave the other fields unchanged and save the settings (press Enter).

Figure 2: Creating the package: SAP-System-Screenshot

When you save, you will be asked for a transportable workbench request. As you did not
create one yet, you have to do this now. Simply click on the icon Create Request or press
F8 and enter a short description of the request. Save to return to the previous window. Your
short description and an automatically generated number of the request should be displayed.

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

Figure 3: Selection of workbench request: SAP-System-Screenshot

Confirm your input with the -icon or the Enter key. You have now created a package
ZZ_#### and saved the creation in a workbench request.

5.3.2 Packages, requests and the transport system

A package is used to group logically associated development objects. A package is an


enhancement of the previous concept of development classes.

The properties of the package determine, among others, whether objects of the current system
can be transported into other systems or not (based on the Transport Layer). Furthermore,
there are three types of packages:

- Normal packages (containing repository objects and other packages)


- Main packages (containing only other packages)
- Structure packages (containing only main packages)

Based on the selection of an application component, the package becomes part of the
application hierarchy. The software component should be HOME for customer
developments.

A change request is a logical unit, which comprises all tasks for a self-contained
development task. In a usual project, the project leader will create a change request and,
moreover, tasks for all employees working within the project are created for the request. All
repository objects changed by an employee during a development project are collected in his
task. In our course, you will create both.

The transport system is used to transfer developments from one system to another (typically
from a development system to a test system and then to the live system). Furthermore, the
transport system is used to log changes, but also to lock objects to ensure that they cannot be
accessed by other developers (to avoid conflicts). As opposed to simple database locks, which
are only able to lock objects being changed until they have been saved, the transport system
enables locking for a longer period of time, covering the whole development process.

Using the transport system, each employee can track his project-specific activities. Repository
objects are available to all project employees, but they are locked for other developers. On
completion of the project, all relevant development objects are transported as they are all part
of the change request.

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

5.3.3 Creating your first program

To create your first program, right click on the package in the object list (navigation tree) on
the left side of the screen. From the context menu, select Create -> Program. Enter the name
ZZ_####_HELLOWORLD for your program and make sure that the checkbox With TOP
INCL is not enabled. Otherwise, your program would be distributed into different parts,
which is not useful here (It will be used later for applications with screens).

Figure 4: Create program: SAP-System-Screenshot

After the confirmation, the system will ask you for a developer key, as you want to start
developing programs. Enter the development key that you have received from your course
administrator.

Figure 5: Access Key: SAP-System-Screenshot

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

5.3.4 Definition: Developer Key

A Developer Key is a numerical code, which is needed to activate a certain SAP user on an
SAP system as a developer. Only with a developer key, the user is able to create development
objects (programs) and to change existing programs.

Each key has to be ordered from SAP individually per user. Ordering the key from SAP is
necessary because the license fees for development users are higher than those for regular
SAP users.

Important note: You have to enter your developer key only once. If you are asked for a key
for a second time during the course, it is most likely a modification key. This question appears
if you accidentally try to create development objects outside the customer namespace, i.e.,
create a program which does not start with X, Y or Z. In this case, control your program
name.

5.3.5 Definition: Modification Key

A modification key is a key that has to be entered to be able to create or change development
objects outside the customer namespace.

SAPs own development objects are those which do not start with X, Y or Z. The modification
key has to be ordered from SAP. The key is only valid for the corresponding object. This
means that one user may have to enter modification keys multiple times, as opposed to the
developer key that has to be entered just once.

However, it should be noted that modified objects are not supported by the usual support
contracts anymore. Furthermore, problems might occur if SAP provides an update of the same
development object later. Because of that, modifications should be avoided if possible. To
make it possible to change the SAP software without the need for a modification, several
techniques such as BAdIs, enhancements, or user exits are available. The modification of SAP
programs is not covered in this course, but it is an important topic of the advanced course.

A new screen appears, which asks you for some properties of your new program. Choose the
status Test Program and save your input by clicking on the corresponding button.

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

Figure 5: Properties of the program: SAP-System-Screenshot

On the next screen, the system will ask for a package. You have created your package already,
so you can use it now. You will only create programs in your package ZZ_#### throughout
the whole course. Hence, enter this package if it is not already selected by the system and
save.

The system asks for a request again in a new window. To show you how to use the transport
system later, you will use a separate request for the creation of this program. This request will
be released later. Hence, use the button Create Request to create another request here.
Choose a suitable short description and save all your input.

5.3.6 Writing your first ABAP statement

You will now see the ABAP editor, which is used to create the program source code. Some
lines are already visible. Most of these lines are only default comments, which you can see by
the stars at the beginning of the lines that indicate a comment.

Your first program shall be a classical “Hello World” example. Add another line with the
following code below the existing lines:

write 'Hello World'.

Note the dot at the end of the line. This dot is necessary at the end of an ABAP statement.
Your program should now look like this:
Page 16
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 6: First source code: SAP-System-Screenshot

5.3.7 Using the Pretty Printer

In the main menu, open the path Utilities(M) -> Settings… In the appearing window, go to
the tab ABAP Editor -> Pretty Printer. It is common to write keywords in uppercase letters.
Furthermore, we recommend using indentation, even though this is not really relevant for this
simple program. Hence, select Indent and Keyword Uppercase from Convert
Uppercase/Lowercase. (cf. screen shot in the following figure)

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

Figure 7: Configuring the Pretty Printer: SAP-System-Screenshot

Accept the settings and go back to the Object Navigator. Click on the button Pretty Printer
on the top left side. The key words REPORT and WRITE should be written in uppercase letters
now.

Save your newly created program using the menu path Program -> Save or using the symbol
.

The syntax check has to be called explicitly. This can be done using the menu path Program -
> Check -> Syntax or by clicking the icon Check below. There should not be any syntax
errors. Otherwise, make sure you typed the line correctly as shown above.

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

5.3.8 Activation of the Program

To make sure the new program can be found and called, it should to be activated now. Use the
menu path Program -> Activate or the icon Activate . During activation, the system
automatically checks the syntax and informs about syntax errors. You should get used to
removing all errors before activation.

The activation is not strictly necessary to test the hello world program here, but you should
get used to this step, because you may run into problems in more complex exercises
otherwise, when multiple development objects interact with each other. It is also very
important to activate all development objects before you let your tutor check your code or,
otherwise, your solutions will be rejected. An activation is required after every change of your
code (each time you save). There are two indicators to see that a program is not yet activated.
Firstly, there is the word Inactive next to the program name field above your source code:

Figure 8: Inactive Program: SAP-System-Screenshot

Secondly, inactive objects are displayed in blue color in the navigation tree of the object
navigator:

Figure 9: Inactive Program in the navigation tree: SAP-System-Screenshot

Figure 10: Active Program in the navigation tree: SAP-System-Screenshot

Before activation, an active and an inactive version of your program exist in the system.
Activation makes the editing version become the new active version. The release of a request
and transport to another system is only possible if all objects in the request have been
activated. You can switch between both versions using the -button.
If multiple inactive objects exist, you may see a list of them (your worklist), and are able to
choose which of them should be activated (during this course, usually all objects should be
the ones you want to activate). During activation of a program, a runtime object is generated
for later executions of the active program.

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

5.3.9 Program execution

The program can be tested now. For this purpose, choose the menu path Program -> Execute
-> Direct Processing, or use the button Direct Processing , or press F8. After a short
compilation, you should get some output similar to the following figure:

Figure 11: Program output: SAP-System-Screenshot

By using the button Back ( ) or pressing F3, you get back to the development environment.

In case of an active and an inactive version of a program, it is possible to execute both. If you
start the program from the context menu from the navigation tree of the object navigator or
from a transaction, the active version is used. If you start it as described above, a temporary
runtime object is generated and executed. Therefore, it is possible to test changes before they
become effective in the whole system. To make clear which version is the correct one in your
exercises, make sure you activate all development objects during this course.

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

5.4 First steps with the transport system


Create a new session (using System -> Create Session or ) and open the Transport
Organizer using the path Tools -> ABAP Workbench -> Overview -> Transport
Organizer or by entering the transaction code SE09. Note that the Transport Organizer may
be called Workbench Organizer at some places due to some inconsistent naming in the
System.

5.4.1 Release of your Task

Your user name should already be standing in the User field. Otherwise, enter it there. In the
Request Type area, select the option Workbench Requests. Make sure both options are
marked in the area Request Status. This way you can avoid confusion if you miss one of
your requests later, because you will release it in this exercise. Commit your input by clicking
on Display or simply using the Enter key.

Figure 12: Transport Organizer: SAP-System-Screenshot

A navigation tree should appear, which is structured by the client, the request, and the task. In
the tree, you should find two modifiable requests. Remember, you used one request for the
creation of the package ZZ_#### and another for the creation of the program
ZZ_####_HELLOWORLD. Open the request that belongs to the program creation by
clicking on the corresponding -icon. If you are unsure which request is the correct one, you
Page 21
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

can expand both trees using the plus icons. Only one of them will contain your program.
Furthermore, you can see the description you entered during its creation. Here you can see
that useful descriptions are valuable. Below the request, you will see a task for your user, and
below the task there is a node with your program.

Figure 13: Transport Organizer: SAP-System-Screenshot

Select your task that belongs to the program creation by clicking on its number, which starts
with the system number (e.g., “S06…” in the screenshot – in your case, the system number
may be different. However, it is the number directly above the “Program” node). Then, select
the menu path Request/Task -> Release -> Directly or click on the -icon. You will see a
message that the task has been released.

5.4.2 Release of your request

Now, select your request, i.e., click on the element above in the tree (on the number, just as
before). Release the request as you did it with the task before. The release may take some
time. Refresh the display using the menu path Edit -> Refresh or using the -icon
repeatedly, until the release is finished, i. e., there is no red highlighting anymore. Then go
back to the Transport Organizer using the Back icon. Now, your request is not listed as
modifiable anymore. Instead, you find it in the Released sub tree.

In our course, we are working with a single system. Therefore, the request leads to a dummy
system. In a more realistic scenario, the release of the request would have led to the transport
of your development objects from the development system to, for example, a test system or a
production system.

Usually, the request is created by a project leader, who defines the employees working on the
project. The Transport Organizer creates a task in the request for each of them.

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

The request is a temporal boundary, as opposed to the package, which represents a permanent
topical boundary (programs belong to a defined package). A program can be part of different
development projects during time.

Close the session with the Transport Organizer. In the other session, leave the Object
Navigator and go back to the Easy Access Menu.

5.5 Note: Free testing


During further progress of the course, you will see many syntactical elements of ABAP. If
you want to try them beyond the exercises of the course, you can modify your
HELLOWORLD program (it is not needed for later parts of the course). You can also create
other programs, but you must stay in your package, and you must keep the naming
convention: All your programs have to begin with ZZ_####_.

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

6 Tools of the development environment


In this chapter, the different tools are presented of which the ABAP development environment
consists. Some wording may seem a bit confusing at the beginning, because ABAP has a
different structure and different names for some concepts than other languages. Due to that,
there are some short explanations on new terms. You will use all the concepts in practical
exercises during the further progress of the course and you can re-read the chapter in case of
doubt. In the exercises, you will use the development environment for your active
programming.

6.1 Structure of the development environment


The development environment basically consists of the following tools:

 ABAP Editor
 Screen Painter
 Menu Painter
 Function Builder
 Class Builder
 Debugger
 Object Navigator
 Repository Infosystem

These tools are presented briefly in the following sub chapters.

6.1.1 ABAP Editor

You have already used the ABAP-Editor to create your first program, the HELLOWORLD
example. It is – like all other tools of the development environment – integrated into the
Object Navigator. Usually, it is called from the Object Navigator, because if it is started
directly, it does not offer any functionality for the transport, hence, it can only be used for
editing ABAP source code. However, direct access is possible using the path Tools -> ABAP
Workbench -> Development -> ABAP Editor or the transaction code SE38. However, we
recommend starting it from the Object Navigator, as this is more convenient.

The Petty Printer in the ABAP Editor is used to format your code in a normalized way. This
includes automatic casing of code elements. Furthermore, certain code elements are put into
separate lines and indentation and new lines are added. You have used the Pretty Printer
already in the exercise above. We recommend using the Pretty Printer on a regular basis.

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

Figure 13: Initial screen of the ABAP Editor: SAP-System-Screenshot

6.1.2 Screen Painter

The Screen Painter is the tool of the ABAP Workbench for the creation of Screens and their
maintenance. Screens are graphical user interfaces used within programs. The Screen Painter
contains a text editor for the creation of the logic behind the screen and a layout editor to
create the visible content of the screen. You can find the screen painter in the easy access
menu under Tools -> ABAP Workbench -> Development -> User Interface -> Screen
Painter or behind the transaction code SE51.

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

Figure 14: Initial screen of the screen painter: SAP-System-Screenshot

Definition: Screen
A Screen is a component of an executable program, a function pool, or a module pool. A
screen consists of a layout of visible elements and logic to control its behavior. It is created
using the Screen Painter.

6.1.3 Menu Painter

Analogously to the Screen Painter, the Menu Painter is the tool for the creation and
maintenance of the GUI Status of an ABAP program. The GUI Status comprises the Menu
bar, the application toolbar and the function keys. The transaction code for the Menu Painter
is SE41.

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

Figure 15: Initial screen of the Menu Painter: SAP-System-Screenshot

6.1.4 Function Builder

The task of the Function Builder is the creation and maintenance of function modules, which
are parts of function groups themselves. For the testing of function modules, the Function
Builder is able to generate input and output screens dynamically, which can be used for
parameter I/O. The Function Builder is located at Tools -> ABAP Workbench ->
Development -> Function Builder and behind the function code SE37.

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

Figure 16: Initial screen of the Function Builders: SAP-System-Screenshot

Definition: Function Module


A Function Module is a procedure, which can only be defined within Function Groups and
outside classes. Function Modules can be called from arbitrary programs. Each Function
Module begins with FUNCTION and ends with ENDFUNCTION.
Function Modules provide general and application independent functions to the developer.

Definition: Function Group


A Function Group is an ABAP program, which can contain Function Modules, and it is
usually loaded by using one of its Function Modules.
Function Groups are used to assemble multiple logically similar Function Modules.
Sometimes they are called "Function Pools."

6.1.5 Class Builder

The Class Builder is used to define global classes. This tool for object-oriented programming
will not be presented during this course. It will be covered in the advanced ABAP course.
You can call it by choosing Tools -> ABAP Workbench -> Development -> Class Builder
or using the transaction code SE24.

6.1.6 Debugger

One of the central tools of the ABAP development environment is the debugger. It enables the
stepwise execution of applications, controlling the values of variables, structures, and tables
during runtime and supports breakpoints (points where the program flow shall be interrupted)
as well as watchpoints (conditional breakpoints where the interruption depends on variable
values).

The debugger van be activated using the menu path Program -> Execute -> Debugging or
using the prefix /h when calling a transaction.

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

6.1.7 Object Navigator

The Object Navigator unifies all the tools presented before in a common user interface. You
have used it already when you created your HELLOWORLD program. It offers a navigation
tree on the left side of the screen, while the right side is used to display different content.

The transaction code of the Object Navigators is SE80.

Figure 17: The Object Navigator: SAP-System-Screenshot

6.1.8 Repository Infosystem

The Repository Infosystem is a search tool, which can be used to find certain development
objects (programs, for example) or even parts of programs. You will not need this tool a lot at
the beginning of this course, as your programs are not too complex and all development
objects are well-known. Nevertheless it will be very helpful for advanced development tasks,
for example, in the advanced ABAP course, when you will enhance existing programs in the
SAP system, you will see the value of this tool.

6.2 Exercise: The development environment


6.2.1 Display mode vs. change mode

As you have already left the Object Navigator, reopen it now (using transaction code SE80 or
the path Tools ->ABAP Workbench -> Overview -> Object Navigator from the Easy
Access Menu).

Open your program ZZ_####_HELLOWORLD again. Take care that you might not be in
the change mode. You can recognize the change mode by the white background of the editor.
If the background is blue instead, you are in display mode and cannot change anything in your
code. Furthermore, you can see the current mode in the headline, being “ABAP Editor:
Display Report …,” or “…Change Report…”, respectively. Change the mode using the menu
path Program -> Display<-->Change or the -icon or the keyboard shortcut Ctrl+F1.

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

6.2.2 The ABAP keyword documentation

Add the following lines at the end of your hello world program:

NEW-LINE.

WRITE 'Another line'.

The meaning of these lines might be obvious or easy to guess, but in many cases you may be
unsure about the exact effects of a statement or about the semantics of its parameters. For
these situations, the ABAP Editor offers a very convenient feature, which is called the
keyword documentation. This integrated documentation should become an essential part of
your programming. It can be used to navigate directly to the documentation of a keyword
from its usage in the ABAP source code. This is so easy that it is the most common entry
point to the documentation. If, for example, you want to know something about a statement,
you simply type it in your source code and call the integrated keyword documentation as
explained below.

To call the documentation, put your cursor on the statement NEW-LINE. After that, press the
F1 key.

A new window appears which contains the documentation of the statement:

Figure 18: Keyword documentation of NEW-LINE: SAP-System-Screenshot

You can see that the statement causes a line break. Note that it is also possible and more
common to initiate a line break in the WRITE statement. This will be explained later.

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

Save your modified program now. The system will ask you for a new request now, because
you released the request in which the program was created in the last exercise already. Hence,
Use the button Own Requests and select the request you created for the creation of the
package ZZ_####.

If you are not asked for a request, you have released a different request in the last exercise.
This is not a problem, and you can proceed. If you accidentally release your request later, you
can simply create a new one.

6.2.3 The pattern button

Using the pattern button, it is possible to insert common ABAP statements without the need to
type all components of the statement manually.

As an example, you will now print a symbol in your program. For this purpose, put the cursor
in a new line at the end of your program and click on the Pattern button. A new window
appears which offers different patterns:

Figure 19: Insertion of patterns: SAP-System-Screenshot

Select WRITE and commit. Another window displays the available patterns for WRITE
statements:

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

Figure 20: WRITE patterns: SAP-System-Screenshot

Change the selection to Symbol and use the F4 help on the corresponding input field on the
right to select a (arbitrary) symbol. To commit your selection, click on ..

You can see that the pattern button inserted another WRITE statement in your source code.
However, if you test your program now, you will see an error message:

Figure 21: Error message: SAP-System-Screenshot

The reason for this error message is that the system obviously does not know your symbol. It
assumes that your intention was to write “SY-” instead, because this sounds similar and is the
name of an available system structure. However, you definitely wanted to insert a symbol and
try to find out what is missing now.

Remember the previous Exercise: Use the integrated keyword documentation of the ABAP
Editor. Put the cursor on the word SYMBOL of the WRITE-Statement (it would be possible
to enter the documentation from WRITE, too, but this would mean you have to navigate more
inside the documentation). This way, you are directly taken to the part of the documentation
that explains the addition AS SYMBOL of the WRITE statement. There, you can read that it
is necessary to use an include “<LIST>” in your Program to be able to use the addition. At
this point, you do not yet know what an include is, but the required statement is displayed in
the documentation, so you can add it in your program (put it after the line “REPORT
ZZ_####_HELLOWORLD”):

INCLUDE <LIST>.

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

Your code could now look like this (depending on the symbol you chose above):

Figure 22: Changed code: SAP-System-Screenshot

Save, check, activate and test your program. There should be no error message anymore, and
the output should contain the symbol:

Figure 23: Output of the symbol: SAP-System-Screenshot

The use of the keyword help and patterns are the most important help functions for an ABAP
developer. We strongly recommend (and expect you) using these functions during the course.
Not all syntactical details can be displayed on the course material.

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

6.2.4 Version Management (Part 1)

The ABAP development environment of the SAP system contains an integrated version
management tool. Using this tool, it is possible to save an arbitrary number of intermediate
versions of your source code. Later, you can undo your changes by going back to one of the
saved versions in the version database. However, make sure that you activate the final version
of your code before you inform your tutor about a finished chapter, to make sure your final
version is checked.

At the beginning of this exercise, add another line at the end of the program:

WRITE 'Version management exercise'.

Save the program, but do not activate it. This way, an active and an inactive state of your code
exist in parallel in the system. This will also be visible in the version management tool, as you
will see now.

Open the version management using the menu path Utilities(M) -> Versions -> Version
Management. There you can see the currently available versions of your program. The screen
should look approximately as follows:

Figure 24: Version Management: SAP-System-Screenshot

As announced before, you can see the active and inactive state of your report. However,
below, there is a notice that there are no versions in the version database. This means that you
have not yet created any versions explicitly, to which you could jump back later. This will be
changed now.

Go back to the ABAP editor and create a new version by choosing the menu path Utilities(M)
-> Versions -> Generate Version. Afterwards, go back to the version management. Now you
can see the version you created in the list. You can use this screen later to compare different
versions using the -button Compare or the F8 key. To do this, you have to select the
Page 34
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

versions that should be compared by clicking the corresponding checkboxes at the beginning
of the lines. You did not change your program so far, so you will not see any differences
between the versions up to this point.

Figure 25: Your version in the version database: SAP-System-Screenshot

You can use the version management during the course if you want. However, make sure that
the final version of your program is activated when you finish a chapter.

6.2.5 Using the debugger

A very important tool for software development in almost any programming language is the
debugger. Such a debugger is also available in the SAP system to support your ABAP
program development. The debugger helps you to detect errors in your programs or to analyze
the behavior of your code. To learn about the basic functions of the debugger, change your
code as follows. Remember that your old code will not be lost, because you created a version
in the previous exercise.

(Open your code and modify it. Of course, the comment at the beginning and your user
number in the REPORT statement should be kept.)
REPORT ZZ_####_HELLOWORLD.

DATA num1 TYPE i.


DATA num2 TYPE I VALUE 5.
num1 = 1.
num2 = 0.
WRITE num2.
num1 = 11 / num2.
WRITE 'End of the program'.

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

Figure 26: Some lines of code: SAP-System-Screenshot

Save your program. Also check and activate it. The activation is important, because you will
add breakpoints directly in the source code later, which requires the code to be active.

At the moment, you do not have to understand each detail of the statements in this code. This
exercise is just used to explain the basic functions of the debugger. However, based on your
previous knowledge from other programming languages, you should understand that these
lines simply contain the definition of two variables, value assignments and output of the
variables num1 and num2. Both variables are integers (Type I in ABAP).
A problem can be expected, as there is an obvious division by zero in line 19.

6.2.5.1 Old vs. new debugger

Since release 6.40 of the SAP system, the ABAP development environment offers two
debuggers: the classic debugger and the new debugger. One of the reasons that led to the
development of the new debugger was the fact that, using the old debugger, the application
being debugged and the debugger itself share the roll area of an external session. Therefore,
each action of the debugger can potentially have an influence on the application. The classic
debugger cannot be used for debugging the control flow of user interfaces.

IN older systems, the classic debugger is still the default debugger, because initially the new
debugger lacked some functionality. For example, there were no watchpoints. In this course,
we use the new debugger, but the functions are quite similar, so a change of the debugger will
not cause too many problems for you.

If you want to try the other debugger, choose the menu path Utilities -> Settings -> Tab
ABAP Editor -> Tab Debugging -> ABAP-Debugger and switch the debugger. Make sure,

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

before proceeding, that the new debugger is active in your system. It is also possible to
change the debugger during debugging using the menu path Debugging -> Switch to Classic
Debugger or Debugging -> Switch to new ABAP Debugger, respectively.

6.2.5.1 Control of execution

Start your program in debug mode using the menu path Program -> Execute -> Debugging.
The Debugger should look as follows:

Figure 27: The new Debugger: SAP-System-Screenshot

The debugger offers four navigation icons:

Figure 28: Navigation icons of the debugger: SAP-System-Screenshot

Single Using this icon, you execute the program step-by-step. This can be used for a
Step detailed analysis. Switching to different (called) program units is possible.
This function is a bit different, because all statements of a line are executed in one
Execute
step, so sub procedure calls are executed at once.
Return This button is used to return from a sub procedure back to the calling program.
Continue Use this function to proceed with the program execution until the next break point
Page 37
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

is reached. If no more breakpoints occur, the debug mode will be left and the
program will be executed.
Table 1: Control functions of the debugger

By double clicking on variables, they are observed. Alternatively, you can enter their names
manually in the right side of the screen. For each observed variable, its current value is
displayed.

Observe the variables num1 and num2 by double-clicking on them, and execute your
program in the debugger using single steps. At the line where the division shall take place, an
exception will occur, because the program tries to divide by zero.

Figure 29: Observing variables in the debugger: SAP-System-Screenshot

Figure 30: A zero division exception has occurred: SAP-System-Screenshot

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

Using the menu path Runtime Errors -> Debugger or the F7 key, you can get back from the
runtime error to the debugger. Choose the menu path Debugger -> Exit Debugger to leave
the debugger. By entering /nSE80 in the transaction code field, you can quickly jump back to
the object navigator.

6.2.5.2 Watchpoints

The debugger offers functionalities to observe the values of variables automatically during
execution of a program. This is done by defining Watchpoints. Start your program in the
debug mode again.

Figure 31: Icon to create Watchpoints: SAP-System-Screenshot

TO create a new watchpoint, click on the -button (create watchpoint) or use the
keyboard shortcut Shift-F8. Enter num2 as variable. Open the condition part by clicking on
. Enter the condition “num2 = 0” (Make sure there is whitespace around the “=”). The
watchpoint shall be reached when num2 receives the value 0 (in a more complex program, it
could be possible that, e.g., you know the line where an error occurs, like the zero division
here, but do not know when the problematic value that leads to an error later is assigned to the
variable).

Figure 32: Creating a watchpoint: SAP-System-Screenshot

Confirm and execute the program in single steps. After num2 has received the value 0, the
system tells you that a watchpoint has been reached.

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

Figure 33: The watchpoint has been reached: SAP-System-Screenshot

Note that the arrow that indicates the current line in the source code is already positioned at
the line "WRITE num2." Open the tab Break./Watchpoints (not the button Watchpoint for
the creation of a new watchpoint, the tab from the row below). You can see which watchpoint
has been reached there:

Figure 34: Watchpoint list: SAP-System-Screenshot

The watchpoint made it possible to find the line of code that was responsible for the
assignment of 0, which later caused the zero division problem. This may appear trivial in this
simple case, but it is an important depiction of a debugging concept, which can be very
helpful later in more complex programs.

6.2.5.3 Breakpoints

Like watchpoints, breakpoints are another concept that is well-known from other
programming languages or debuggers. The task of a breakpoint is to interrupt the execution of
a program at a certain point. Using this concept, debugging a specific section of a program
becomes much easier, because it is not necessary to use the single step mode until the relevant
source code section has been reached.

In the ABAP-Debugger, there are two types of breakpoints: static breakpoints and dynamic
breakpoints.

Static breakpoints are parts of the source code and consist mainly of the keyword BREAK-
POINT. Additionally, they may contain a number to distinguish the breakpoints easier, e.g.,
BREAK-POINT 1.

Static breakpoints may be user dependent. A breakpoint BREAK username. will only be
considered by the debugger if a user with the given name executes the program. Static
breakpoints have to be removed before transporting a program into a productive system.

Dynamic breakpoints do not change the source code of your program. They can also be
added from the ABAP editor, but also be inserted from the debugger, just like watchpoints.

In the ABAP Editor, you create a breakpoint by clicking on the line in which the execution
should be interrupted and the menu path Utilities (M) -> Breakpoints -> Set/Delete, or by
clicking on the -icon. Breakpoint lines are highlighted in the debugger. If you encounter an

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

error message “You can only set breakpoints in an active, unchanged source,” you first have
to save and activate your program.

In the debugger itself, setting a breakpoint is possible by selecting the corresponding line and
then calling Breakpoints -> Create Breakpoint from the menu or simply clicking on the
begin of the line. Breakpoints are marked by a stop sign and color.

Figure 35: Dynamic breakpoint in the editor: SAP-System-Screenshot

Figure 36: Dynamic breakpoint in the debugger: SAP-System-Screenshot

Dynamic breakpoints that have been created in the debugger get lost when you leave the
debugger. To avoid this, you can save them from the Breakpoints Menu.

Test the concept of breakpoints by adding a dynamic breakpoint at the statement "num1 = 1"
in your code. Start the debugging and use the Continue function or the F8 key to jump to
your breakpoint immediately. The program will be executed normally until your breakpoint is
reached. Using the same function (Continue), you can continue after the breakpoint.
Afterwards, get back to the object navigator.

6.2.5.4 Important hint for debugging

Creating a dynamic breakpoint is the easiest way to start the debugger in practice: As soon as
a dynamic breakpoint is added to your program, the testing button ( ) directly starts the
debugger on the breakpoint.

This is not only easier than using the main menu. There is an additional advantage: You are
directly at the relevant point of the program. In larger programs, you will often see some
system code which is executed before you reach your code (in the context of graphical user
interfaces, for example). If you use a dynamic break point instead, you will be directly at the
interesting part.

6.2.6 Version Management (Part 2)

Choose the menu path Utilities (M) -> Versions -> Generate Version to save the current
development as a version. Then, change your program code by deleting the line in which the
zero division happens. Save, check, and activate your program. If you test it now, you will see
the output without a zero division error.

Now, call the version management (Utilities (M) -> Versions -> Version Management)
from the menu.

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

Figure 37: Versions of your program: SAP-System-Screenshot

In the bottom line, select the checkbox of version 0001 of your program and select Versions -
> Retrieve from the menu or click on the corresponding button to return to the previous
version. You will see a warning message, which you can confirm. The system informs you
that a temporary version has been generated before overwriting your code. Leave the version
management. In the ABAP editor, you see your original program. Analogously you can now
jump back to one of the other versions.

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

This page is intentionally left blank

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

7 Basic concepts of ABAP


This chapter contains the basic concepts of the language ABAP.

During this course, some syntax diagrams are displayed. To understand these descriptions,
we present a short overview on the syntax of the diagrams themselves.

Words in UPPERCASE LETTERS are keywords of ABAP, so they belong to the language and
have to be used like this in your code.

Parts in [square brackets] are optional and can, but do not have to, be used. The square
brackets are not part of the code.

Parts written in lowercase letters are explained in the text. Usually, they are data elements or
parts of the syntax, which are displayed separately.

Parts which are embraced by {curly braces} belong together. The braces are not part of the
code.

Parts displayed with a vertical bar are alternatives. For example, { a | {b c}} means that you
can use either a or b c.

In some diagrams, three dots are used when parts are left out. This means that at this place
may be further code, which has been left out for the presentation. If you miss details of the
syntax, use the integrated keyword documentation of the SAP system!

If you see round brackets () or <> brackets, they are parts of the ABAP code itself.

In most cases, ABAP code is written in Monospaced font.

7.1 Data types


In ABAP, a strong type concept is available. Firstly, there is a differentiation between
predefined ABAP standard types and local or global data types, which can be defined by the
user. The local or global data types can be divided into simple types with just one value and
complex data types (structure types and table types). Structure types are sometimes called line
types, because they can represent a line of a table. In this chapter, the standard types and local
type definitions will be presented, while global types will be discussed in the chapter about
the data dictionary.

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

Figure 38: Basic Structure of ABAP Types

Additionally, there are reference types. These types will be presented later.

Data types determine how the information in a field will be interpreted.

7.1.1 Built-in standard types

The following table displays an overview of the available predefined data types of the SAP
system.

Default Initial
Type Possible length Description
length value
1-262.143 (65.535 in
C 1 Character space Character string
earlier Releases)
N 1 Character See C '0...0' Numerical string
T 6 Characters 6 Character 000000 Time as HHMMSS
Date as
D 8 Characters 8 Character 00000000
YYYYMMTT
F 8 Characters 8 Character 0.0 Floating point number
Gleitpunktzahl
DECFLOAT16 8 Bytes 8 Bytes 0
(dezimal)
Gleitpunktzahl
DECFLOAT34 16 Bytes 16 Bytes 0
(dezimal)
I 4 4 bytes 0 Integer (whole

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

number)
P 8 1-16 bytes 0 Packed number
X 1 1-524,287 (earlier: 65535) X'00' Byte (hexadecimal)
Char field of variable
STRING 0 Any Null-String
length
Byte field of variable
XSTRING 0 Any Null
length
Table 2: Predefined data types in ABAP1

The types DECFLOAT16 and DECFLOAT34 have been added with release 7.02/7.20. They
shall replace the F type.

Data objects without an explicit type specification are implicitly of type C with length 1. This
is a common source of errors.

There are further types (b, s, cursor), which are not covered in our courses.

7.1.1.1 Character string (type C)

Character strings can contain arbitrary alphanumerical characters. As opposed to the (newer)
type STRING, the length of a character string of type C is fixed for the whole lifetime of the
data object.

Example: 'Hello World'

7.1.1.2 Numerical string (type N)

The numerical string, as opposed to the regular character string, can only contain numerical
characters, i.e., the numbers 0-9, but no sign. Numerical strings are usually used for keys like
product numbers or matriculation numbers. The value is stored right-justified, and unused
places are filled with zeroes.

Example: '0000003142'

7.1.1.3 Time (type T)

Time information is stored in the form HHMMSS, i.e., a two digit hour, followed by a two
digit minute and second information. The hours are stored in 24-hour format, ranging from 00
to 24. If the range is left by assigning a value greater than 24, no runtime error occurs.
Instead, the values start from 0 again.

Using a time data object in a WRITE statement leads to an output without dividing characters.
For formatted output, further parameters are required.

7.1.1.4 Example for formatted output of time

1
Adaptation from Keller (2012, S. 113ff.)
Page 46
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Add the following lines to your HELLOWORLD program:


DATA time1 TYPE t.
time1 = '123456'.
WRITE time1.
WRITE (8) time1.

Note: Before the equation sign in a value assignment, a space character is always required.

The output of this program part looks as follows:


123456 12:34:56

The first part of the output is the output without formatting. The second WRITE statement
contains the additional information that the value should be formatted for an output length of
8 characters; hence, the dividing characters are inserted.

7.1.1.5 Date (type D)

Date fields contain the date as JJJJMMTT, i.e., a four-digit year followed by a two-digit
month and a two-digit day information.

Formatting of the output is possible analogously to the time type described above. Also,
specific formatting masks can be applied. The available masks are DD/MM/YY,
MM/DD/YY, DD/MM/YYYY, MM/DD/YYYY, DDMMYY, MMDDYY, and YYMMDD.

However, the output is also dependent on the user master record, so the „/“ will be replaced
by a user specific divider determined there.

7.1.1.6 Example for date formatting

Add the following lines to your code:


WRITE sy-datum DDMMYY.
WRITE sy-datum DD/MM/YYYY.

These lines should lead to an output like the following:


311212 31.12.2012

Using sy-datum and sy-timlo, you can access the current date and the current local
time. Note, however, that these values are determined at the beginning of the program
runtime. In a complex program with a long runtime, this time could already have passed.
Using the GET TIME statement, you can ask the system to refresh the time information to get
a current value.

7.1.1.7 Floating point number (types F, DECFLOAT16, and DECFLOAT34)

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

Floating point numbers in the F type are internally stored in a binary representation consisting
of exponent and mantissa. This data type can be compared to the float type from the C
language. The output of floating point numbers is by default done in exponent representation.

For value assignments, the values are enclosed in single quotes. The comma is represented as
a dot, e.g., '1.2' or '-123E-5'.

The possible value range reaches from -1E307 to +1E307. The precision is approximately 15
digits. Hence, floating point numbers are especially suitable for data which requires a large
value range and for which a limited precision can be accepted.

As of release 7.02/7.20, the new types DECFLOAT16 and DECFLOAT34 are available.
DECFLOAT means decimal floating point number.

7.1.1.8 Integer (type I)

Integer (whole) numbers are also stored in a binary representation internally, so the field
length is not exactly the number of digits. The I data type is comparable to the corresponding
whole number types in languages like C or Java.

On usual hardware, values from -2^31 to +2^31, i.e., -2.1 billion to +2.1 billion, are
representable.

Example: 124

7.1.1.9 Packed number (type P)

Packed numbers are used for the representation of fixed-point numbers. During declaration,
the number of decimal points may be specified, which is 0 by default.

In one byte, two digits are stored. There is an additional digit, which stores the number of
decimal points. A minus sign has to be counted as a digit.

Packed numbers are used for data where the number of decimals is defined in advance, e.g.,
price information.

Example: '1.19' (Input in single quotes)

7.1.1.10 Hexadecimal string (type X)

This data type is not used very often. Like for the P type, each byte of the data element stores
two digits of the hexadecimal number.

7.1.1.11 Character strings with dynamic length (type STRING)

Character strings with dynamic length (type STRING) do not require the specification of a
length when they are declared. The required memory is determined dynamically during
runtime, which reduces memory consumption.

7.1.1.12 Hexadecimal string with dynamic length (type XSTRING)

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

Hexadecimal strings similarly have no fixed length. They contain hexadecimal values.

7.1.2 Completeness

The types D, T, I, F, DECFLOAT16, DECFLOAT34, STRING and XSTRING are called


complete types, whereas the types C, N, X and P are called incomplete types.

The latter have no fixed length, hence, the length is specified when a data object is defined.

7.1.3 Defining simple data objects

A simple data object (a variable or field) is defined using the keyword DATA. The syntax is
as follows2:
DATA var [(len)] {TYPE type_spec}|{LIKE dobj_spec}
[VALUE {val | IS INITIAL}}]
[READ-ONLY].

var is the name of the variable, e.g., "num1".

The len argument defines the length if the corresponding type allows a length specification.
Alternatively, the length can be specified by an addition of LENGTH len).

By TYPE type_spec, a data type is determined (see the last sub sections). Alternatively,
the specification LIKE dobj_spec can be used. Here, dobj_spec is another variable.
This specification means that you do not need to know the exact data type as long as a data
object of the required type is available. If no type is specified, the field has the type c(1).

Using VALUE val, you can specify an initial value. IS INITIAL sets the initial value to
the default initial value of the respective data type. This also happens if no VALUE
information is given.

The addition READ-ONLY is only relevant for ABAP Objects later in this course.

7.1.4 Examples for simple data object definitions


DATA num1 TYPE i.
DATA num2 TYPE f VALUE '0.2'.
DATA num3 LIKE num2.
DATA cutomername(20) TYPE c.

7.1.5 Basics of data manipulation

For the simple assignment of values to a variable, there are two possible formulations in
ABAP:
MOVE a TO b.

or

2
Keller (2102, S. 182ff.)
Page 49
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

b = a.

If you used languages like Java, Python, C++ or similar, you will be more familiar with the
second formulation. We will also use the second formulation throughout the course, as it is
easier to read.

Similar statements are available for simple operations. For example, an addition can be
written as follows:
ADD a TO b.

is similar to
b = b + a.

Similarly we will use the second formulation.

If the types of the variables in the assignment do not match, an automatic type conversion is
executed. Hence, it is possible to assign a P value to an integer variable. However, the
conversions require calculation and should, therefore, be avoided. If no suitable type
conversion is possible, an error will occur.

7.1.6 User-defined simple data types

Using the TYPES statement, you can define local data types within your program.

The syntax for this purpose3 is as follows:

TYPES dtype[(len)] {TYPE typedef} | {LIKE dobj }.

(Further syntactical variations of the statement will be explained during the explanation of
structure types).
Here, dtype is the name of the type to be defined, len is the length information for types
that have a length specification, typedef is the name of the type on which the new type
shall be based, while dobj represents a data object whose type shall be used. Both ways to
specify a type are already known from the DATA statement.

Example:
TYPES zipcode(5) TYPE n.
DATA myzip TYPE zipcode.
myzip = '45141'.

In this example, a type for zip codes has been defined, which is based on the predefined data
type n (numerical character). Afterwards, a data object of the newly defined type has been
defined and a value has been assigned.

7.1.7 Statement chains

The concept of statement chains saves a lot of typing effort for statements that are used
multiple times, like DATA, TYPES, or WRITE.

3
I. e. there are further syntactical options, cf. Keyword documentation or Keller (2012, pp. 154 ff)
Page 50
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Statements that directly follow each other and have identical parts at their beginning can be
shortened using statement chains. The part of the statements that is identical is written just
once, and finished by a colon. Thereafter, the different remaining statements are written,
separated by commas. A dot closes the chained statement.

Statement chain example:

Instead of repeating the keywords like this:


DATA a TYPE b.
DATA c TYPE d.

you can use this simple chained statement:


DATA: a TYPE b,
c TYPE d.

This is a very simple example for a chained statement. It should not lead to the assumption
that only one keyword can be used for the chained statement. In fact, longer statements can be
shortened, too, by separating all identical parts by the colon.
An example for such a case is shown in the following lines:

WRITE 'ABC' :

INVERSE,

HOTSPOT.

Here, the character literal 'ABC' is printed twice: first it is printed inverted, and then it is
printed as a hotspot.

Chained statements are an absolute fundamental concept, which is used by every ABAP
programmer.

7.1.8 Complex data objects

To represent complex data objects, simple data types are not sufficient: For example, a
student cannot be represented by a simple value, as he or she has different properties, such as
a name, an address or a matriculation number. It becomes even more difficult if a set of
multiple customers have to be processed by a program. For these and similar use cases,
structured data types are available in ABAP. They are divided into structure types and types
for internal tables.

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

7.1.8.1 Structures and structure types

The TYPES statement is also used for the definition of structure types. Structure types are
similar to Records from Pascal.
TYPES: BEGIN OF struc,
...
END OF struc.

Note that the chained syntax is used here. The last line of the code above would be TYPES
END OF struc, if written without chained statements. Within the structure type, fields can
be defined, e.g., as follows:
TYPES: BEGIN OF str_car,
manufacturer(20) TYPE c,
model(20) TYPE c,
color(10) TYPE c,
power TYPE i,
END OF str_car.

This is how a type is defined that determines the structure of data objects of type str_car.

Figure 39: The structure type str_car

The newly defined type can be used for a variable declaration now:
DATA mycar TYPE str_car.

The fields of the structure are also called components. They can be accessed using the hyphen
syntax as follows:
mycar-manufacturer = 'Volkswagen'.
mycar-model = 'Passat'.
mycar-color = 'red'.
mycar-power = 150.

The data object looks like this now:

Figure 37: Instance of type str_fahrzeug

Structures can be nested like in the following example:


TYPES: BEGIN OF str_col,
red TYPE i,
yellow TYPE i,
blue TYPE i,
END OF str_col.

TYPES: BEGIN OF str_car_new,


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

BEGIN OF name,
manufacturer(20) TYPE c,
model(20) TYPE c,
END OF name,
color TYPE str_col,
power TYPE i,
END OF str_car_new.

The type str_car_new contains the structure type name as a component and uses the type
str_col. It can be used like this:

DATA mycar2 TYPE str_car_new.

mycar2-name-manufacturer = 'Ferrari'.
mycar2-name-model = 'F40'.
mycar2-color-red = 2.
mycar2-color-yellow = 10.
mycar2-color-blue = 65.
mycar2-power = 200.

The depiction is slightly more difficult now. Now mycar2 is a structure that has components
that are structures themselves:

Figure 38: Visualization of the structure of type str_car_new

Note that you could also define a data object directly as a structure without defining a type
explicitly:

DATA BEGIN OF dobj.

DATA …

DATA END OF dobj.

However, this is not a good programming style, so in our exercises we will always define
types explicitly.

7.1.8.2 Reusing structures to define other structures

Using the statement INCLUDE TYPE, it is possible to reuse the components of one structure
in another structure without building sub-structrues. Have a look at this example:

TYPES BEGIN OF str_fleet_car.

INCLUDE TYPE str_car_new.

TYPES car_number TYPE i.

TYPES END OF str_fleet_car.


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

Here, a structure type str_fleet_car is defined, which contains all components of


str_car_new, but additionally a car number. If you would define a corresponding data
object now:

DATA johnscar TYPE str_fleet_car.

This way, you could now use johnscar-power to access the car’s power or johnscar-
car_number to access the car number.

Attention: In the example, no chained statement was used. A common programming mistake
is to try to use the INCLUDE TYPE statement inside a chained TYPES statement, as in the
following lines of code:

TYPES: BEGIN OF str_fleet_car,

INCLUDE TYPE str_car_new, " !Attention!

car_number TYPE i,

END OF str_fleet_car.

The result is not the same as above: INCLUDE TYPE is a separate statement normally. Here,
however – because of the chained statement – the line becomes TYPES INCLUDE TYPE
str_car_new. This does not include the components of the structure. Instead, the result is a
sub-structure with the name “include,” similar to the sub-structure for the color of the car.
This is normally not the intention.

7.1.8.3 Flat and deep structures

Structures can be divided into flat and deep structures4. Flat structures have only components
based on elementary data types with fixed length (including nested structures with flat types
in the sub structures). Deep structures, however, are structures in which at least one
component (or component of a sub structure) is typed as an internal table or a data type like
STRING, which has no fixed length.

At this point, the distinction is not too important for you. However, if you start to create
graphical user interfaces (programs with screens), this difference becomes relevant. You will
get to know the TABLES statement, which is very useful in that context but has the
disadvantage that it cannot handle deep types. You should keep in mind, though, that using
the STRING type (as opposed to the C type with fixed length) in conjunction with screens
might cause problems.

7.1.8.4 Exercise: Structures and structure types

Create a new program called ZZ_####_CARS by opening the Object Navigator (transaction
code SE80), selecting Program from the drop-down field on the left, entering the name
ZZ_####_CARS in the field below and pressing Enter. Confirm the question whether you
want to create the program. Unselect the field With TOP INCL and choose the status Test
Program in the following window.

4
Keller and Krüger (2011, p. 262)
Page 54
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Commit and choose your package ZZ_#### in the next window. Similarly, make sure your
request is used. After committing the request window, you can start editing the program
source code.

Note: If you see your program on top of the navigation tree on the left side of the Object
Navigator (in the Repository Browser) and you want to jump to a different program in your
package, you can use the icon Display Superord. Object List to jump to the next higher
level. Furthermore, it is possible to define favorites using the icon next to it. Note further that
there is no synchronization between the right and left side, so it is possible that you navigate
to a different element on the right while the navigation tree still shows the last opened
program. You can synchronize this using the -icon.

The program being created shall be able to work with cars. These shall be represented by a
corresponding structure. Hence, you will define a corresponding structure type now before
defining data objects.

Define a structure type str_car (use the TYPES statement). The structure type should
contain at least components for the manufacturer and model name, power (in horse power),
year of construction, and a serial number. The names should be of type c (character) and have
a length of 20 (characters), while the power should be of type I, the year of construction of
type n (numerical character), and length 4, and the serial number should be of type n
(numerical character) and have a length of 10 (characters). Add three more components to
the structure type str_car and choose suitable types for them.

Now, create a variable of the type str_car. Assign example values to all components of the
data object. Use the hyphen syntax to access the components. And take care that a space
character is present before and after the equation sign. Enclose all character strings in single
quotes, including the serial number, because the n type is also a character type, e.g.,
'Volkswagen'.

Afterwards, the data should be printed to the screen. Use the statement WRITE /. for this.
The slash makes sure that the output begins in a new line. To get help on how to use the
statement, put the cursor on the WRITE statement and press the F1 key. Simplify the source
code by using chained statements for the WRITE.

Before you print the individual component of the structure, print the respective name as a
character literal, for example (the code may differ depending on the names you chose for your
variable and component):

WRITE: / 'Year of construction:', mycar-year.

Save, check, and activate your program, then test it. The output should look as follows:

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

Figure 40: Possible output of your program: SAP-System-Screenshot

Test your program again, but this time, use the debug mode (Program -> Execute ->
Debugging). By double-clicking on the component name (e.g., manufacturer, depending
on your choice of field names), you can observe its value on the right. When the value is
assigned to the component, you see the value change like in the following figure:

Figure 41: Single components in the debugger: SAP-System-Screenshot

If you click on the name of the variable in the DATA statement, you observe the structure as a
whole. It appears like this:

Figure 42: Structure in the variable list: SAP-System-Screenshot

To see the content of the structure, double-click on its name in this list. Now, you can see the
whole structure:

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

Figure 43: Detailed view of the structure: SAP-System-Screenshot

7.1.8.5 Internal tables and table types

If, as in section 7.1.8.1, multiple cars of the same type have to be represented in a program,
for example, a list of all company cars, an internal table is required. Internal tables are
temporary tables, which are defined by a table type. Internal tables contain data of identical
structure. This structure, which is similar to a description of the table columns, is defined by
the type of the table. The entries of the table are also called lines of the table.

An internal table is a local data object, as it is the case for simple data objects and structures
as described above. Hence, an internal table is not a table of the underlying database system.
(How the database is used will be explained in a later section of the course). However,
internal tables can be used to locally maintain the data that has been read from a database
table by defining an internal table with a similar structure as the database table.

The line structure of the internal table is, therefore, a part of the syntax of the internal table
definition5:
TYPES typename { { TYPE tabkind OF [REF TO] type }
| { LIKE tabkind OF [REF TO] dobj } }
[WITH key] [INITIAL SIZE n].

Here, typename is the name of the table type being defined, while type is the type that
describes the structure of each line of the table (theoretically, you can use a data type which is
not a structure, too). The LIKE-part represents a definition based on the type of an existing
data object, as you know it already from other variants of the TYPES syntax. The REF TO-
syntax will be explained later during this course. The INITIAL SIZE information makes it
possible to tell the system how many lines should be reserved in terms of space in the main
memory. This is only useful if the number of lines is known in advance.

tabkind defines the type of the table. In ABAP, there are three general types of internal
tables:

5
Keller (2012, pp. 164ff.)
Page 57
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 44: Kinds of tables

Standard tables are defined by the syntax STANDARD TABLE. These kinds of tables do
not have a fixed order of their entries, so new entries can be added to the table at arbitrary
places. Standard tables can be accessed both by index as well as using a key.

Sorted tables are defined by the syntax SORTED TABLE. These kinds of tables are always
in a sort order. Hence, it is impossible to insert an element at a place in the table that would
lead to a violation of the search order. Trying to do this will lead to a crash of your program.
It is possible to access the table by index or by key. Unique and non-unique keys are allowed.

Hash tables are the third kind of table. They are defined by the syntax HASHED TABLE.
Their specialty is that they can only be accessed based on a key, but not using an index.
Hence, only the first two kinds of tables are called index tables. The key must be unique.

Access by index is the access to a line of the internal table by specifying its line number. An
access by key is based on the specification of a key. The key is a field of the table that is used
for sorting, so search for an entry based on the key information can be done very efficiently.

An unambiguous key, a key where no two lines have the same key value, is called a UNIQUE
key. An ambiguous key is called NON-UNIQUE.

It is recommended6 to use key-based based access if possible, so hashed tables can be used
that allow an optimized access in this case. Otherwise, according to the recommendation, a
sorted table should be used if there is a mixed key/ index access scenario. Standard tables are
used in cases where Data is inserted into a table and sorted later before output.

The syntax for tabkind is as follows:


… { {[STANDARD] TABLE }
| {SORTED TABLE}
| {HASHED TABLE}
| {ANY TABLE}

6
Keller und Krüger (2011, pp. 321f.)
Page 58
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

| {INDEX TABLE} } …

The first three Table types are the ones described above, but the word STANDARD is optional.
The additional possibilities ANY TABLE and INDEX TABLE can only be used for the
definition of formal parameters and field symbols (you have not learned these topics yet), and
describe “any type of table” or “standard or sorted table,” respectively.

The syntax for key is7 as follows:


… [UNIQUE | NON-UNIQUE] { {KEY comp1 comp2 …}
| {DEFAULT KEY} } …

Here, comp1 comp2 … are the components of the key. You see that the key may be
composed from multiple columns. It is required that the keys are not tables or structures
containing tables themselves. In most cases, the columns of your tables will be usual, non-
structured types.

7.1.8.6 Example: local table types

Based on the above example on structure types, we can define a table type for a table of cars
now:

TYPES tab_cars TYPE STANDARD TABLE OF str_car WITH KEY manufacturer.

The structure type str_car defines the structure of the lines of the table type tab_cars
here. This is the reason why structure types are sometimes called line types. Using the defined
table type, we can now define an internal table:
DATA itab_cars TYPE tab_cars.

Alternatively, it is possible to leave out the type definition and directly use the structure type
for the definition of the table:
DATA itab_cars TYPE STANDARD TABLE OF str_car WITH KEY manufacturer.

In both cases, a table as in the following figure is defined:

Figure 43: Internal table tab_cars

7
Krüger (2012, p. 169) with a more detailed description
Page 59
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Internal tables can be used for tasks where arrays or lists would be used in other programming
languages. The line structure of a local table type can also be a global structure from the Data
Dictionary, which will be presented to you later.

Be careful! Often people make a wrong definition like this one:

DATA itab_cars TYPE STANDARD TABLE OF tab_cars.

This line does not define a table of cars, as you might think. Instead, a table of tables is
defined. In other words: Here, the table itab_cars has only one column, and in this
column, each line has another table of cars. Syntactically this is allowed, but in most cases it
is not what you really want to define.

Note:
To find out about further possibilities to use the TYPES statement, put your cursor on it in
your source code and press the F1 key.

7.1.8.7 Operations on internal tables

The following sections explain the different operations that can be performed on internal
tables.

7.1.8.8 Accessing single lines

For most operations on single lines, you need a data object that has a structure similar to a line
of the table. This data object is called a work area.
A special case is internal tables with header line: These tables contain a header line
themselves, which is similar to a work area. These kinds of tables will be explained in more
detail separately. Normally, regular internal tables without header line should be used.

Insert Append Read Modify Delete

INSERT APPEND … READ TABLE MODIFY DELETE…


…INTO… TO… TABLE …
… INTO… FROM…

Figure 45: Accessing lines of internal tables

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

In the following sections, the above-mentioned statements are explained. Please note that we
cannot display each detail of the syntax of these statements. Complete explanations of all
syntactical options can be found in the keyword documentation8.

7.1.8.8.1 Insert
To insert a line (the content of the work area) into a table, the INSERT statement is used:

INSERT wa INTO { TABLE itab} | { itab INDEX idx}.

If you use TABLE itab in case of a standard table, the new entry will be inserted at the end
of the table. In case of hash tables or sorted tables, it will be inserted at the corresponding
position. The second variation of the syntax is only allowed for standard tables and sorted
tables. It inserts the line at the position given by the idx argument. This is dangerous in case
of a sorted table, because a violation of the sort order leads to an exception that cannot be
handled.
Example:
DATA wa TYPE spfli.

DATA itab TYPE TABLE OF spfli.

wa-carrid = 'LH'. wa-connid = 401.

INSERT wa INTO TABLE itab.

Attention:
Often people make mistakes with this statement which lead to confusing error messages. For
example if you would accidentally write
INSERT wa INTO itab.

instead of
INSERT wa INTO TABLE itab.

In the example above, you would see the following error message during execution:

8
Or confer Keller (2011, pp. 726 ff.) or Keller and Krüger (2012, pp. 326 ff.)
Page 61
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Figure 46: Error message (INTO instead of INTO TABLE): SAP-System-Screenshot

Take care of similar statements:


Later in this course, you will learn about statements to work with database tables. These
statements are quite similar to those shown here for internal tables. Hence you should be very
careful and remember whether you are currently working with an internal table or a database
table.

Figure 47: Internal table vs. database table

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

7.1.8.8.2 Append

APPEND wa TO itab.

Here, a line will be appended at the end of the table itab. In this case, itab should be a
standard table. The reason for this is that appending something at the end of a table makes no
sense for sorted tables (which are sorted anyway) and is impossible for hashed tables. If you
would apply the statement to a hashed table, there would be a syntax error. If you would apply
it to a sorted table, there is a risk of a runtime error if appending the work area would violate
the sort order.

7.1.8.8.3 Read
Using the READ- statement, a line of the internal table can be read into the corresponding
work area.

READ TABLE itab { { FROM wa2 }


| { WITH TABLE KEY f1 = d1 f2 = d2 … }
| { INDEX idx } }
INTO wa.

Here, wa is the work area into which the line should be read. wa2 is a different work area
whose values in the key components can be used for the selection of the line. Alternatively,
key values can be specified separately using the WITH TABLE KEY syntax variation.
Furthermore, an access based on the index is possible using the INDEX syntax (for suitable
tables).

Example:
READ TABLE itab INTO wa WITH TABLE KEY carrid = 'LH' connid =
401.

This statements reads the record from itab into the work area wa which has the value LH for
the carrid field and the value 401 for the connid field.

If you specify the conditions of this statement in a way that multiple records match the
criteria, the first found record will be used by the system.

7.1.8.8.4 Modify
Using the MODIFY statement, a line of the table is overwritten by data of the work area.

MODIFY {{ TABLE itab}


| { itab INDEX idx }}
FROM wa.

Like for the insert, the line can be given using an index (if an index is available for the table
type) or the key.

Example:
MODIFY TABLE itab FROM wa.

This code modifies the record if the internal table itab which matches the key components of
wa with the content of wa.

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

7.1.8.8.5 Delete
The syntax of the DELETE statement is similar:

DELETE {{ TABLE itab table_key}


| { itab INDEX idx }}

The first variation deletes based on the key, while the second one uses the index. The key
table_key has to be specified as follows:

… { FROM wa }
| { WITH TABLE KEY c1 = d1 c2 = d2 …}

The meaning of symbols is similar to the READ statement.

Example:
DATA wa TYPE spfli.

DATA itab TYPE SORTED TABLE OF spfli WITH UNIQUE KEY carrid
connid.

wa-carrid = 'LH'. wa-connid = 401.

INSERT wa INTO TABLE itab.

wa-carrid = 'AA'. wa-connid = 333.

INSERT wa INTO TABLE itab.

DELETE TABLE itab WITH TABLE KEY carrid = 'LH' connid = 401.

Here, a sorted table is defined with carrid and connid as the key components. These
components are used in the key-based deletion in the last line.

7.1.8.9 Excursus: The sy-subrc

When these various statements were presented to you, you might have wondered if there
could be less harmful error situations than thos where you can expect an exception. For
example, when you us the MODIFY statement, it is possible that no record in the internal
table matches the criteria. This does not lead to an exception, but is still an unexpected
behavior. To find out if something went wrong, there is a special system variable called sy-
subrc. This variable iss et by the corresponding statement automatically and can be evaluated
avterwards to determine the success of the statement.

For example, the MODIFY statement sets the value of sy-subrc to 0, if at least one line
matched the search criteria and was changed. Otherwise, the value of sy-subrc is set to 4.
This value can then be evaluated immediately after the statement. It is very important to
implement this evaluation directly after the statement. If other statements appear in between
they could overwrite the sy-subrc with their own success information. The evaluation of the
sy-subrc is usally implemented using an IF statement. The syntax of IF statements will be
explained later in the control structures section of this document. However as you should
know about IF statements from other programming languages, an example will be shown
nevertheless:
Page 64
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

MODIFY TABLE itab FROM wa.

IF sy-subrc = 0.

WRITE 'All right'.

ELSE.

WRITE 'This did not work!'.

ENDIF.

This code prints “All right” if the MODIFY statement before the IF found a record in the
internal table to be changed. Otherwise, “This did not work” will be printed instead.

To find out which values of the sy-subrc are set by a specific statement, look at the integrated
keyword documentation of the statement. This is very importand – you should use the sy-
subrc for success checks if they are possible. Do not use any improvisational ways instead.
Usually the value 0 of the sy-subrc represents a successful execution of a statement.

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

7.1.8.10 Accessing multiple lines

Processing line-by- Deleting multiple Inserting lines of Appending lines of


line lines other tables other tables

LOOP AT … / DELETE… INSERT LINES APPEND LINES


ENDLOOP OF… INTO … OF … TO …

Figure 48: Processing multiple lines of internal tables

7.1.8.10.1 Processing line-by-line


You can create multiple lines of an internal table successively using the LOOP statement. This
statement is a special kind of loop though, which is used for internal table iterations. The
Syntax is as follows:
LOOP AT itab result [cond].
...
ENDLOOP.

Here, itab is an internal table from which all lines are read one after another. Each time, the
loop body (indicated by … here) is executed.

The location where the lines should be stored is given by result using the following syntax:
... {INTO wa }
| {ASSIGNING <fs>}
| {REFERENCE INTO dref }
| {TRANSPORTING NO FIELDS } ...

INTO assigns a work area wa. The other three options are not yet relevant (they are covered
in the advanced course). The work area is still a data object that has the structure of a line of
the table itab.

The conditions in cond are specified by this syntax:


[FROM idx1] [TO idx2] [WHERE log_expr]

By using FROM and TO, it is possible to restrict the loop to a certain range of indices of the
table. By using WHERE, it is possible to define a logical expression. Only lines that fulfill the
logical expression will be used for the loop.

The number of the current loop iteration can be found in the system field sy-tabix during
the LOOP execution. The system structure sy contains some more helpful components, which
will be explained later during the course.

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

Typically, you do not need any complex additions. The majority of loops can be written quite
simple, as in the following example.

Example:

LOOP AT itab INTO wa.

WRITE: wa-carrid, wa-connid.

ENDLOOP.

Here, the lines of itab are transported to wa one by one. For each line, the carrid and connid
components are printed.

7.1.8.10.2 Deleting multiple lines


The already presented DELETE statement can also be used to delete multiple lines:

DELETE itab [FROM idx1] [TO idx2] [WHERE log_expr].

Here, an index range can be specified using idx1 and idx2, or a logical expression
log_expr can be given (similar to the one used for the LOOP).

7.1.8.10.3 Inserting lines of another table


Using the following syntax, multiple lines from one internal table can be copied and inserted
into a different internal table:

INSERT LINES OF itab2 [FROM idx1] [TO idx2]


INTO {{TABLE itab}
| {itab [INDEX idx]}}.

Here, the lines of itab2 from index idx1 to index idx2 will be inserted into the table
itab. The meaning of the syntax after INTO is similar to the INSERT statement for single
lines (see above).

7.1.8.10.4 Appending lines of other tables


The following syntax is used to append multiple lines from one table to another table:

APPEND LINES OF itab2 [FROM idx1] [TO idx2]


TO itab.

Here, the lines of itab2 from index idx1 to index idx2 will be appended at the end of
table itab.

7.1.8.11 Condensed insertion

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

Figure 49: Condensed insertion of lines

A less common statement is the COLLECT statement:

COLLECT wa INTO itab.

Here, the key is important. If itab does not yet contain a line with the same key as wa, wa
will be inserted like a usual INSERT statement. If there is already a line with the same values
for the key components, all non-key-components of wa will be added to the corresponding
components of that line. This requires all non-key components to have a numerical data type.

7.1.8.11.1 Example for condensed insertion

TYPES: BEGIN OF str_car_km,


number TYPE i,
km TYPE i,
END OF str_car_km.

DATA: kilometer_values TYPE SORTED TABLE OF str_car_km WITH


UNIQUE KEY number,
trip TYPE str_car_km.

trip-number = 1.
trip-km = 100.
COLLECT trip INTO kilometer_values.
trip-number = 2.
trip-km = 30.
COLLECT trip INTO kilometer_values.
trip-number = 1.
trip-km = 50.
COLLECT trip INTO kilometer_values.

Here, a table for kilometer values of cars is defined. Using the collect statement, single trips
are inserted. Using this statement makes the insertion easy, because it does not have to be
checked whether the corresponding car already appears in the table or decided between the
insertion of a new line and the modification of an existing value.

7.1.8.11.2 Exercise: Collect statement


Create a new program called ZZ_####_KILOMETER. The program shall not have a TOP-
Include and be part of your package and request.

Insert the code of the example above.

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

Afterwards, insert a LOOP and use this loop to create an output based on WRITE statements,
which show the car numbers and kilometer values stored in the table. You can use trip as
your work area. If you are unsure how to implement this LOOP, look at the example on loops
above.

Save, check, and activate your program. Execute your program using the -icon (Test). You
should see the output of the trips.

Figure 50: Kilometer output: SAP-System-Screenshot

Attention: Make sure you did not use different car numbers for all three trips when you
copied the example code above. It is the intention that there are multiple trips for the same
car! Otherwise, you would not see how the COLLECT statement works.

Now put a breakpoint on the line “trip-number = 1” and execute your program using
the -icon (Test). Because of the breakpoint, the debugger will be opened. Double click on
“kilometer_values” in your source code. The table will be observed now and appear on the
right:

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

Figure 51: The internal table in the debugger: SAP-System-Screenshot

To see the table content, double click on KILOMETER_VALUES in this table. The table
view will appear:

Figure 52: Empty table: SAP-System-Screenshot

Continue debugging in single step mode and watch how the content of the table changes
during time.

7.1.8.12 Sorting internal tables

The SORT statement is used to sort internal tables. Its syntax is9:

SORT itab

[STABLE]

[ASCENDING|DESCENDING]

[AS TEXT]

[sort_key].

9
Keller (2102, p. 757 f.)
Page 70
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The keyword STABLE means that the relative ordering of lines, which do not differ in terms
of sorting key values, will be preserved.
Note, that only standard and hash tables may be sorted. Sorted tables cannot be sorted by
SORT, as they already have a fixed sorting.
By adding ASCENDING or DESCENDING, you can explicitly ask for an ascending or
descending search order, respectively. If no such information is present, ascending order is
used by default.
For the sorting, numerical and byte-like components are sorted by their value, while character
based components are sorted according to their internal representation (codepage). A
lexicographic sorting of character components can be achieved by adding AS TEXT.

The sorting key, which specifies which columns should be used to determine the search order,
is given as sort_key. This information is structured as follows:

… BY comp1 [ASCENDING|DESCENDING] [AS TEXT]

comp2 [ASCENDING|DESCENDING] [AS TEXT]

If the sorting key is left out completely, the table key is used as a sort key. The first
component has the highest priority for sorting. The addition ASCENDING, DESCENDING, or
AS TEXT can be provided for each component separately. Otherwise, the previous value
(given before sort_key) will be used.

Further details for the configuration of the sorting can be found in the keyword documentation
of the sort statement. You find this documentation – as usual for all statements – using the F1
key while your cursor is placed on the keyword in the ABAP editor. It is very helpful and
strongly recommended to read this documentation while programming, as not all syntactic
details can be covered in this document.

7.1.8.13 Initialization of internal tables and other data objects

ABAP offers multiple statements to initialize internal tables and other data objects. There are
some differences between the three statements CLEAR, REFRESH, and FREE.10

The CLEAR statement (CLEAR dobj) assigns the type specific initial value. This depends on
the data type and is a null reference for reference variables. Structures are initialized
component by component. All rows of internal tables are deleted. The memory is released
except the initial memory requirement (this is defined in the INITIAL SIZE information
when the table was defined).

The REFRESH statement (REFRESH itab) similarly deletes all lines of an internal table. If
the table has a header line (see next chapter), only the table body but not the header line will
be initialized.

10
Keller (2012, S. 513f., 1500)
Page 71
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The FREE statement (FREE dobj) acts like the CLEAR statement, except for internal tables.
All memory consumed by the lines of an internal table will be released. In structures with
table typed components, the memory of each table typed component will be released. This
implies a bit more work for the system.

Internal tables with header lines will be described in the following section. For them, the
statements act slightly different: REFRESH initializes the body, but not the header line.
CLEAR deletes only the header line. To delete the body, you have to write [] directly behind
the table name. FREE acts on the table body, but not on the header line.

7.1.8.14 Internal tables with header line

A special and a bit old-fashioned variation of internal tables is the internal table with header
lines. Internal tables with header line are defined by adding WITH HEADER LINE at the
table (type) definition. The header line is an automatically generated work area, which has the
same name as the table itself. It is derived from the context whether the name refers to the
table or the header line. Using these tables, the syntax of some table operation becomes
shorter (but also more difficult to understand).

Figure 53: Header line vs. work area

The figure displays the difference: Tab1 has a header line, while there is a separate work area
for Tab2.

7.1.8.14.1 Exercise for internal tables with header line


Create another Program named ZZ_####_HEADERLINE. As usual, the program should not
have a TOP include and be part of your package and request. Add code as follows to your
program:

TYPES:
BEGIN OF str_line,
example TYPE i,
example2 TYPE i,
END OF str_line.

DATA: tab_modern TYPE STANDARD TABLE OF str_line,


wa_modern TYPE str_line,
tab_old TYPE STANDARD TABLE OF str_line WITH HEADER LINE.

tab_old-example = 1.
tab_old-example2 = 1.

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

APPEND tab_old.

tab_old-example = 2.
tab_old-example2 = 2.
APPEND tab_old.

wa_modern-example = 1.
wa_modern-example2 = 1.
APPEND wa_modern TO tab_modern.

wa_modern-example = 2.
wa_modern-example2 = 2.
APPEND wa_modern TO tab_modern.

This code defines two tables: The table tab_modern, which is accessed using the work area
wa_modern, and the table tab_old, which has a header line for accessing its content.
Looking at the APPEND statement, you see the shorter syntax. Similarly, other statements
can be shortened, for example, the LOOP statement. For further information on that syntax,
have a look at the keyword documentation.
If you look at assignments like tab_old-example = 1, you see that the context (here:
access with component selector “-“) determines whether the table or the header line is meant
in a statement.
It is obvious that this code can be difficult to interpret for the reader. Hence it is
recommended to use modern tables without header line in your own programs. Nevertheless
you should know about tables with header lines, because they might appear in existing
programs. Also, selection criteria (taught in the following course part) are represented like
internal tables with header lines. If you are programming in the object-oriented context, as in
the last chapter of this course and most parts of the advanced ABAP course, you will not be
able to use header line tables at all as they are forbidden there.

7.1.8.14.2 Tables with header line in the debugger


Make sure the new debugger is active in your system (cf. section 6.2.5.1). Save, check, and
activate your program. Then, add a (dynamic) breakpoint at the first assignment. Now, test the
program. In the debugger, double click on tab_modern, wa_modern, and tab_old in
the DATA statement. Now, you see the four data objects on the right side of the debugger
window:

Figure 54: The four variables in the debugger: SAP-System-Screenshot

In the column Val., you see that tab_modern is a standard table and wa_modern is a
structure. tab_old is also displayed as a structure (the header line), but you see in the
column left of the Val. Column a hat icon . This icon indicates that tab_old is a table

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

with header line. A double click on the name tab_old would now show the header line like a
usual structure. Instead, double click on the additional TAB_OLD[]. Now, execute the
program in single step mode. You can now watch the table content:

Figure 55: Header line in the debugger: SAP-System-Screenshot

Return to the Object Navigator using the menu path Debugger -> Exit debugger.

7.2 Exercise on internal tables and table types


Open your program ZZ_####_CARS. Create a table type for cars. The type should define a
standard table with the serial number as the key. Create a table using the table type.

Insert the car that you already created in your code into the table. Then, create three more cars
by assigning different values to the components of the work area and inserting it into the
table. You do not need multiple work areas!

Now, add a DELETE statement to delete a specific car (of your choice) from the internal
table.

Replace the existing output by a LOOP, which outputs all cars from the table. Note: In later
chapters of this course, you will learn how to format output like this in a nicer way. Currently,
it is sufficient to print the description before the values as before, e.g., printing
‘Manufacturer:’ before the manufacturer name. Hence, you can reuse the existing code for the
output and just have to add the loop. However, please make sure that an empty line is printed
between different cars, so they can be distinguished properly in the output. For this purpose,
use the statement:

WRITE /.

At the beginning of the loop body, add an output of the value of the sy-tabix system field.

Now, test your program. The output should be similar to the following output example:

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

Figure 56: Output of a program using internal tables: SAP-System-Screenshot

Insert a breakpoint on the second INSERT statement in your code and start the program.
Double-click on the name of the internal table in your source code. The table then appears on
the right side of the debugger. Now, double-click on the table name there. Now, the table will
be displayed with its content:

Figure 57: Table view in the debugger: SAP-System-Screenshot

Continue the program execution in single step mode and watch the content of the table.

Note: If you have to watch multiple tables, structures, and variables in a complex program,
the debugger offers the use of multiple “Desktops,” on which different data objects can be
observed. You can switch between desktops using the tabs above the source code:

Figure 58: Multiple desktops in the new debugger: SAP-System-Screenshot

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

7.3 Excursus: Old vs. new Editor


While writing large loops, lots of source code, many keywords, etc., it can be difficult to get
an overview on your code if you work with the classic editor. In SAP GUI for Windows, there
is a new editor available (which you have most likely already used), which has several
advantages compared to the old one:

 Line numbers next to each line


 Proper syntax highlighting
 Auto completion of keywords (using the Tab key)
 Collapsing of blocks
 Display of changed lines

On non-Windows-GUIs, the new editor is not available.

To switch between both editors, use the menu path Utilities(M) -> Settings and choose the
Tab ABAP Editor. There you can choose the Editor on the tab Editor. The new editor is
called Front-End Editor (New); the old one is called Front-End Editor (Old):

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

Figure 59: Editor choice: SAP-System-Screenshot

Here, you can switch between the two editors. The following figures show the difference
between the editors:

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

Figure 60: Example code in the old editor: SAP-System-Screenshot

The same code looks as follows in the new editor:

Figure 58: Example code in the new editor: SAP-System-Screenshot

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

Using the grey minus symbol, the TYPES block can be collapsed for a better overview. If the
cursor is placed on the first TYPES, BEGIN and END are highlighted in bold font.

The auto completion is visible if you start typing a keyword, e.g., if you write the WHILE
keyword, which is used to define a while loop. After typing W and H, the Editor makes a
suggestion:

Figure 61: Simple auto completion: SAP-System-Screenshot

By pressing the Tab key, the keyword WHILE will be completed. After that, the editor also
proposes to create a pattern for the whole loop:

Figure 62: Completed keyword WHILE: SAP-System-Screenshot

By pressing the Tab key again, the while loop gets completed:

Figure 63: Generated while loop structure: SAP-System-Screenshot

The choice of the editor is kept across multiple sessions, so you have to do it only once.

7.4 Constants
Constant data objects, sort: constants, are data objects whose value does not change during the
execution of an ABAP program. The syntax of their definition is similar to the syntax of
simple data declarations. The value must be specified in the definition.
CONSTANTS const[(len)]
{ {TYPE type_spec}
| {LIKE dobj_spec} }
VALUE { val | {IS INITIAL} }.

It is also possible to use structured types:


CONSTANTS BEGIN OF struct_const.
CONSTANTS...
CONSTANTS END OF struct_const.

7.5 Text symbols


Text symbols are used for the internationalization (i18n) of programs. By using text symbols,
it is possible to replace text literals in programs and show a suitable text according to the
language of the user who accesses the program. The text symbols are assigned to their
Page 79
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

specific program, but they are stored in a separate repository object outside the program, the
text pool of the program. They can be translated into different languages using the menu path
Goto -> Translation from the Text Symbol editor (which is reachable from the ABAP
editor). The text symbols have to be activated separately.

Text symbols are identified by a three-digit alpha-numeric ID. To use a text symbol in a
Program, it is called text-xyz, where xyz is the ID of the text symbol.

Example:
WRITE text-a00.

This syntax is a bit difficult to read, because the three-digit ID does not allow a speaking
name. Due to that, there is another equivalent syntax in which instead of text-xxx, the text
symbol is called as 'My Text'(xxx). The description (“my text”) can be an arbitrary text,
but usually it is the value of the text symbol in the original language of the program.

Example:
WRITE 'Willkommen'(a00).

To create a text symbol, you can choose the menu path Goto -> Text elements -> Text
Symbols from the ABAP Editor, or – which is the fastest way in most cases – you can double
click on the ID in your source code. This navigation (forward navigation) is usable with many
elements in the source code (e.g., global types) and will be an important tool while you create
your programs.

7.6 Parameters
Parameters are a very simple but powerful possibility to give input values to a program. They
are defined similar to other data objects:
PARAMETERS pa_test.

(Note: Their names may have 8 characters at most)

In the example, no type is specified. Hence, like for the DATA statement, the default type C
with length 1 is used.

If a program is called that contains a PARAMETERS statement, the system automatically


generates a graphical user interface in which the corresponding value can be entered by the
user. This user interface is called a selection screen and will be explained in more detail later.

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

Figure 64: Automatically generated selection screen: SAP-System-Screenshot

For the definition of parameters, a data type should also be defined. This is done using TYPE
or LIKE in the same way as for usual data declarations. Parameters can get some further
syntactical arguments to control the visual behavior of the input fields.

The Syntax is as follows11:


PARAMETERS { {para[(len)]} | {para [LENGTH len]} }
[type_options]
[screen_options]
[value_options]
[ldb_options].

Using len makes it possible to determine the length of the field if this is not possible for the
type defined in the type_options (for n, p and x). You should define a length for such
parameters, because, otherwise, the default length (1) will be used.

In the type_options, besides the possibilities for types you already know, you can also
use global types from the ABAP Dictionary, which will be presented in a later chapter. The
parameter can be used within your program just like a usual variable of the type given in the
type_options.

Further options of the statement will be presented in a later chapter of the course. Currently, it
is enough to know how to define a simple parameter and how to use it to realize simple input
for your programs. Later, you will learn how to use select options, which is an even more
powerful concept for input interfaces.

7.7 Comments
There are different ways to include comments in your ABAP code. If a whole line of code
should be commented, you can insert a star symbol at the beginning of the line. You already
know this syntax: The automatically generated comments at the beginning of your programs
use this syntax.
* This is a comment.

If, however, a comment shall be inserted in a line of code at an arbitrary position, this is done

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

by using a double quote ("). The content of the line starting from the double quote will be
ignored by the ABAP compiler. The only exception is a double quote that appears within a
single quoted text literal.
DATA num1 TYPE i. " Declaration of num1

Remember: Text literals are enclosed in single quotes in ABAP, for example: 'Example'
(or `` for Strings)

7.8 The system structure sy / syst


The structure syst or sy contains a number of system variables, which you might need for
your programs.

To have a look at the components of the syst structure, choose the transaction code SE11
(Dictionary) or use the path Tools -> ABAP Workbench -> Development -> Dictionary
from the Easy Access Menu.

Choose Data type and enter SYST into the field next to it. Then, click on the button Display.
Now, you see a list of the components. Have a look at their short description.

After that, leave the dictionary.

You can access these components from your ABAP code using sy-componentname. The
following table shows the most important components:

Component Cotent
sy-datlo Current date of the user
sy-datum Current date of the application server
sy-host Name of the application server
sy-index Number of loop index
sy-langu Language of the user (may be overridden)
sy-lsind Index of the list level (more in the following script part)
sy-mandt Current client
Return code of the last call. Usually
sy-subrc 0 means success, while other values represent errors.
These values are described in the respective keyword documentation.
sy-tabix Index of the last read internal table row
sy-tcode Current transaction code
sy-timlo Local time of the user
sy-uname User name of the current user
sy-uzeit Local time of the application server
Table 3: Components of the sy structure 12

12
Adapted from Keller (2012, pp. 132 ff.)
Page 82
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

You have seen the fields sy-datum and sy-timlo already in the section about data types
for date and time. You have used the sy-tabix field in your program code already.

You know the hyphen notation already from other structures to access their components. It is
roughly comparable to the dot notation that is used in the Java language, but has no object-
oriented context.

7.9 Operators
7.9.1 Arithmetic operators

The next table displays the arithmetic operators that can be used in the ABAP programming
language:

Type / Precedence Operator Operation


Potentation: highest Priority ** Exponentiation of the left with the right operand
Multiplication / Division: * Multiplication of the operands
medium priority / Division of the left operand by the right operand
DIV
Integer portion of the division of the left by the
right operand
MOD
Integer remainder of the division of the left by
the right operand
Addition / Subtraction: lowest + Addition of the operands
priority Subtraction of the right operand from the left
-
operand
Table 4: Arithmetic operations in ABAP

Calculations of operators with higher priority are executed before the execution of operators
with lower priority, provided they are on the same level of bracing. If the priority is identical,
the order given in the rightmost column is used.

When integer numbers are used, all intermediate results are also represented as whole
numbers.

Floating point numbers are represented binary internally. This has the consequence that some
numbers are not exactly representable, as you can see in the following figure.

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

Figure 65: Floating point arithmetic

When dealing with arithmetic expressions, three types of arithmetic can be distinguished:

7.9.1.1 Integer arithmetic

Integer arithmetic uses only whole numbers. This leads to a loss of precision due to rounding
to whole numbers. A division by 0 leads to an exception that can be handled. There is an
exception: 0/0 is 0 by definition in ABAP. Integer arithmetic is used only in cases where no
floating point or fix point numbers appear in the expression being evaluated.

7.9.1.2 Floating point arithmetic

Floating point arithmetic is used for floating point numbers. Because of the above-mentioned
problems of representing decimal numbers in a binary number format, there can be a loss of
precision. Floating point arithmetic is used as soon as one component of an expression is a
floating-point number.

7.9.1.3 Fixed-point arithmetic

The fixed point arithmetic is an arithmetic that is similar to exact calculations with pen and
paper. It is used for fixed point numbers (type p).

7.9.2 Operations on character strings

For character strings, ABAP offers many different operations. The following sections present
the most important ones of them. Some of the operations are also applicable to byte strings.
However, to keep the syntax diagrams simple, the corresponding syntactical parts have been
left out.

7.9.2.1 Concatenation

CONCATENATE a b INTO c.
This operation concatenates the character strings a and b, and saves the result in c. It is
possible to concatenate more than one character string at once. Furthermore, it is possible (but
Page 84
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

not required) to add another character string, which is inserted between two concatenated
character strings. For example:
DATA: t1(10) TYPE c VALUE 'This',
t2(10) TYPE c VALUE 'is',
t3(10) TYPE c VALUE 'a',
t4(10) TYPE c VALUE 'test',
result(20) TYPE c.

CONCATENATE t1 t2 t3 t4 INTO result SEPARATED BY ' '.

The return value (sy-subrc) of the operation is 0 if it was successful and 4 if the variable in
which the concatenated character string should have been stored was not long enough.

7.9.2.2 Searching

FIND a IN b
This operation searches for the character string a in the character string b. If a has been found,
the return value is 0, otherwise it is 4. Additional arguments enable you to search in a specific
part of the character string:
... SECTION [OFFSET off] [LENGTH len] OF...

The offset marks the beginning of the part of b in which the search shall take place, while
LENGTH defines the length of the relevant section. If only an offset is given, the system will
search until the end of the character string is reached. If only a length is given, the offset is
assumed to be 0. However, if the keyword SECTION is present, at least one of the
information has to be provided.

Example:
FIND a IN SECTION OFFSET 2 LENGTH 5 OF b.

By default, the search distinguishes uppercase and lowercase letters. If the casing shall be
ignored, IGNORING CASE has to be added to the Operation:
FIND a IN SECTION OFFSET 2 LENGTH 5 OF b IGNORING CASE.

As described before, the return value does not provide any information about the location of
the search string. To receive this information, MATCH OFFSET c has to be added to the
statement:
FIND a IN SECTION OFFSET 2 LENGTH 5 OF b MATCH OFFSETT c.

Now, the offset of the first match will be stored in c.

An alternative to the FIND operation is the SEARCH operation. This operation is a bit
outdated, as it is not yet able to distinguish uppercase and lowercase letter, and it is also
slower than using find for large character strings. Nevertheless, it offers some possibilities
that cannot be realized using FIND.

The Syntax is:


SEARCH chars FOR pattern [options].
Page 85
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The pattern can be structured as follows:


'mypattern': Searches for the character string ‘mypattern.’ Whitespace at the beginning
or end of the pattern will be ignored.
'.mypattern.': Searches for the exact character string 'mypattern,' whitespace is taken
into account.
'*mypattern': Searches for words that end with ‘mypattern.’
'mypattern*': Searches for words that begin with ‘mypattern.’

The syntax of the search options is:


[STARTING AT position] [ENDING AT position2] [ABBREVIATED] [AND MARK]

By STARTING AT and ENDING AT a range delimiting the search can be specified.

ABBREVIATED leads to a search for words that starts with the same character as the pattern
and contains all other characters of the pattern in the same order, but at arbitrary positions of
the word.

AND MARK causes the found character string to be converted to uppercase letters.

Example:
DATA text TYPE string VALUE 'The wonderful example'.
SEARCH text FOR 'wdrf' ABBREVIATED AND MARK.

After the execution, text has the value 'The WONDERFUL example'.

7.9.2.3 Replacing characters

The REPLACE operation can be used to replace parts of a character string13.


REPLACE {
SECTION [OFFSET off] [LENGTH len] OF
|
[{FIRST OCCURRENCE} | {ALL OCCURRENCES} OF]
sub_string
IN [SECTION [OFFSET off] [LENGTH len] OF]
}
text WITH neu [case_option]
[pos_len].

Using the SECTION addition, a section can be defined which should be subject to the
replacement.
The sub_string addition is used to provide a search pattern, which defines the position of
the replacement.

FIRST OCCURRENCE replaces the first occurrence only, while ALL OCCURRENCES
causes all occurrences to be replaced. Syntax and semantics of the section_of part are
similar to those of the FIND operation.

The case_option is also similar to the one from FIND.


13
Cf. Keller (2012, pp. 561 ff.)
Page 86
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

pos_len is used to determine the number, position, and length of hits during pattern-based
search. The syntax is:
... [REPLACEMENT COUNT num]
[REPLACEMENT OFFSET offset]
[REPLACEMENT LENGTH len]...

In num, the number of hits is stored (number of replacements). offset contains the offset
value of the last hit and len contains its length. If the pattern is not found, all variables keep
their values.

7.9.2.4 Split character strings

The SPLIT statement is used to split a character string into multiple parts based on a dividing
character. The syntax14 is:
SPLIT text AT divider INTO {{result1 result2 ...} | {TABLE result_tab}
} .

The character string text will be searched for the dividing character divider. The content
of text from its beginning to the first hit, the part of text between the hits, and the part
between the last hit and the end will be stored in the variables result1, result2, etc., or
stored in an internal table result_tab.

Example:
SPLIT 'John Peter Doe' AT ' ' INTO firstname secondname lastname.

Here, firstname would have the value 'John', secondname would have the value 'Peter,'
and lastname would have the value 'Doe'.

If the number of variables is not sufficient to store all parts, all but the last will be filled with
the corresponding parts and the remaining text will be assigned (un-split) to the last variable.

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

7.9.2.5 Condensing character strings

The CONDENSE statement removes whitespace at the beginning and at the end of a character
string. Additionally, it replaces multiple whitespace characters occurring directly after another
by just one. If the addition NO-GAPS is given, all whitespace will be removed.

Example:
DATA text TYPE c LENGTH 20 VALUE ' this is an example '
CONDENSE text NO-GAPS.

Here, text receives the value 'thisisanexample'.

7.9.2.6 Translate character strings

The TRANSLATE statement can be used to transform characters of a character string. The
syntax is:
TRANSLATE text { case | using }.

With case, the casing of the character string can be changed. TO UPPER CASE changes all
characters into uppercase letters, and TO LOWER CASE transforms them into lowercase.

7.9.3 Operators for comparison


7.9.3.1 Comparison of arbitrary data types

The following comparison operators are provided by ABAP for all data types.

Equal (= or EQ)

The expression is true if the value of the left operand is equal to the value of the right
operand.

Not Equal (<> or NE)

The expression is true if the value of the left operand is not equal to the value of the right
operand.

Lower Than (< or LT)

The expression is true if the value of the left operand is lower than the value of the right
operand.

Greater Than (> or GT)

The expression is true if the value of the left operand is greater than the value of the right
operand.

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

Lower Equal (<= or LE)

The expression is true if the value of the left operand is lower than or equal to the value of the
right operand.

Greater Equal (>= or GE)

The expression is true if the value of the left operand is greater than or equal to the value of
the right operand.

It is recommended not to mix the notation, i.e., either to use the operators =, >, etc., only or to
use EQ, NE, LT, etc., only.

The meaning of comparison operators for character strings is: 'aaa' > 'aa', 'bbb' >
'aaa', etc.

7.9.3.2 Comparison operators for character types

The following operators are provided specially for character types.

Contains Only (CO)

The expression is true if the left operand contains only characters that are also part of the right
operand. Casing is taken into account.

Contains Not Only (CN)

The expression is true if the left operand contains not only characters that are also part of the
right operand. Casing is taken into account. This is the opposite of the CO operator.

Contains Any (CA)

The expression is true if the left operand contains at least one character that is also part of the
right operand.

Contains Not Any (NA)

The expression is true if the left operand contains no character that is also part of the right
operand. This is the opposite of the CA operator.

Contains String (CS)

The expression is true if the left operand contains the right operand. Casing is not taken into
account.

Contains No String (NS)

The expression is true if the left operand does not contain the right operand. This is the
opposite of the CS operator.

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

Covers Pattern (CP)

An expression with the CP operator is true if the content of the left operand matches the
pattern given in the right operand. In the right operand, arbitrary characters can be used. *
represents an arbitrary character string, + represents an arbitrary character. Casing is not taken
into account, except for characters that are preceded by a sharp sign (#) in the right operand.

No Pattern (NP)

The opposite of the CP operator.

7.10 Control structures


7.10.1 Unconditional loops

An unconditional loop is written with the keyword DO in ABAP. The syntax is as follows:
DO [n TIMES].
[statement_block]
ENDDO.

If the addition n TIMES is missing, the loop runs infinitely often, until the maximum
runtime of the program has been reached. Instead, it should be left using the EXIT statement
in the statement_block.
If the addition is present, the loop is executed as often as indicated by n at the beginning of
the loop (Changing the value of n during loop execution has no effect).

The number of the current loop iteration can be retrieved from the system field sy-index.
The numbering begins with 1 and is always related to the current (inner) loop if there are
nested loops. To access the index of an outer loop, it has to be stored in a variable.

Example for a DO loop:


DO 5 TIMES.
WRITE sy-index.
ENNDO.

Do not forget the dot after TIMES. If you leave it out, the compiler will expect a VARYING
expression. The corresponding error message may be confusing for beginners.

7.10.2 Conditional loops

For conditional, header-controlled loops, the keyword WHILE is used in ABAP. The syntax is
(similar to the DO-loop) as follows:
WHILE log_expr.
[statement_block]
ENDWHILE.

The statement_block is executed as long as the logical expression log_expr is true or


until the loop is interrupted by the EXIT statement.

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

Like for the DO loop, sy-index provides the number of the current loop iteration.

7.10.3 Loop for internal tables

Internal tables can be iterated using a LOOP loop. In each iteration, an entry of the table is
loaded into a work area. You already know this type of loop from section 7.1.8.10.1.

7.10.4 Loops for database tables

There is another kind of loop for reading data from the database. This will be presented later.

7.10.5 Leaving loops

There are three statements to leave a loop independent of the numbers of iterations or logical
expressions specified in the loop header.

7.10.5.1 The EXIT statement

Using the EXIT statement, it is possible to leave a loop immediately. If the statement is used
outside a loop, the current execution block will be left.

7.10.5.2 The CONTINUE statement

Using the CONTINUE statement, you can leave the current loop iteration. The loop will be
continued with the next loop iteration.

7.10.5.3 The CHECK statement

The CHECK statement is similar to the CONTINUE statement, but it contains a condition, so
the current loop execution will only be left if this condition is true.

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

7.10.6 Conditional branches


7.10.6.1 The IF construct

The IF construct should not be new to you, as it is a very common construct that appears in
many different programming languages. In ABAP, it has the following syntax15:
IF log_expr.
[statement_block]
[ELSEIF log_expr2.
[statement_block2]]
...
[ELSE.
[statement_blockn]]
ENDIF.

Depending on the logical conditions, at most one statement block statement_block1 to


statement_blockn will be executed. The logical conditions will be checked one after
another until a true expression has been found, and whose statement_block will then be
executed. If all logical expressions are false, the statement block of the ELSE part will be
executed. The logical operators AND and OR can be used to connect complex expressions.
Braces can also be used.

Example:
IF z = 6.
WRITE 'Z is 6'.
ELSEIF z = 5.
WRITE 'Z is 5'.
ELSEIF z < 5.
WRITE 'Z is less than 5'.
ELSE.
WRITE 'Z is greater than 6'.
ENDIF.

7.10.6.2 The CASE construct

Branchings with many ELSEIF parts can be written in a more convenient way using the
CASE construct. The syntax is as follows:
CASE operand.
[WHEN operand1 [OR operand 2 [OR operand3] [...]]].
[statement_block1] ]
...
[WHEN OTHERS.
[statement_blockn] ]
ENDCASE.

The system searches top-down to find a branch where the operand operand matches one of
the other operands. For the first match, the corresponding statement_block is executed.

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

If there is no match, the WHEN OTHERS block will be chosen. In both cases, the execution
flow will be continued after ENDCASE.

Note that there is no specification whether one of the operands should be a variable or a
literal, as opposed to some other programming languages.

Example 1: Variable in CASE, literal in WHEN:

PARAMETERS num TYPE i.

CASE num.

WHEN 1.

WRITE 'You entered a one.'.

WHEN 2.

WRITE 'You entered a two.'.

WHEN OTHERS.

WRITE 'You entered something different.'.

ENDCASE.

This is the usual way a CASE statement is used: Depending on the value of a variable, a
suitable action is chosen.

Example 2: Literal in CASE, variable in WHEN:


PARAMETERS: num1 TYPE i,num2 TYPE i.

CASE 1.

WHEN num1.

WRITE 'You entered a one in num1'.

WHEN num2.

WRITE 'You entered a one in num2, but not in num1'.

WHEN OTHERS.

WRITE 'No one was entered'.

ENDCASE.

This situation is a bit less common. It is assumed that a certain value is stored in one of the
given variables. Here it is checked in which variable the value 1 is stored. Note that if 1 is the
value of num1, the value of num2 ha no influence on the output.

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

7.11 Modularization in ABAP


Modularization is used when parts of a program with a certain functionality are encapsulated
in specific modularization units. There are two main reasons for modularization of programs.
Firstly, complex programs can be structured by modularization and are, therefore, easier to
maintain. The second reason is the ability to reuse components of one program in another
program. Functionalities that are required for many programs have to be implemented just
once and can be maintained at a central place. The time-consuming task to fix a bug, which
occurs in many different programs, can become obsolete.

ABAP offers different possibilities of program modularization. The following sections


describe three types:

Include Files for a simple source code modularization,

Subroutines (Form routines) for (usually) local sub programs and

Function modules for functionality shared among programs.

Methods of local and global classes can also be used as a local or global modularization unit,
respectively, but global classes are not covered in this course. They are discussed in detail in
the advanced course. Local classes will be discussed at the end of the course.

7.11.1 Include files

Include files are used to store code sections in separate repository objects. They represent a
special program type. When they are created, the program type INCLUDE program has to
be selected instead of Executable Program. It is also possible and convenient to create
includes directly from the calling source code using forward navigation.

An include program does not contain the header lines of a usual program. Instead, it contains
only those lines of codes that were taken out of the original program. These lines of code do,
therefore, not have to be complete. Include programs cannot be executed on their own. They
are included in other programs using the INCLUDE statement.

The syntax for including an include program is quite simple:


INCLUDE includename [IF FOUND].

includename is the name of the program that should be included. During syntax checking
of the calling program, at the position of the include statement, the code lines of the include
are taken into account.

The option IF FOUND makes it possible to insert the content of an include only if this
include exists. Otherwise, the execution continues.
Include programs may contain include statements themselves. It is also possible to put the
first line (PROGRAM…) of an executable program into an include, but that affects the
readability and is, therefore, not recommended.

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

7.11.1.1 Example include

Create a new program in your package ZZ_####. The program shall be named
ZZ_####_VAT and have no TOP include. Save the program and choose your request as you
did for the other programs.

Figure 66: Creating a program: SAP-System-Screenshot

The task of this program is a simple calculation of a total amount based on a net amount plus
value added tax. Add a parameter to your program (using the PARAMETERS statement)
named net. Use a packed number with two decimals as the type (cf. section 7.1.1.9).
Furthermore, define a data object (variable) of the same type named total. Use the DATA
statement for this.

Now, calculate the total amount based on the net amount and a VAT value of your choice.
Afterwards, display net value, VAT and total value. Save, check, and activate your program.
If you test your program, you should first see an input mask (a selection screen) where you
enter an arbitrary test value:

Figure 67: Input of net value: SAP-System-Screenshot

Commit your input using F8 or . You will see your output, which should look similar to
the following figure:

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

Figure 68: Output of the VAT program: SAP-System-Screenshot

If you do not manage to get your program to work immediately, look back to the previous
sections and chapters. It is normal that you make mistakes when you are new to ABAP. If you
are finished, have a look at the following example code.

Figure 69: Solution example: SAP-System-Screenshot

The calculation of the total amount shall now be put into an include file.

Right click on your program ZZ_####_VAT in the navigation tree of the object navigator and
choose the context menu path Create -> Include. Name your include ZZ_####_VAT_INCL
and save the include. Commit the package and request dialogues as usual. You will see a
message like this:

Figure 70: Notice about INCLUDE statement: SAP-System-Screenshot

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

Commit this message. Now, add the line that calculates the total amount to the include. Then
save and activate the include. During activation, you will see this window:

Figure 71: Inactive objects: SAP-System-Screenshot

The system informs you that multiple repository objects are inactive. In this case, it is your
include that you just edited and the main program, because the system inserted the include
statement there. Usually, in such situations, you should activate all listed objects. You can
select all lines separately by clicking on the empty button at the beginning of each line ( ),
or by using the icons at the bottom of the window to quickly select/unselect all items
( ). Activate both items by selecting and committing.

If you open your program ZZ_####_VAT, you will see that the statement mentioned in the
message some moments ago has been added to your code:

Figure 72: Include statement: SAP-System-Screenshot

However, the new line has been inserted at the end of your program, which is obviously not
what we need. Remove the line that was responsible for the calculation so far, and move the
include statement to this place.

If you save, check, and activate your program again, it should act as before, but the
calculation takes place in the include instead of the main program.

The drawback of this kind of modularization is the missing encapsulation of data. The
modularization unit, here: the include, directly accesses data objects of the main program.

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

7.11.2 Subroutines (form routines)

Subroutines, or form routines, are sub programs of ABAP programs. They are used for local
modularization. Theoretically, it is also possible to call them (from other programs), but this is
regarded as bad programming style. As a local modularization unit, they are part of the main
program. Today, subroutines are a deprecated functionality, because, e.g., object-oriented
concepts provide better possibilities for modularization.

To be able to use the subroutine dependent on the current situation with different data objects,
the subroutine should not use global data objects of the main program. Nevertheless, this is
technically possible. Instead, all data should be exchanged using a defined interface using
placeholders called parameters. The defined placeholders of the subroutine are called formal
parameters. During execution, concrete values are assigned to these parameters, which are
called actual parameters. This process is called parameter passing.

The syntax to define a subroutine is:


FORM subroutine_name [parameters]
[RAISING exception1 exception2 exception3 ...].
...
ENDFORM.

Hereby, a subroutine named subroutine_name and its interface is defined. The code of
the subroutine is inserted at the “…” in the above syntax.

The parameters part represents the description of formal parameters. RAISING allows to
define exceptions that can be propagated from the subroutine to the calling program.
Exceptions will be explained in more detail later.

The syntax of the parameter part is as follows16:


... [ USING { { VALUE(u1) | u1 } [typing | structure ]
{ VALUE(u2) | u2 } [typing | structure ]
... } ]
[ CHANGING { { VALUE(c1) | c1 } [typing | structure ]
{ VALUE(c2) | c2 } [typing | structure ]
... } ] ...

Here, the parameters u1, u2, ... and c1, c2, ... are defined. They can be used inside the
subroutine just like usual data objects. Different ways to pass parameters can be
distinguished:

7.11.2.1 Call by reference

If not marked differently, parameters are only referenced from the subroutine. Changes of the
formal parameters in the subroutine hence influence the actual parameters of the calling
program directly.

16
Keller (2012, p. 1425 f.)
Page 98
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

The addition CHANGING should be used for those parameters that are being changed during
the execution of the subroutine.

7.11.2.2 Call by value

If the parameter should be passed as a value instead, the parameter has to be specified as
VALUE (parametername) in the subroutine interface. This ensures that a variable is
created for the parameter in the subroutine and the value of the actual parameter is copied to
this variable. The value of the actual parameter is not changed.

If, however, the addition CHANGING is used, the value of the actual parameter can be
changed if the subroutine is left using ENDFORM, RETURN, CHECK, or EXIT. This is called
call by value and result.

Note that copying large data objects may be time-consuming.

7.11.2.3 Typing

Typing makes it possible to check the type of the actual parameter. The syntax is similar to
the syntax of type definitions described above.

Typing by structure is obsolete and will not be discussed here.

The advantage of typing is that incompatible types are already detected during syntax
checking. This makes it possible to detect type conflicts and to avoid type conflicts during
runtime, e.g., if, by accident, a character string shall be assigned to a parameter for which a
number is expected. If one of the standard types P, N, C, or X is used, the missing length
information is passed at runtime. If a structure or an internal table shall be passed to a
subroutine, typing is strictly required to be able to access the components from within the
subroutine.

7.11.2.4 Propagating exceptions

The RAISING keyword in the subroutine interface is used to define exceptions, which may
be propagated to the calling program. They are given in ascending order of their inheritance
hierarchy. Exceptions will be explained in detail later.

7.11.2.5 Calling subroutines (form routines)

Subroutines are called using the PERFORM statement. It has the following syntax:
PERFORM subr_identifier [parameter_list]

subr_identifier is the name of the subroutine, which has been defined after the FORM
keyword. However, ABAP also offers a way to call subroutines dynamically from the current
program or from other programs.

For the dynamic call, instead of the subroutine name subr_identifier, a variable in
braces is given, e.g., (subrname), which contains the name of the subroutine in uppercase
Page 99
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

letters at runtime. To call a subroutine from a different program, IN PROGRAM prog is


added to the statement, where prog is the name of the other program. Also, instead of prog,
the name of the program can be given as a variable in braces, e.g., (progname), which
contains the name of the program in uppercase letters at runtime. Calling subroutines from
other programs is not recommended due to stylistic reasons.

Parameter passing takes place in the parameter_list, which has the following syntax:
... [USING a b ...]
[CHANGING a b ...] ...

These lines assign actual parameters to the corresponding formal parameters. They need to
have a matching data type. The assignment to the USING and CHANGING part is not required
from a technical point of view, as the kind of parameter passing is already defined by the
FORM definition, but it is strongly recommended due to documentation reasons.

For the assignment between formal and actual parameters, the order of parameters is relevant.
Be careful: There is no additional “VALUE..” here.

7.11.2.6 Visibility

If a data object or a formal parameter is defined in a subroutine whose name is equal to a


global data object, this name is always associated to the local data object or parameter within
the subroutine. The global data object is “shadowed.” Having a local data object with the
same name as a formal parameter is not allowed. Global data objects are visible inside
subroutines in general.

7.11.2.7 Subroutine example

For this exercise, create a copy of your existing program ZZ_####_VAT. For this purpose,
right click on the program ZZ_####_VAT in the navigation tree and choose Copy. Enter
ZZ_####_VAT2 as Target Program.

Figure 73: Copying a program: SAP-System-Screenshot

Commit the following window and proceed, as always, with your package and request.

Open the new program ZZ_####_VAT2 and change it so that there is a second parameter
vat to enable the user to enter the current VAT (as a percentage, e.g., 19 for 19 % VAT).
Replace the line in which the include was called by the following calculation of the total
value:

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

Make sure your program displays the vat value, which was entered by the user.

Save, check and activate your program. Then test it – the VAT is now a parameter that can be
determined by the user.

Figure 74: Output of the program: SAP-System-Screenshot

Now, add a subroutine called calculation at the end of the program. The subroutine shall
have three parameters: basevalue, percentage, and result. All parameters shall have
the type packed number. The parameters basevalue and percentage shall be passed by
value. The result parameter shall be passed by value and result.

For the body of the subroutine, you can adapt the line of the program that was responsible for
the calculation so far. You just have to replace the variable names by the appropriate
parameter names. The subroutine should now look like this:

Figure 74: Revised source code: SAP-System-Screenshot

To use the subroutine, you first have to remove the old calculation line from the main
program. You could now manually write the PERFORM statement at this position, but this
would be dangerous for large subroutines, because it is easy to make mistakes here. Instead,
you will use drag-and-drop. First, save, check, and activate your program. If you extend the
part of the navigation tree of the Object Navigator, which belongs to your program
ZZ_####_VAT2, you will see a sub folder Subroutines that you can also extend. There you
will see your subroutine CALCULATION. If this part of the tree is missing, refresh the tree
using the -icon above the tree.

Figure 75: Subroutine in the navigation tree: SAP-System-Screenshot

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

Now, click on the entry CALCULATION, drag it to your program (to the former position of
the calculation) and drop it there. Now, you see a pattern for calling the subroutine:

Figure 76: Subroutine call pattern: SAP-System-Screenshot

Behind USING and CHANGING, you still see the names of the formal parameters. Replace
these names by the corresponding actual parameter names that shall be used for the
calculation.

Save, check, activate and test your program now. It should work as before, but the difference
is that the calculation of the total value is done in a subroutine, which could be reused.

Now, start the debugger by choosing the menu path Program -> Execute -> Debugging.
Enter arbitrary values for net value and VAT and commit. Execute the program in single step
mode using F5 or the -icon, until you reach the line in which the PERFORM statement is
located. If you apply another single step, the debugger will step into the subroutine. If you
choose Execute (F6 or the -icon) instead, the subroutine will be executed directly and the
execution continues after the subroutine call.

From within a subroutine, you can leave by a Return statement. If you want to test this, you
first have to extend the functionality of the subroutine, because it currently contains only one
line, and there would not be any difference if there were a return statement after this line.

7.11.3 Function modules

Function modules are procedures that can be reused independent of the program for which
they were created. They are organized (grouped) in function pools.

Sometimes function modules are simply called functions. They can be created easily using the
Object Navigator (and the Function Builder), because all properties like name, parameters,
and return value can be configured in a graphical user interface here. A source code pattern is
then created automatically.

Function modules encapsulate source code and cannot access variables of the calling program.
The exchange of data happens only based on parameters that have been defined in the
function module interface. As function modules are visible in all programs, it is clear that the
name of the function module has to be unique in the whole system. There are already more
than 100000 predefined function modules in the SAP system.

Special function modules are remote-enabled function modules, which are accessible by web
services and BAPIs (Business Application Programming Interfaces), which represent
functions that are encapsulated based on business criteria. An overview of BAPIs is available
from the transaction BAPI (the BAPI Explorer).

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

All function modules are assigned to function groups (also called function pools). A
function group should contain all function modules that offer a related function and work on
the same data.

Figure 77: Depiction of a function group

The figure above should not lead to the assumption that function group contains three
function modules at most. The number of 3 modules is just used as an example for illustration
purposes.

The function group can contain global data that can be accessed by all function modules of
the function group. When one of the function modules is called, the whole function group is
loaded and remains in the memory until the calling program is closed. During this time, global
data of the function modules is kept and can be used by other function modules17.

Furthermore, a function group can contain global subroutines and screens that can be used by
all function modules of the group. The figure above illustrates that access to the function
modules is always performed using its interface.

7.11.3.1 Function module interfaces

The interface of a function module can contain the following elements. All of them can be
configured using the Function Builder.

 Import parameters: They are used to transport values or variables from the calling
program to the function module. Import parameters may be marked as optional. In this
case, they do not have to be given when the function module is called.

17
Keller and Krüger (2011, p. 462)
Page 103
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

 Export parameters: These parameters are always optional. They are used to return
results of the function module back to the calling program. When a function module is
called, a variable is given which shall receive the result of the function module.
 Changing parameter: Changing parameters are used to give variables to the function
modules that may be changed there.
 Exceptions: In case of a failure during execution of the function module, exceptions
may be defined that allow the error to be treated by the calling program (e.g., by
displaying an error message).

7.11.3.2 Calling function modules

To call a function module from an ABAP program, the statement CALL FUNCTION is used.

The syntax is as follows18:


CALL FUNCTION func { parameter_list | parameter_tables }.

The call of a function module is always dynamic. This means that func is not the name of
the function module. Instead, it can be a character string (a literal) containing the name of the
function module or a character-based variable whose value represents the name of the
function module at runtime.

Passing the parameters is possible in a static way using the parameter_list or in a


dynamic way using parameter_tables.

7.11.3.3 Static parameter passing

The syntax of parameter_list from the above syntax diagram is:


... [EXPORTING p1 = a1 p2 = a2 ...]
[IMPORTING p1 = a1 p2 = a2 ...]
[CHANGING p1 = a1 p2 = a2 ...]
[TABLES t1 = itab1 t2 = itab2 ...]
[EXCEPTIONS [exc1 = n1 exc2 = n2 ...]
[error_message = n_error]
[OTHERS = n_others]
]...

Here, the EXPORTING, IMPORTING, or CHANGING formal parameters p1, p2, ... are
assigned to corresponding actual parameters a1, a2, …

With TABLES, the non-optional table parameters t1, t2, ... of the function module are
assigned to internal tables itab1, itab2, ... of the calling program. This is done by using
pass by reference.

The EXCEPTIONS is used to assign return values to exceptions. These return values can be
retrieved later using the system variable sy-subrc.

18
Keller (2012, S. 340 ff.)
Page 104
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Similar to the call of the subroutine, it is also possible to generate a pattern for a function
module call. All required information about parameters and exceptions is available from the
interface and can be used to create the pattern. Remember the exercise about the pattern
button from above.

7.11.3.4 Dynamic parameter passing

The syntax of parameter_tables is:


... [PARAMETER-TABLE ptab]
[EXCEPTION-TABLE etab] ...

Here, ptab and etab are internal tables. ptab is used to assign formal parameters of the
function module to actual parameters of the program. This requires the use of sorted tables of
type ABAP_FUNC_PARMBIND_TAB with lines of type ABAP_FUNC_PARMBIND. They
are defined in the tpye group ABAP. You can view them in the ABAP Dictionary (transaction
code SE11) if you enter the type group name there. You should not try to change anything
there! In the source code, you can see how these types are defined.

The columns of the table are:

NAME: The name of the formal parameter in uppercase letters

KIND: The type of the formal parameter, which is given by one of the constants defined in a
type group: ABAP_FUNC_EXPORTING for input parameters, ABAP_FUNC_IMPORTING
for output parameters, ABAP_FUNC_CHANGING for I/O parameters and
ABAP_FUNC_TABLES for table parameters.

VALUE: This field is used as a reference to the actual parameter.

TABLES_WA: Used as a reference if KIND is ABAP_FUNC_TABLES.

7.12 Exercise on basic concepts


In this exercise, you will use some of the basic concepts shown before in simple exercises.

After you meet the favorites menu of the Object Navigator, you will use data declarations and
data manipulation. Then, you will process user input by using a selection screen. You will
also use modularization when the functionality of your program will be put into a function
module. Finally, BAPIs will be used.

7.12.1 The favorites menu

If you use the Object Navigators frequently, it can be somewhat of an annoying task to often
navigate back to your package or to jump to a program you use very often. This could be your
HELLOWORLD program from the beginning, for example, if you want to test some
statements. To make these scenarios easier, the Object Navigator offers a favorites function,
similar to the one you know from the Easy Access Menus.

To get in touch with the favorites menu, you will create entries for your package and your
HELLOWORLD program.

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

Click on your package in the navigation tree so that it gets highlighted:

Figure 78: Selecting your package: SAP-System-Screenshot

To add the package to the favorites menu, click on the favorites -icon and select add.

Figure 79: Adding a favorite: SAP-System-Screenshot

You will see a message confirming your favorite addition:

Figure 80: Commitment: SAP-System-Screenshot

Now, select your program ZZ_####_HELLOWORLD and add it similarly to the favorites
menu using the favorites symbol.

Now, open the favorites menu and select your program:

Figure 81: The favorites menu: SAP-System-Screenshot

Afterwards, you see your program as the root node in the navigation tree of the Object
Navigator, and you can open it by double-clicking on it. To jump back to your package, you
can use the favorites menu again or use the -button.

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

You can use the favorites menu during the course at all places where you think it might be
helpful for you. If you want to remove an entry from the favorites menu, you can choose the
entry Edit from the favorites menu. The following window will be displayed:

Figure 82: Editing favorites: SAP-System-Screenshot

Here, you can select an entry and click on to delete it.

7.12.2 Selection screens and control structures

For this exercises, create a new program called ZZ_####_CALCULATOR. If you are unsure
how to create new programs, go back to the previous exercises to find out. This program shall
be used to implement a simple calculator, which is able to add, subtract, multiply, divide, or
modulo divide two numbers.

The graphical user interface shall be realized by a selection screen. Insert the parameters
operand1, operand2, and operator into your program using the PARAMETERS
statement. They shall be typed as integers. The operator shall be typed as a c with a length of
1. Use chained notation for your code.

After defining the parameters, save, check, and activate your program, then test it.

On the selection screen, the input fields are described by their technical name. They may still
be understandable here as the sense of the parameters is clear from their names, but in
general, it leads to messy interfaces. However, of course it is possible to change the names
displayed on the screen. Get back to the ABAP editor and choose the menu path Goto -> Text
Elements -> Selection Texts. There you can enter texts that should be displayed on the
selection screen (see the following figure).

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

Figure 83: Entering selection texts: SAP-System-Screenshot

If your parameters do not appear here, you probably have not activated your program. You
can see checkboxes for a connection to the dictionary. This is not required for now, but later
you can use this functionality to retrieve the descriptions directly from the ABAP Dictionary
by activating this checkbox. For now, simply add suitable texts manually. Save and activate
the selection text before returning to your program.

Depending on the operator (+,-,*,/, or % as a shortcut for modulo division), the operands shall
be added, subtracted, multiplied, or divided, and the result shall be printed on the screen. Use
a CASE construct (see section 7.10.6.2), which distinguishes the operator and chooses a
suitable calculation. You do not have to care for inconsistent input for the moment. Note,
however, that you must use the Operator MOD in ABAP to calculate the modulo division; the
% is just what the user enters.

Define a variable for the calculation result using the DATA statement and type i. The
declaration has to be done before your CASE structure to make the variable available inside.
After the CASE structure, add an output of the result using the well-known WRITE statement.

Save, check, and activate your program. If a window appears that offers multiple objects to be
activated, you have more than one inactive object, e.g., you did not activate the selection texts
yet. In this case, mark all entries by clicking on the empty buttons at the beginning of the lines
or using the F9 key. Commit the activation.

Now, test your program. The user interface should show your selection texts now, like in the
following example:

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

Figure 84:User interface of the program: SAP-System-Screenshot

Make sure your program is able to calculate correctly. For this purpose, enter suitable
example data and commit using the F8 key. The result could look like this, for example
(depending on your WRITE statements):

Figure 85: Output of the result: SAP-System-Screenshot

7.12.3 Implementing a function module

For the next step, the functionality of your calculator shall be put into a function module. As
described above, each function module has to be assigned to a function group. This function
group has to be created first. For this purpose, right click on your package to open the context
menu (if the package is not visible, navigate to the package first by using the favorites menu).
From the context menu, choose Create -> Function Group. Name your function group
ZZ_####_FGR and choose a suitable short text. The following commitments are similar to
those when creating a program; you also have to specify package and request.

A new entry Function Groups appears in the Repository Browser navigation tree. Within this
sub tree, you will find the function group you just created. Right click on the function group
and choose Create -> Function Module. Name your module Z_####_F_CALC.

Note that the naming scheme is a little bit different here. If you accidentally entered ZZ
instead of Z at the beginning, you will see a warning that your function module is part of the
SAP namespace. This can lead to problems during the activation of the function module. If
Page 109
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

this happened to you, double-click on your program ZZ_####_CALCULATOR, then right


click on the wrong function module, and choose rename. Now, you can change the wrong
name. After that, click on the function module again.

On top of the screen, you see different tabs. They are used to access the different settings of
the function module in a convenient way. Start with the tab Import. Here, the importing
parameters are defined.

Choose the parameter names IM_OPERAND1, IM_OPERAND2, and IM_OPERATOR, the


type i for the operands and type c for the operator. Choose the typing TYPE and enter the type
in the Associated Type column (see the following figure).

Figure 86: Parameters of the function module: SAP-System-Screenshot

In the Export tab, analogously define the export parameter EX_RESULT of type i. Check the
Pass Value checkbox, too.

Switch to the tab named Source code. There you can already see the defined interface. Note,
however, that this is only a comment displaying the configuration of the function module
interface. You cannot change anything here; you have to use the corresponding tabs instead.

Figure 87: Predefined comments: SAP-System-Screenshot

Save your function module and add the code to calculate the result here. For this purpose, you
can move (cut and paste) the CASE structure from your program ZZ_####_CALCULATOR
into the function module. However, you must change the names of the respective variables
Page 110
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

(e.g., IM_OPERAND1 instead of OPERAND1), because the function module is independent of


your program and can only receive and return data based on the parameters in its interface.
You can use the search and replace functionality, which is available from the menu path Edit
-> find/replace or by pressing Ctrl-F. Save, check, and activate the function module.

As function modules do not depend on a specific program, they can also be tested on their
own. This is possible by an integrated tool inside the ABAP Workbench, which automatically
generates simple input fields for a test. Note, however, that these input fields have nothing in
common with your PARAMETERS-Definitions in your program (note: the term “parameter”
is ambiguous in the ABAP world, as it may refer to a PARAMETERS statement in an ABAP
program, as well as to a parameter in the interface of a modularization unit). Start the test by
clicking on .

Figure 88: Automatically generated mask for testing: SAP-System-Screenshot

You see an automatically generated input mask where you can enter test values manually.
Commit your input by F8 or .

Afterwards, the runtime and the input and output parameters are displayed:

Figure 89: Result of the function module test: SAP-System-Screenshot

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

Make sure that your function module itself does not contain any output. Hence, it should not
contain any WRITE statements. Its purpose is only the calculation, while the output will still
take place in the main program, after it has been changed to use the function module.

After you have completed the test, return to your main program ZZ_####_CALCULATOR.
There, the CASE structure shall be replaced by a call to the function module. If you have not
yet removed the structure during the cut and paste to the function module, remove the whole
CASE- structure from the source code now, but keep the WRITE statements.

You could now enter the CALL FUNCTION statement to call the function module, but this is
a lot of work and may lead to errors. For simplification, you will use the Pattern button
instead. Click on this button and enter the name Z_####_F_CALC of your function module in
the appearing window next to CALL FUNCTION and select the corresponding radio button
on the left. You will see a pattern for the CALL FUNCTION statement. Optional parameters –
in this case, the EX_RESULT parameter – are commented.

Uncomment it by removing the stars at the beginning of the lines. Add the local variables on
the right side of the equations. Note that the assignment of EXPORTING and IMPORTING is
done from the perspective of the calling program – in the function module, the assignment is
the other way around.

In the EXPORTING block of the call, the Import parameters of the function module receive
their values.

In the IMPORTING block of the call, the Export parameters of the function module are
assigned to their actual parameters.

Also note that the actual parameter is always on the right side of the equation, so this equation
may not be read as a typical left-to-right-assignment. This helps to get a common display, but
might be confusing at the beginning, as the result is not written to EX_RESULT. Instead, the
value of EX_RESULT is stored in the actual parameter.

At the end of the “equation” part, there is no dot or comma, there is only one dot at the end of
the whole CALL FUNCTION statement, i.e., after the local result variable there is a dot.
Don’t let the system confuse you: In the pattern-generated code, this dot is placed in a
separate line.

Save, activate, and test your program. It should work as before, but the functionality of
calculation is now executed by a function module. This is advantageous, because a different
Program that also needs the functionality of a calculation could also use the function module.
This saves the effort of implementing and maintaining the corresponding code redundantly.

Especially when you create function modules that should be reused in multiple applications, it
is important to provide some kind of documentation. In the SAP system, there is a separation
into a Function Module Documentation, which describes the functionality of the whole
module, and a Parameter Documentation, in which the meaning of each parameter of the
module and the exceptions are explained.

Open your function module by using forward navigation: Double-click on the name of the
function module inside the source code of your main program. Make sure you are in change
Page 112
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

mode. Using the -button, you can access the Function Module
Documentation. Add some description here, save, and activate it. Then, get back to the
function module and open the tab Import or Export. In the column Long text ( ), you
find a button for each parameter that leads to the corresponding parameter documentation.
Analogously, add some comments there. If there is documentation available, this is shown by
a green symbol ( ).

Afterwards, get back to the function module and press Ctrl-F1 or click on the button Display
<-> Change ( ) to enter the display mode. Now, click on Function Module
Documentation again. You see the documentation including parameter documentation you
entered before.

Figure 90: Viewing the function module documentation: SAP-System-Screenshot

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

7.12.4 Exception handling

Your function module currently ignores cases in which an invalid operator was entered or a
division by zero occurs. If you try to divide, for example, 1 by 0, the following short dump
appears:

Figure 91: Short dump caused by zero division: SAP-System-Screenshot

To improve the behavior of your function module, you will now define exceptions for both
cases. For this purpose, open your function module and open the tab Exceptions.

Define the exceptions ZERO_DIVISION and INVALID_OPERATOR and add suitable short
and long texts.

Figure 92: Definition of exceptions: SAP-System-Screenshot

Now, open the tab Source Code. Add a suitable IF construct that checks whether a zero
division could occur. If this is the case, the statement RAISE ZERO_DIVISION shall be
executed.

Take care of the following aspects:

 It should still be possible to add, multiply by or subtract 0


 The modulo operation is a special kind of division. Hence, you must check for a zero
division not only for the regular division but also for the modulo division

Now, extend your CASE structure to make sure that in all other cases for the operator, the
statement RAISE INVALID_OPERATOR is executed.

Note: The exception concept used here may not be confused with the new class-based
exception concept, which would be used if the statement RAISE EXCEPTION is used. This
new concept is covered in the advanced ABAP course.
Page 114
Copyright Prof. Dr. Heimo H. Adelsberger/Dipl.-Wirt.-Inf. Pouyan Khatami
Introduction to ABAP

Save, check, and activate your function module. Then, open your program
ZZ_####_CALCULATOR. If you test it, you will still receive a runtime error when a zero
division occurs:

Figure 93: Another runtime error: SAP-System-Screenshot

Attention: If you see the COMP_INT_ZERODIVIDE runtime error instead of this


RAISE_EXCEPTION runtime error, you did not prevent the zero division by your IF
construct properly. This may be the case if you did not place the IF before the division.

The reason for the new runtime error can be seen in the section Error Analysis: The
exception has been raised, but has not been handled by the calling program. This means that
your program does not define a reaction on the exception yet.

To improve this situation, open the source code and add another part EXCEPTIONS to the
function module call, which already contains the EXPORTING and IMPORTING sections.
There you assign numbers to the exceptions. These numbers can be processed later. Make
sure not to use the value 0, as this is the predefined value for “no exception.” An example is
the following assignment:

Figure 94: Assignment of exceptions and numbers: SAP-System-Screenshot

Make sure there is no dot after the IMPORTING part anymore, but after the EXCEPTIONS
part.

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

The defined numbers can now be retrieved from the system value sy-subrc. Add a CASE
structure to your main program, which checks the value of sy-subrc. Only if the value is 0,
the usual output of the result shall appear. In the two other cases, an appropriate Error
message shall be displayed.

Save, check, activate, and test the program with valid and invalid test data. There may not
be any short dumps anymore! Instead, there must always be a result or a readable error
description, as shown in this figure:

Figure 95: Example error message: SAP-System-Screenshot

It is possible to add an entry for OTHER in the EXCEPTIONS block. In this case, exceptions
that are not handled individually are assigned to a common number.

7.13 Repository and Repository Infosystem


You have learned to work with a package during this chapter. All packages and, therefore, all
contained development objects are stored in the so-called Repository Infosystem in the SAP
ERP system. This repository is client-independent and stored in the database. The repository
objects can be accessed by all clients and looks the same to all clients. Application data,
opposed to that, is usually client dependent.

The repository is structured by application components. When you have created the package
ZZ_####, you saw a field in the input mask, which could be used to define the application
component (see next figure).

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

Figure 94: Selection of application component: SAP-System-Screenshot

Some repository objects may contain other objects that are repository objects themselves.
Furthermore, repository objects can reference each other. To search for specific repository
objects, the SAP ERP system provides search tools in the Repository Infosystem.

7.13.1 SAP Application hierarchy

If you know the application component to which the required repository object belongs, you
can search for it using the SAP application hierarchy. It can be found in the Easy Access
Menu under the path Tools -> ABAP Workbench -> Overview -> Application hierarchy -
> SAP or by transaction code SE81. There you see the application hierarchy as a tree and can
navigate in this structure. To select a certain sub tree for search, put the cursor on the
corresponding node and click on (Select subtree +/-) or press F9. The sub tree will be
highlighted.

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

Figure 96: Highlighted part of the application hierarchy: SAP-System-Screenshot

You can highlight multiple sub trees of the application hierarchy this way. After that, click on
. You now enter the Repository Infosystem, which will be explained in the
following section, but in all search masks there will be a predefined selection of the selected
parts of the application hierarchy.

7.13.2 The Repository Information System

The Repository Information System allows specifying many different search criteria to find
repository objects. It can be started by choosing Tools -> ABAP Workbench -> Overview ->
Infosystem from the Easy Access Menu or using transaction code SE84.

Hint: You can always see the transaction code of the current transaction by clicking on at
the bottom right corner of the SAP window:

Figure 97: Displaying the transaction code: SAP-System-Screenshot

From the navigation tree, choose the path Repository Information System -> Program
Library -> Programs. After double clicking on Programs, you see a search mask on the
right:

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

Figure 98: Program search mask: SAP-System-Screenshot

The search mask does not display all fields initially for a better overview. To see all search
options, click on (All Selections) or press Shift-F9. Further selection criteria will appear.
Enter ZZ_####* as Program Name (replace the # symbols by your user number as usual, but
leave the star unchanged. It is a Symbol for arbitrary characters). Furthermore, enter a date for
Changed on, which is at least before the creation of your last program. Then, click on the
-button (Multiple Selection). In the appearing window, click on the empty button , left
to the date you just entered. Choose and commit both windows.

Now, you are searching for programs that have a name starting with ZZ_#### and were
changed at or after the date you entered. Commit your input by or F8.

The result should comprise at least the last program you created. If you see no result at all,
you may have called the Repository Information System from the application hierarchy,
which adds further restrictive search criteria.

Figure 99: Example search result: SAP-System-Screenshot

Double click on one of the found programs. You will see the source code. You will notice that
on the left, there is still the navigation tree of the Repository Infosystem. In the object
navigator, these two areas are independent, so the object displayed on the right is not
necessarily the same as on the left. To move the navigation tree to the object displayed on the
right, you can choose (Display Object list). Then, click on the -button above the tree
(Display superord. Object list) to get back to your package. The other way, displaying an
object on the right that is selected on the left is trivial; you just have to double click.

Another hint: Using the -button, you can see the navigation window, which shows how
you reached the current view.

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

7.13.3 Program specific search

An alternative to the search via the Repository Infosystem is the search within a program.
This is used if you know a program that is using the relevant repository object. To search for
your function module Z_####_F_CALC, for example, you can open your program
ZZ_####_CALCULATOR and choose one of the following:

 Search the source code for a CALL FUNCTION statement.


 Add a Breakpoint for the statement CALL FUNCTION in the debugger before you
execute the corresponding functionality in the program.

 If the function module sends a screen (which is not the case here, screens are
discussed later), you can use F1 and navigate to the technical settings. This contains
the screen number, which can be used for a Where-Used List.

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

7.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.

If you completed the course so far, send an e-mail to your tutor using the subject
„ABAP: Finished Chapter 7 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 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 contents are read.

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

You might also like