Learning Sap Abap
Learning Sap Abap
Learning Sap Abap
#abap
www.dbooks.org
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Hello World 2
Examples 4
Examples 7
Class declaration 7
ABAP Classes can be declared Globally or Locally. A global class can be used by any object 7
Constructor, methods 7
Inheritance - definition 9
Information 9
Class implementation 9
Information 9
Class implementation: 9
Examples 11
End of Line 11
Full Line 11
Examples 12
IF/ELSEIF/ELSE 12
CASE 12
CHECK 12
ASSERT 12
COND/SWITCH 13
COND 13
Examples 13
SWITCH 13
Examples 13
Examples 15
Examples 17
Field-Symbols 17
Data references 18
Examples 20
www.dbooks.org
Declaration based on Database Table 21
Chapter 9: Loops 23
Remarks 23
Examples 23
While Loop 23
Do Loop 23
General Commands 24
Introduction 26
Remarks 26
Examples 26
Dynamic Messaging 27
Syntax 28
Examples 28
Local variable 28
Global variable 28
Examples 29
SELECT statement 29
Examples 30
Replacing 30
Searching 30
Examples 32
Literals 32
String templates 32
Concatenating strings 32
Syntax 34
Examples 34
Examples 35
Credits 37
www.dbooks.org
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: abap
It is an unofficial and free ABAP ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official ABAP.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with ABAP
Remarks
ABAP is a programming language developed by SAP for programming business applications in
the SAP environment.
Previously only procedural, ABAP is now also an object-oriented language thanks to the ABAP
Objects enhancement.
Versions
Examples
Hello World
PROGRAM zhello_world.
START-OF-SELECTION.
WRITE 'Hello, World!'.
Instead of printing to the console, ABAP writes values to a list which will be displayed as soon as
the main logic was executed.
https://riptutorial.com/ 2
www.dbooks.org
Hello World in ABAP Objects
PROGRAM zhello_world.
START-OF-SELECTION.
main=>start( ).
https://riptutorial.com/ 3
Chapter 2: ABAP GRID List Viewer (ALV)
Examples
Creating and Displaying an ALV
This example portrays the most simple ALV creation using the cl_salv_table class and no
additional formatting options. Additional formatting options would be included after the TRY ENDTRY
block and before the alv->display( ) method call.
All subsequent examples using the ABAP Objects approach to ALV creation will use this example
as a starting point.
" Fill ALV object with data from the internal table
TRY.
cl_salv_table=>factory(
IMPORTING
r_salv_table = alv
CHANGING
t_table = t_spfli ).
CATCH cx_salv_msg INTO error_message.
" error handling
ENDTRY.
" Use the ALV object's display method to show the ALV on the screen
alv->display( ).
This example shows how to optimize the column width so that column headings and data are not
chopped off.
alv->get_columns( )->set_optimize( ).
This example hides the MANDT (client) field from the ALV. Note that the parameter passed to
get_column( ) must be capitalized in order for this to work.
https://riptutorial.com/ 4
www.dbooks.org
The column text may change upon the horizontal resizing of a column. There are three methods to
accomplish this:
set_short_text 10
set_medium_text 20
set_long_text 40
The following example shows usage of all three. A column object is declared and instantiated as a
reference to the result of alv->get_columns( )->get_column( 'DISTID' ). The column name must be
in all capital letters. This is so that this method chaining is only called once in its instantiation,
instead of being executed every time a column heading is changed.
The following method call enables usage of many advanced features such as sorting, filtering, and
exporting data.
alv->get_functions( )->set_all( ).
This method increases readability by giving consecutive rows alternating background color
shading.
By default, when an ALV is displayed, the title at the top is just the program name. This method
allows the user to set a title of up to 70 characters. The following example shows how a dynamic
title can be set that displays the number of records displayed.
https://riptutorial.com/ 5
viewer--alv-
https://riptutorial.com/ 6
www.dbooks.org
Chapter 3: ABAP Objects
Examples
Class declaration
Constructor, methods
Class implementation:
METHOD method1.
"Logic
ENDMETHOD.
METHOD method2.
"Logic
method3( ).
ENDMETHOD.
METHOD method3.
"Logic
https://riptutorial.com/ 7
ENDMETHOD.
ENDCLASS.
Class implementation:
method1 (
EXPORTING iv_string = lv_string
IMPORTING ev_string = lv_string2
CHANGING cv_string = lv_string3
).
Class implementation:
lv_string = method1( ).
https://riptutorial.com/ 8
www.dbooks.org
Note that parameters declared with RETURNING are passed by value only.
Inheritance - definition
Information
Inheritance allows you to derive a new class from an existing class. You do this using
the INHERITING FROM addition in the
statement. The new class subclass inherits all of the components of the existing class
superclass. The new class is called the subclass of the class from which it is derived.
The original class is called the superclass of the new class. A class can have more
than one direct subclass, but it may only have one direct superclass.
Class implementation
Information
The ABSTRACT and FINAL additions to the METHODS and CLASS statements allow
you to define abstract and final methods or classes.
Class implementation:
https://riptutorial.com/ 9
PUBLIC SECTION.
METHODS: abstract_method ABSTRACT,
final_method FINAL
normal_method.
ENDCLASS.
METHOD normal_method.
"Some logic
ENDMETHOD.
ENDCLASS.
METHOD abap_class_method.
"Logic
ENDMETHOD.
ENDCLASS.
lo_class->abstract_method( ).
lo_class->normal_method( ).
lo_class->abap_class_method( ).
lo_class->final_method( ).
https://riptutorial.com/ 10
www.dbooks.org
Chapter 4: Comments
Examples
End of Line
Any text following a " character on the same line is commented out:
Full Line
The * character comments out an entire line. The * must be the first character in the line.
https://riptutorial.com/ 11
Chapter 5: Control Flow Statements
Examples
IF/ELSEIF/ELSE
IF lv_foo = 3.
WRITE: / 'lv_foo is 3'.
ELSEIF lv_foo = 5.
WRITE: / 'lv_foo is 5'.
ELSE.
WRITE: / 'lv_foo is neither 3 nor 5'.
ENDIF.
CASE
CASE lv_foo.
WHEN 1.
WRITE: / 'lv_foo is 1'.
WHEN 2.
WRITE: / 'lv_foo is 2'.
WHEN 3.
WRITE: / 'lv_foo is 3'.
WHEN OTHERS.
WRITE: / 'lv_foo is something else'.
ENDCASE
CHECK
CHECK is a simple statement that evaluates a logical expression and exits the current processing
block if it is false.
METHOD do_something.
CHECK iv_input IS NOT INITIAL. "Exits method immediately if iv_input is initial
ASSERT
ASSERT is used in sensitive areas where you want to be absolutely sure, that a variable has a
specific value. If the logical condition after ASSERT turns out to be false, an unhandleable exception
(ASSERTION_FAILED) is thrown.
ASSERT 1 = 2. "ERROR
https://riptutorial.com/ 12
www.dbooks.org
COND/SWITCH
SWITCH and COND offer a special form of conditional program flow. Unlike IF and CASE, they
respresent different values based on an expression rather than executing statements. That's why
they count as functional.
COND
Whenever multiple conditions have to be considered, COND can do the job. The syntax is fairly
simple:
COND <type>(
WHEN <condition> THEN <value>
...
[ ELSE <default> | throw <exception> ]
).
Examples
SWITCH
SWITCHis a neat tool for mapping values, as it checks for equality only, thus being shorter than COND
in some cases. If an unexpected input was given, it is also possible to throw an exception. The
syntax is a little bit different:
SWITCH <type>(
<variable>
WHEN <value> THEN <new_value>
...
[ ELSE <default> | throw <exception> ]
).
Examples
https://riptutorial.com/ 13
DATA(lw_language) = SWITCH string(
sy-langu
WHEN 'E' THEN 'English'
WHEN 'D' THEN 'German'
" ...
ELSE THROW cx_sy_conversion_unknown_langu( )
).
https://riptutorial.com/ 14
www.dbooks.org
Chapter 6: Data Declaration
Examples
Inline Data Declaration
When using an inline data declaration inside of a SELECT...ENDSELECT block or SELECT SINGLE
statement, the @ character must be used as an escape character for the DATA(lv_cityto)
expression. Once the escape character has been used, all further host variables must also be
escaped (as is the case with lv_carrid below).
Outputs BERLIN.
https://riptutorial.com/ 15
Read Data Declaration online: https://riptutorial.com/abap/topic/1646/data-declaration
https://riptutorial.com/ 16
www.dbooks.org
Chapter 7: Dynamic Programming
Examples
Field-Symbols
Field-Symbols are ABAP's equivalent to pointers, except that Field-Symbols are always
dereferenced (it is not possible to change the actual address in memory).
Declaration
To declare a Field-Symbol the keyword FIELD-SYMBOLS must be used. Types can be generic (ANY
[... TABLE]) to handle a wide variety of variables.
Assigning
Field-Symbols are unassigned on declaration, which means that they are pointing to nothing.
Accessing an unassigned Field-Symbol will lead to an exception, and, if uncaught, to a short
dump. Therefore, the state should be checked with IS ASSIGNED:
IF <fs> IS ASSIGNED.
*... symbol is assigned
ENDIF.
As they are only references, no real data can be stored inside. So, declared DATA is needed in
every case of use.
Unassigning
Sometimes it could be useful to reset a Field-Symbol. This can be done using UNASSIGN.
UNASSIGN <fs>.
* Access on <fs> now leads to an exception again
https://riptutorial.com/ 17
Use for internal tables
Attention! Field-Symbols stay assigned even after leaving the loop. If you want to reuse them
safely, unassign them immediately.
Data references
If the type of a structure should be decided on runtime, we can define our target structure as
reference to the generic type data.
To give wa a type we use the statement CREATE DATA. The addition TYPE can be specified by:
Reference:
• Static checks are active so it's not possible to create an unknown type
Name:
• The parentheses are needed and lw_name_as_string contains the types name as
string.
• If the type was not found, an exception of type CX_SY_CREATE_DATA_ERROR will be
thrown
For instancing dynamically created types the HANDLE addition can be specified. HANDLE receives an
object which inherits from CL_ABAP_DATADESCR.
https://riptutorial.com/ 18
www.dbooks.org
datacontainer (normally done via Field-Symbols)
Classes
CL_ABAP_TYPEDESCR
|
|--CL_ABAP_DATADESCR
| |
| |--CL_ABAP_ELEMDESCR
| |--CL_ABAP_REFDESCR
| |--CL_ABAP_COMPLEXDESCR
| |
| |--CL_ABAP_STRUCTDESCR
| |--CL_ABAP_TABLEDESCR
|
|--CL_ABAP_OBJECTDESCR
|
|--CL_ABAP_CLASSDESCR
|--CL_ABAP_INTFDESCR
CL_ABAP_TYPEDESCR is the base class. It implements the needed methods for describing:
• DESCRIBE_BY_DATA
• DESCRIBE_BY_NAME
• DESCRIBE_BY_OBJECT_REF
• DESCRIBE_BY_DATA_REF
https://riptutorial.com/ 19
Chapter 8: Internal Tables
Examples
Types of Internal tables
Standard Table
This table has all of the entries stored in a linear fashion and records are accessed in a linear way.
For large table sizes, table access can be slow.
Sorted Table
Requires the addition WITH UNIQUE|NON-UNIQUE KEY. Searching is quick due to performing a binary
search. Entries cannot be appended to this table as it might break the sort order, so they are
always inserted using the INSERT keyword.
Hashed Table
Requires the addition WITH UNIQUE|NON-UNIQUE KEY. Uses a proprietary hashing algorithm to maintain
key-value pairs. Theoretically searches can be as slow as STANDARD table but practically they are
faster than a SORTED table taking a constant amount of time irrespective of the size of the table.
https://riptutorial.com/ 20
www.dbooks.org
" Declaration of internal table
DATA t_flightb TYPE STANDARD TABLE OF ty_flightb.
This code declares the table i_compc_all with the existing structure of compc_str.
A work area (commonly abbreviated wa) has the exact same structure as the table, but can
contain only one line (a WA is a structure of a table with only one dimension).
Read, write and insert into internal tables with a header line:
https://riptutorial.com/ 21
LOOP AT i_compc_all. " Loop over table i_compc_all and assign header line
CASE i_compc_all-ftype. " Read cell ftype from header line from table i_compc_all
WHEN 'B'. " Bill-to customer number transformation
i_compc_bil = i_compc_all. " Assign header line of table i_compc_bil with content of
header line i_compc_all
APPEND i_compc_bil. " Insert header line of table i_compc_bil into table
i_compc_bil
" ... more WHENs
ENDCASE.
ENDLOOP.
Reminder: Internal tables with header lines are forbidden in object oriented contexts.
Usage of internal tables without header lines is always recommended.
Read, write and insert into internal tables without a header line:
" Loop over table i_compc_all and assign current line to structure i_compc_all_line
LOOP AT i_compc_all INTO i_compc_all_line.
CASE i_compc_all_line-ftype. " Read column ftype from current line (which as
assigned into i_compc_all_line)
WHEN 'B'. " Bill-to customer number transformation
i_compc_bil_line = i_compc_all_line. " Copy structure
APPEND i_compc_bil_line TO i_compc_bil. " Append structure to table
" more WHENs ...
ENDCASE.
ENDLOOP.
https://riptutorial.com/ 22
www.dbooks.org
Chapter 9: Loops
Remarks
When looping over internal tables, it is generally preferable to ASSIGN to a field symbol rather than
loop INTO a work area. Assigning field symbols simply updates their reference to point to the next
line of the internal table during each iteration, whereas using INTO results in the line of the table
being copied into the work area, which can be expensive for long/wide tables.
Examples
Internal Table Loop
Conditional Looping
If only lines that match a certain condition should be taken into the loop, addition WHERE can be
added.
While Loop
ABAP also offers the conventional WHILE-Loop which runs until the given expression evaluates to
false. The system field sy-index will be increased for every loop step.
WHILE condition.
* do something
ENDWHILE
Do Loop
https://riptutorial.com/ 23
Without any addition the DO-Loop runs endless or at least until it gets explicitly exited from inside.
The system field sy-index will be increased for every loop step.
DO.
* do something... get it?
* call EXIT somewhere
ENDDO.
The TIMES addition offers a very convenient way to repeat code (amount represents a value of type i
).
DO amount TIMES.
* do several times
ENDDO.
General Commands
DO.
READ TABLE itab INDEX sy-index INTO DATA(wa).
IF sy-subrc <> 0.
EXIT. "Stop this loop if no element was found
ENDIF.
" some code
ENDDO.
To skip to the next loop step, the command CONTINUE can be used.
DO.
IF sy-index MOD 1 = 0.
CONTINUE. " continue to next even index
ENDIF.
" some code
ENDDO.
The CHECK statement is a CONTINUE with condition. If the condition turns out to be false, CONTINUE will
be executed. In other words: The loop will only carry on with the step if the condition is true.
DO.
" some code
CHECK sy-index < 10.
" some code
ENDDO.
DO.
" some code
IF sy-index >= 10.
https://riptutorial.com/ 24
www.dbooks.org
CONTINUE.
ENDIF.
" some code
ENDDO.
https://riptutorial.com/ 25
Chapter 10: Message Classes/MESSAGE
keyword
Introduction
The MESSAGE statement may be used to interrupt program flow to display short messages to the
user. Messages content may be defined in the program's code, in the program's text symbols, or
in an independent message class defined in SE91.
Remarks
The maximum length of a message, including parameters passed to it using &, is 72 characters.
Examples
Defining a Message Class
PROGRAM zprogram MESSAGE-ID sabapdemos.
System-defined message may be stored in a message class. The MESSAGE-ID token defines the
message class sabapdemos for the entire program. If this is not used, the message class must be
specified on each MESSAGE call.
A message will display the text stored in the text symbol i00 to the user. Since the message type
is i (as seen in i000), after the user exits the dialog box, program flow will continue from the point
of the MESSAGE call.
Although the text did not come from the message class za, a MESSAGE-ID must be specified.
PROGRAM zprogram.
...
MESSAGE i050(sabapdemos).
It may be inconvenient to define a message class for the entire program, so it is possible to define
the message class that the message comes from in the MESSAGE statement itself. This example will
display message 050 from the message class sabapdemos.
https://riptutorial.com/ 26
www.dbooks.org
Dynamic Messaging
The & symbol may be used in a message to allow parameters to be passed to it.
Ordered Parameters
Calling this message with three parameters will return a message using the parameters:
This message will be displayed as Message with type E 010 in event START-OF-SELECTION. The
number next to the & symbol designates the order in which the parameters are displayed.
Unordered Parameters
https://riptutorial.com/ 27
Chapter 11: Naming Conventions
Syntax
• Characters, numbers and _ can be use for variable name.
• Two character using for variable state and object type.
• Local variables start with L.
• Global variables start with G.
• Function input parameter start with I (import).
• Function output parameter start with E (export).
• Structures symbol is S.
• Table symbol is T.
Examples
Local variable
Global variable
https://riptutorial.com/ 28
www.dbooks.org
Chapter 12: Open SQL
Examples
SELECT statement
SELECT is an Open-SQL-statement for reading data from one or several database tables into
data objects.
* This returns single record if table consists multiple records with same key.
SELECT SINGLE * INTO TABLE lt_mara
FROM mara
WHERE matnr EQ '400-500'.
4. Aggregate Functions
* This puts the number of records present in table MARA into the variable lv_var
SELECT COUNT( * ) FROM mara
INTO lv_var.
https://riptutorial.com/ 29
Chapter 13: Regular Expressions
Examples
Replacing
Searching
For more advanced regex operations it's best to use CL_ABAP_REGEX and its related classes.
The predicate function matches can be used to evaluate strings on the fly without use of any object
declarations.
https://riptutorial.com/ 30
www.dbooks.org
cl_demo_output=>display( 'This will not display' ).
ELSEIF matches( val = '6c6f7665'
regex = '[0-9a-f]*' ).
cl_demo_output=>display( 'This will display' ).
ENDIF.
By using the method GET_SUBMATCH of class CL_ABAP_MATCHER, we can get the data in the
groups/subgroups.
ref_regex->create_matcher(
EXPORTING
text = lv_test
RECEIVING
matcher = ref_matcher
).
ref_matcher->get_submatch(
EXPORTING
index = 0
RECEIVING
submatch = lv_smatch.
https://riptutorial.com/ 31
Chapter 14: Strings
Examples
Literals
Note that the length-range only applies to hard coded values. Internally CString-variables have
arbitrary length while variables of type C always have a fixed length.
String templates
String templates are a convenient way of mixing literal strings with values from variables:
It can also format things like dates. To use the logged on user's date format:
WRITE |The order was completed on { lv_date DATE = USER } and can not be changed|.
Concatenating strings
String and char-like variables can be concatenated using ABAP CONCATENATE command. An extra
variable for storing the results is required.
Example:
https://riptutorial.com/ 32
www.dbooks.org
CONCATENATE var1 var2 var3 INTO result.
"result now contains the values of var1, var2 & var3 stringed together without spaces
Shorthand
Newer versions of ABAP offer a very short variant of concatenation using && (Chaining operator).
Attention! It's worth noticing, that using temporary results in combination with the
Chaining operator inside of loops can lead to massive performance problems due to
growing copy instructions (read more about it here).
https://riptutorial.com/ 33
Chapter 15: Template Programs
Syntax
• CLASS DEFINITION ABSTRACT FINAL makes the program class essentially static as
instance methods could never be used. The intention is to keep the class minimal.
Examples
OO Program with essential event methods
REPORT z_template.
PUBLIC SECTION.
CLASS-METHODS start_of_selection.
CLASS-METHODS initialization.
CLASS-METHODS end_of_selection.
ENDCLASS.
METHOD initialization.
ENDMETHOD.
METHOD start_of_selection.
ENDMETHOD.
METHOD end_of_selection.
ENDMETHOD.
ENDCLASS.
INITIALIZATION.
lcl_program=>initialization( ).
START-OF-SELECTION.
lcl_program=>start_of_selection( ).
END-OF-SELECTION.
lcl_program=>end_of_selection( ).
https://riptutorial.com/ 34
www.dbooks.org
Chapter 16: Unit testing
Examples
Structure of a test class
Test classes are created as local classes in a special unit test include.
PRIVATE SECTION.
DATA:
mo_cut TYPE REF TO zcl_dummy.
METHODS:
setup,
METHOD dummy_test.
cl_aunit_assert=>fail( ).
ENDMETHOD.
ENDCLASS.
Any method declared with FOR TESTING will be a unit test. setup is a special method that is executed
before each test.
An important principle for unit testing is to separate data access from business logic. One efficient
technique for this is to define interfaces for data access. Your main class always use a reference
to that interface instead of direct reading or writing data.
in production code the main class will be given an object that wraps actual data access. This could
be select statement, function mudule calls, anything really. The important part is that this class
should not perform anything else. No logic.
When testing the main class, you give it an object that serves static, fake data instead.
https://riptutorial.com/ 35
An example for accessing the SCARR table
INTERFACE zif_db_scarr
PUBLIC.
METHODS get_all
RETURNING
VALUE(rt_scarr) TYPE scarr_tab .
ENDINTERFACE.
PRIVATE SECTION.
DATA:
mo_cut TYPE REF TO zcl_main_class.
METHODS:
setup.
ENDCLASS.
The idea here is that in production code, ZCL_MAIN_CLASS will get a ZIF_DB_SCARR object that does a
SELECT and returns the whole table while the unit test runs against a static dataset defined right
there in the unit test include.
https://riptutorial.com/ 36
www.dbooks.org
Credits
S.
Chapters Contributors
No
Control Flow
5 Community, gkubed, maillard
Statements
Dynamic
7 Community, gkubed
Programming
Message
10 Classes/MESSAGE gkubed
keyword
https://riptutorial.com/ 37