0% found this document useful (0 votes)
69 views61 pages

ABAP On HANA Synatx Part 2

ABAP on HANA Synatx part 2

Uploaded by

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

ABAP On HANA Synatx Part 2

ABAP on HANA Synatx part 2

Uploaded by

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

SAP ABAP ON HANA

Part-2
22. ABAP – Date and Time SAP ABAP

ABAP implicitly references the Gregorian calendar, valid across most of the world. We can
convert the output to country specific calendars. A date is a time specified to a precise
day, week or month with respect to a calendar. A time is specified to a precise second or
minute with respect to a day. ABAP always saves time in 24-hour format. The output can
have a country specific format. Dates and time are usually interpreted as local dates that
are valid in the current time zone.

ABAP provides two built-in types to work with dates and time:

 D data type
 T data type

Following is the basic format:

DATA: date TYPE D,


time TYPE T.
DATA: year TYPE I,
month TYPE I,
day TYPE I,
hour TYPE I,
minute TYPE I,
second TYPE I.

Both of these types are fixed-length character types that have the form YYYYMMDD and
HHMMSS, respectively.

Timestamps
In addition to these built-in types, the other two types TIMESTAMP and TIMESTAMPL
are being used in many standard application tables to store a timestamp in the UTC format.
Following table shows the basic date and time types available in ABAP.

Data Type Description

A built-in fixed-length date type of the form YYYYMMDD. For


example, the value 20100913 represents the date
D
September 13, 2010.

A built-in fixed-length time type of the form HHMMSS. For


T example, the value 102305 represents time 10:23:05 AM.

57
SAP ABAP

TIMESTAMP This type is used to represent short timestamps in


YYYYMMDDhhmmss form. For instance, the value
(Type P –
20100913102305 represents the date September 13, 2010
Length 8 at 10:23:05 AM.
No decimals)

TIMESTAMPL
TIMESTAMPL represents long timestamps in
(Type P - YYYYMMDDhhmmss,mmmuuun form. Here the additional
digits ‘mmmuuun’ represent the fractions of a second.
Length 11
Decimals 7)

Current Data and Time


The following code snippets retrieve the current system date and time.

REPORT YR_SEP_15.
DATA: date_1 TYPE D.
date_1 = SY-DATUM.
Write: / 'Present Date is:', date_1 DD/MM/YYYY.
date_1 = date_1 + 06.
Write: / 'Date after 6 Days is:', date_1 DD/MM/YYYY.

The above code produces the following output:

Present Date is: 21.09.2015


Date after 6 Days is: 27.09.2015

The variable date_1 is assigned the value of the current system date SY-DATUM. Next, we
increment the date value by 6. In terms of a date calculation in ABAP, this implies that
we’re increasing the day component of the date object by 6 days. The ABAP runtime
environment is smart enough to roll over the date value whenever it reaches the end of a
month.

Time calculations work similar to date calculations. The following code increments the
current system time by 75 seconds using basic time arithmetic.

REPORT YR_SEP_15.
DATA: time_1 TYPE T.
time_1 = SY-UZEIT.
Write /(60) time_1 USING EDIT MASK
'Now the Time is: __:__:__'.
time_1 = time_1 + 75.
Write /(60) time_1 USING EDIT MASK
'A Minute and a Quarter from Now, it is: __:__:__'.

58
SAP ABAP

The above code produces the following output:

Now the Time is 11:45:05


A Minute and a Quarter from Now, it is: 11:46:20

Working with Timestamps


You can retrieve the current system time and store it in a timestamp variable using
GET TIME STAMP as shown in the following code. The GET TIME STAMP statement stores
the timestamp in a long-hand or a short-hand format according to the type of the
timestamp data object used. Timestamp value is encoded using the UTC standard.

REPORT YR_SEP_12.
DATA: stamp_1 TYPE TIMESTAMP,
stamp_2 TYPE TIMESTAMPL.
GET TIME STAMP FIELD stamp_1.
Write: / 'The short time stamp is:', stamp_1
TIME ZONE SY-ZONLO.
GET TIME STAMP FIELD stamp_2.
Write: / 'The long time stamp is:', stamp_2
TIME ZONE SY-ZONLO.

The above code produces the following output:

The short time stamp is: 18.09.2015 11:19:40


The long time stamp is: 18.09.2015 11:19:40,9370000

In the above example, we are displaying the timestamp using the TIME ZONE addition of
the WRITE statement. This addition formats the output of the timestamp according to the
rules for the time zone specified. The system field SY-ZONLO is used to display the local
time zone configured in the user’s preferences.

59
23. ABAP – Formatting Data SAP ABAP

ABAP offers various types of formatting options to format the output of programs. For
example, you can create a list that includes various items in different colors or formatting
styles.

The WRITE statement is a formatting statement used to display data on a screen. There
are different formatting options for the WRITE statement. The syntax of the WRITE
statement is:

WRITE <format> <f> <options>.

In this syntax, <format> represents the output format specification, which can be a
forward slash (/) that indicates the display of the output starting from a new line. In
addition to the forward slash, the format specification includes a column number and
column length. For example, the WRITE/04 (6) statement shows that a new line begins
with column 4 and the column length is 6, whereas the WRITE 20 statement shows the
current line with column 20. The parameter <f> represents a data variable or numbered
text.

The following table describes various clauses used for formatting:

Clause Description

LEFT-JUSTIFIED Specifies that the output is left-justified.

CENTERED Denotes that the output is centered.

RIGHT-JUSTIFIED Specifies that the output is right-justified.

UNDER <g> The output starts directly under the field <g>.

NO-GAP Specifies that the blank after field <f> is rejected.

Denotes the specification of the format template <m>.


Using No EDIT Mask: This specifies that the format
USING EDIT MASK <m>
template specified in the ABAP Dictionary is
deactivated.

If a field contains only zeroes, then they are replaced


NO-ZERO
by blanks.

60
SAP ABAP

Following are the formatting options for Numeric Type fields:

Clause Description

NO-SIGN Specifies that no leading sign is displayed on the screen.

Specifies that in type F (the floating point fields), the


EXPONENT <e>
exponent is defined in <e>.

The type P fields (packed numeric data types) are first


ROUND <r> multiplied by 10**(-r) and then rounded off to an integer
value.

Denotes that the formatting is done according to the


CURRENCY <c> currency <c> value that is stored in the TCURX database
table.

Specifies that the number of decimal places is fixed


UNIT <u> according to the <u> unit as specified in the T006
database table for type P.

Specifies that the number of digits <d> must be


DECIMALS <d>
displayed after the decimal point.

For instance, the following table shows different formatting options for the date fields:

Formatting Option Example

DD/MM/YY 13/01/15
MM/DD/YY 01/13/15
DD/MM/YYYY 13/01/2015
MM/DD/YYYY 01/13/2015
DDMMYY 130115
MMDDYY 011315
YYMMDD 150113

Here, DD stands for the date in two figures, MM stands for the month in two figures, YY
stands for the year in two figures, and YYYY stands for the year in four figures.

61
SAP ABAP

Let’s take a look at an example of ABAP code that implements some of the above
formatting options:

REPORT ZTest123_01.
DATA: n(9) TYPE C VALUE 'Tutorials',
m(5) TYPE C VALUE 'Point'.
WRITE: n, m.
WRITE: / n,
/ m UNDER n.
WRITE: / n NO-GAP, m.
DATA time TYPE T VALUE '112538'.
WRITE: / time,
/(8) time Using EDIT MASK '__:__:__'.

The above code produces the following output:

Tutorials Point
Tutorials
Point
TutorialsPoint
112538
11:25:38

62
24. ABAP – Exception Handling SAP ABAP

An exception is a problem that arises during the execution of a program. When an


exception occurs the normal flow of the program is disrupted and the program application
terminates abnormally, which is not recommended, therefore these exceptions are to be
handled.

Exceptions provide a way to transfer control from one part of a program to another. ABAP
exception handling is built upon three keywords: RAISE, TRY, CATCH and CLEANUP.
Assuming a block will raise an exception, a method catches an exception using a
combination of the TRY and CATCH keywords. A TRY - CATCH block is placed around the
code that might generate an exception. Following is the syntax for using TRY – CATCH:

TRY.
Try Block <Code that raises an exception>

CATCH
Catch Block <exception handler M>
. . .
. . .
. . .
CATCH
Catch Block <exception handler R>

CLEANUP.
Cleanup block <to restore consistent state>

ENDTRY.

RAISE: Exceptions are raised to indicate that some exceptional situation has occurred.
Usually, an exception handler tries to repair the error or find an alternative solution.

TRY: The TRY block contains the application coding whose exceptions are to be handled.
This statement block is processed sequentially. It can contain further control structures
and calls of procedures or other ABAP programs. It is followed by one or more catch blocks.

CATCH: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The CATCH keyword indicates the
catching of an exception.

CLEANUP: The statements of the CLEANUP block are executed whenever an exception
occurs in a TRY block that is not caught by the handler of the same TRY - ENDTRY
construct. Within the CLEANUP clause, the system can restore an object to a consistent
state or release external resources. That is, cleanup work can be executed for the context
of the TRY block.
63
SAP ABAP

Raising Exceptions
Exceptions can be raised at any point in a method, a function module, a subroutine, and
so on. There are two ways an exception can be raised:

 Exceptions raised by ABAP runtime system.


For instance Y = 1 / 0. This will result in a run time error of type
CX_SY_ZERODIVIDE.

 Exceptions raised by programmer.


Raise and create an exception object simultaneously. Raise an exception with an
exception object that already exists in the first scenario. The syntax is: RAISE
EXCEPTION exep.

Catching Exceptions
Handlers are used to catch exceptions.

Let’s take a look at a code snippet:

DATA: result TYPE P LENGTH 8 DECIMALS 2,


exref TYPE REF TO CX_ROOT,
msgtxt TYPE STRING.
PARAMETERS: Num1 TYPE I, Num2 TYPE I.
TRY.
result = Num1 / Num2.
CATCH CX_SY_ZERODIVIDE INTO exref.
msgtxt = exref->GET_TEXT( ).
CATCH CX_SY_CONVERSION_NO_NUMBER INTO exref.
msgtxt = exref->GET_TEXT( ).

In the above code snippet, we are trying to divide Num1 by Num2 to get the result in a
float type variable.

Two types of exceptions could be generated.

 Number conversion error.


 Divide by zero exception. Handlers catch CX_SY_CONVERSION_NO_NUMBER
exception and also the CX_SY_ZERODIVIDE exception. Here the GET_TEXT( )
method of the exception class is used to get the description of the exception.

64
SAP ABAP

Attributes of Exceptions
Here are the five attributes and methods of exceptions:

Attribute Description

Textid Used to define different texts for exceptions and also


affects the result of the method get_text.

Previous This attribute can store the original exception that allows
you to build a chain of exceptions.

get_text This returns the textual representation as a string as per


the system language of the exception.

get_longtext This returns the long variant of the textual representation


of the exception as a string.

Gives the program name and line number reached where


get_source_position the exception was raised.

Example
REPORT ZExceptionsDemo.
PARAMETERS Num_1 TYPE I.
DATA res_1 TYPE P DECIMALS 2.
DATA orf_1 TYPE REF TO CX_ROOT.
DATA txt_1 TYPE STRING.
start-of-selection.
Write: / 'Square Root and Division with:', Num_1.
write: /.
TRY.
IF ABS( Num_1 ) > 150.
RAISE EXCEPTION TYPE CX_DEMO_ABS_TOO_LARGE.
ENDIF.

TRY.
res_1 = SQRT( Num_1 ).
Write: / 'Result of square root:', res_1.
res_1 = 1 / Num_1.
Write: / 'Result of division:', res_1.
CATCH CX_SY_ZERODIVIDE INTO orf_1.
txt_1 = orf_1->GET_TEXT( ).
CLEANUP.
CLEAR res_1.
ENDTRY.

65
SAP ABAP

CATCH CX_SY_ARITHMETIC_ERROR INTO orf_1.


txt_1 = orf_1->GET_TEXT( ).
CATCH CX_ROOT INTO orf_1.
txt_1 = orf_1->GET_TEXT( ).
ENDTRY.
IF NOT txt_1 IS INITIAL.
Write / txt_1.
ENDIF.
Write: / 'Final Result is:', res_1.

In this example, if the number is greater than 150, the exception


CX_DEMO_ABS_TOO_LARGE is raised. The above code produces the following output for
the number 160.

Square Root and Division with: 160


The absolute value of number is too high
Final Result is: 0.00

66
25. ABAP – Dictionary SAP ABAP

As you are aware, SQL can be divided into two parts:

 DML (Data Manipulation Language)


 DDL (Data Definition Language)
DML part consists of query and update commands such as SELECT, INSERT, UPDATE,
DELETE, etc. and ABAP programs handle the DML part of SQL. DDL part consists of
commands such as CREATE TABLE, CREATE INDEX, DROP TABLE, ALTER TABLE, etc. and
ABAP Dictionary handles the DDL part of SQL.

ABAP Dictionary can be viewed as metadata (i.e. data about data) that resides in the SAP
database along with the metadata maintained by the database. The Dictionary is used to
create and manage data definitions and to create Tables, Data Elements, Domains, Views
and Types.

67
SAP ABAP

Basic Types in ABAP Dictionary


The basic types in ABAP Dictionary are as follows:

 Data elements describe an elementary type by defining the data type, length and
possibly decimal places.

 Structures with components that can have any type.


 Table types describe the structure of an internal table.

Various objects in the Dictionary environment can be referenced in ABAP programs. The
Dictionary is known as the global area. The objects in the Dictionary are global to all ABAP
programs and the data in ABAP programs can be declared by reference to these Dictionary
global objects.

The Dictionary supports the definition of user-defined types and these types are used in
ABAP programs. They also define the structure of database objects such as tables, views
and indexes. These objects are created automatically in the underlying database in their
Dictionary definitions when the objects are activated. The Dictionary also provides editing
tools like Search Help and locking tool like Lock Objects.

68
SAP ABAP

Dictionary Tasks
ABAP Dictionary achieves the following:

 Enforces data integrity.


 Manages data definitions without redundancy.
 Integrates tightly with rest of the ABAP development workbench.

Example
Any complex user-defined type can be built from the 3 basic types in the Dictionary.
Customer data is stored in a structure ‘Customer’ with the components Name, Address
and Telephone as depicted in the following image. Name is also a structure with
components, First name and Last name. Both of these components are elementary
because their type is defined by a data element.

The type of component Address is defined by a structure whose components are also
structures, and the Telephone component is defined by a table type because a customer
can have more than one telephone number. Types are used in ABAP programs and also to
define the types of interface parameters of function modules.

69
26. ABAP – Domains SAP ABAP

The three basic objects for defining data in the ABAP Dictionary are Domains, Data
elements and Tables. The domain is used for the technical definition of a table field such
as field type and length, and the data element is used for the semantic definition (short
description). A data element describes the meaning of a domain in a certain business
context. It contains primarily the field help and the field labels in the screen.

The domain is assigned to the data element, which in turn is assigned to the table fields
or structure fields. For instance, the MATNR domain (CHAR material number) is assigned
to data elements such as MATNR_N, MATNN and MATNR_D, and these are assigned to
many table fields and structure fields.

Creating Domains
Before you create a new domain, check whether any existing domains have the same
technical specifications required in your table field. If so, we are supposed to use that
existing domain. Let’s discuss the procedure for creating the domain.

Step 1: Go to Transaction SE11.

Step 2: Select the radio button for Domain in the initial screen of the ABAP Dictionary,
and enter the name of the domain as shown in the following screenshot. Click the CREATE
button. You may create domains under the customer namespaces, and the name of the
object always starts with ‘Z’ or ‘Y’.

70
SAP ABAP

Step 3: Enter the description in the short text field of the maintenance screen of the
domain. In this case, it is “Customer Domain”. Note: You cannot enter any other attribute
until you have entered this attribute.

Step 4: Enter the Data Type, No. of Characters, and Decimal Places in the Format block
of the Definition tab. Press the key on Output Length and it proposes and displays the
output length. If you overwrite the proposed output length, you may see a warning while
activating the domain. You may fill in the Convers. Routine, Sign and Lower Case fields if
required. But these are always optional attributes.

Step 5: Select the Value Range tab. If the domain is restricted to having only fixed values
then enter the fixed values or intervals. Define the value table if the system has to propose
this table as a check table while defining a foreign key for the fields referring to this
domain. But all these are optional attributes.

Step 6: Save your changes. The Create Object Directory Entry pop-up appears and asks
for a package. You may enter the package name in which you are working. If you do not
have any package then you may create it in the Object Navigator or you can save your
domain using the Local Object button.

Step 7: Activate your domain. Click on the Activate icon (matchstick icon) or press CTRL
+ F3 to activate the domain. A pop-up window appears, listing the 2 currently inactive
objects as shown in the following snapshot:

71
SAP ABAP

Step 8: At this point, the top entry labeled ‘DOMA’ with the name ZSEP_18 is to be
activated. As this is highlighted, click the green tick button. This window disappears and
the status bar will display the message ‘Object activated’.

If error messages or warnings occurred when you activated the domain, the activation log
is displayed automatically. The activation log displays information about activation flow.
You can also call the activation log with Utilities(M)  Activation log.

72
27. ABAP – Data Elements SAP ABAP

Data elements describe the individual fields in the ABAP Data Dictionary. They are the
smallest indivisible units of the complex types, and they are used to define the type of
table field, structure component or row type of a table. Information about the meaning of
a table field and also information about editing the corresponding screen field could be
assigned to a data element. This information is automatically available to all the screen
fields that refer to the data element. Data elements describe either elementary types or
reference types.

Creating Data Elements


Before creating a new data element, you need to check whether any existing data elements
have the same semantic specifications required in your table field. If so, you may use that
existing data element. You can assign the data element with a predefined type, domain,
or reference type.

Following is the procedure for creating the data element:

Step 1: Go to Transaction SE11.

Step 2: Select the radio button for Data type in the initial screen of the ABAP Dictionary,
and enter the name of the data element as shown below.

Step 3: Click the CREATE button. You may create data elements under the customer
namespaces, and the name of the object always starts with ‘Z’ or ‘Y’.

73
SAP ABAP

Step 4: Check the Data element radio button on the CREATE TYPE pop-up that appears
with three radio buttons.

Step 5: Click the green checkmark icon. You are directed to the maintenance screen of
the data element.

Step 6: Enter the description in the short text field of the maintenance screen of the data
element. In this case, it is “Customer Data Element”. Note: You cannot enter any other
attribute until you have entered this attribute.

74
SAP ABAP

Step 7: Assign the data element with the type. You can create an elementary data element
by checking elementary type or a reference data element by checking Reference type. You
can assign a data element to a Domain or Predefined Type within Elementary Type and
with Name of Reference Type or Reference to Predefined Type within Reference Type.

Step 8: Enter the fields for short text, medium text, long text, and heading in the Field
Label tab. You can press Enter and the length is automatically generated for these labels.

Step 9: Save your changes. The Create Object Directory Entry pop-up appears and asks
for a package. You may enter the package name in which you are working. If you do not
have any package then you may create it in the Object Navigator or you can save your
data element using the Local Object button.

75
SAP ABAP

Step 10: Activate your data element. Click the Activate icon (matchstick icon) or press
CTRL + F3 to activate the data element. A pop-up window appears, listing the 2 currently
inactive objects as shown in the following screenshot.

Step 11: At this point, the top entry labeled ‘DTEL’ with the name Z_CUST is to be
activated. As this is highlighted, click the green tick button. This window disappears and
the status bar will display the message ‘Object activated’.

If error messages or warnings occurred when you activated the data element, the
activation log is displayed automatically. The activation log displays information about
activation flow. You can also call the activation log with Utilities(M)  Activation log.

76
28. ABAP – Tables SAP ABAP

Tables can be defined independent of the database in ABAP Dictionary. When a table is
activated in ABAP Dictionary, similar copy of its fields is created in the database as well.
The tables defined in ABAP Dictionary are translated automatically into the format that is
compatible with the database because the definition of the table depends on the database
used by the SAP system.

A table can contain one or more fields, each defined with its data type and length. The
large amount of data stored in a table is distributed among the several fields defined in
the table.

Types of Table Fields


A table consists of many fields, and each field contains many elements. The following table
lists the different elements of table fields:

Elements Description

This is the name given to a field that can contain a maximum of 16


characters. The field name may be composed of digits, letters, and
Field name underscores. It must begin with a letter.

Determines whether or not a field belongs to a key field.


Key flag

Assigns a data type to a field.


Field type

The number of characters that can be entered in a field.


Field length

Defines the number of digits permissible after the decimal point.


Decimal places This element is used only for numeric data types.

Describes the meaning of the corresponding field.


Short text

Creating Tables in ABAP Dictionary


Step 1: Go to transaction SE11, select the ‘Database table’ radio button, and enter a
name for the table to be created. In our case, we have entered the name ZCUSTOMERS1.
Click the Create button. The Dictionary: Maintain Table screen appears. Here the ‘Delivery
and Maintenance’ tab is selected by default.

Step 2: Enter an explanatory short text in the Short Description field.

77
SAP ABAP

Step 3: Click the Search Help icon beside the Delivery Class field. Select ‘A [Application
table (master and transaction data)]’ option.

Step 4: Select the ‘Display/Maintenance Allowed’ option from the ‘Data Browser/Table
view Maintenance’ drop-down menu. The Dictionary: Maintenance Table screen appears.

Step 5: Select the Fields tab. The screen containing the options related to the Fields tab
appears.

Step 6: Enter the names of table fields in the Field column. A field name may contain
letters, digits, and underscores, but it must always begin with a letter and must not be
longer than 16 characters.

The fields that are to be created must also have data elements because they take the
attributes, such as data type, length, decimal places, and short text, from the defined data
element.

Step 7: Select the Key column if you want the field to be a part of the table key. Let’s
create fields such as CLIENT, CUSTOMER, NAME, TITLE and DOB.

Step 8: The first field is an important one and it identifies the client which the records are
associated with. Enter ‘Client’ as the Field and ‘MANDT’ as the Data Element. The system
automatically fills in the Data Type, Length, Decimals and Short Description. The ‘Client’
field is made a key field by checking the ‘Key’ box.

Step 9: The next field is ‘Customer’. Check the box to make it a key field and enter the
new Data Element ‘ZCUSTNUM’. Click the Save button.

Step 10: As the Data Element ‘ZCUSTNUM’ doesn’t yet exist, it has to be created. Double-
click the new Data Element and the ‘Create Data Element’ window appears. Answer ‘Yes’
to this and a ‘Maintain Data Element’ window appears.

Step 11: Enter ‘Customer Number’ in the Short Description area. The Elementary data
type called ‘Domain’ should be defined for the new Data element. So enter ‘ZCUSTD1’,
double-click it and agree to save the changes made. Choose ‘Yes’ to create the domain
and type into the ‘Short Description’ box a description of the domain.

78
SAP ABAP

The ‘Definition’ tab opens automatically. The first field is ‘Data Type’.

Step 12: Click inside the box and select ‘NUMC’ type from the drop-down menu. Enter the
number 8 in the ‘No. of characters’ field (a maximum of 8 characters) and enter 0 in
‘Decimal places’ area. The Output length of 8 must be selected and then press Enter. The
‘NUMC’ field’s description must re-appear, confirming that this is a valid entry.

Step 13: Click Save button and Activate the object.

Step 14: Press F3 to return to the ‘Maintain/Change Data Element’ screen. Create four
Field labels as shown in the following snapshot. After this, Save and Activate the element.

Step 15: Press the back button to return to the table maintenance screen. The Customer
column has the correct Data Type, Length, Decimals and Short Description. This indicates
the successful creation of a Data element and also the Domain used.

79
SAP ABAP

Similarly, we need to create three additional fields such as NAME, TITLE and DOB.

Step 16: Select ‘Technical settings’ from the toolbar. Choose APPL0 for the ‘Data class’
and the first size category 0 for the ‘Size’ category’ field. In case of buffering options,
‘Buffering not allowed’ has to be selected.

Step 17: Click Save. Go back to the table and Activate it. The following screen appears.

The table ‘ZCUSTOMERS1’ is activated.

80
29. ABAP – Structures SAP ABAP

Structure is a data object that is made up of components of any data type stored one
after the other in the memory.

Structures are useful for painting screen fields, and for manipulating data that has a
consistent format defined by a discrete number of fields.

A structure may have only a single record at run-time, but a table can have many records.

Creating a Structure
Step 1: Go to transaction SE11.

Step 2: Click on the ‘Data type’ option on the screen. Enter the name 'ZSTR_CUSTOMER1'
and click on Create button.

Step 3: Select the option 'Structure' in the next screen and press Enter. You can see
'Maintain / Change Structure' wizard.

Step 4: Enter the Short Description as shown in the following snapshot.

81
SAP ABAP

Step 5: Enter the Component (Field Name) and Component Type (Data Element).

Note: Here the component names start with Z as per the SAP recommendation. Let's use
data elements that we have already created in the database table.

Step 6: You need to Save, Check and Activate after providing all the components and
component types.

The following screen appears:

Step 7: As this 'ZSTR_CUSTOMER1' is highlighted, click the green tick button. This window
disappears and the status bar will display the message ‘Active’.

The structure is now activated as shown in the following snapshot:

82
30. ABAP – Views SAP ABAP

A View acts like a database table only. But it will not occupy storage space. A view acts
similar to a virtual table - a table that does not have any physical existence. A view is
created by combining the data of one or more tables containing information about an
application object. Using views, you can represent a subset of the data contained in a table
or you can join multiple tables into a single virtual table.

Data related to an application object is distributed among multiple tables by using


database views. They use the inner join condition to join the data of different tables. A
maintenance view is used to display and modify the data stored in an application object.
Every maintenance view has a maintenance status associated with it.

We use projection view to mask unwanted fields and display only relevant fields in a table.
Projection views must be defined over a single transparent table. A projection view
contains exactly one table. We can't define selection conditions for projection views.

Creating a View
Step 1: Select the View radio button on the initial screen of ABAP Dictionary. Enter the
name of the view to be created and then click Create button. We entered the name of the
view as ZVIEW_TEST.

Step 2: Select the projection view radio button while choosing view type and click Copy
button. The ‘Dictionary: Change View’ screen appears.

Step 3: Enter a short description in the Short Description field and the name of the table
to be used in the Basis Table field as shown in the following snapshot.

83
SAP ABAP

Step 4: Click the ‘Table fields’ button to include the fields of ZCUSTOMERS1 table in the
projection view.

Step 5: The Field Selection from Table ZCUSTOMERS1 screen appears. Select the fields
that you wish to include in the projection view as shown in the following snapshot.

Step 6: After clicking the Copy button, all the selected fields for the projection view are
displayed on the ‘Dictionary: Change View’ screen.

Step 7: Select Maintenance Status tab to define an access method. Choose read-only
radio button and ‘Display/Maintenance Allowed with Restrictions’ option from the drop-
down menu of ‘Data Browser/Table View Maintenance’.

Step 8: Save and Activate it. In the ‘Dictionary: Change View’ screen select Utilities(M) >
Contents to display the selection screen for ZVIEW_TEST.

Step 9: Click the Execute icon. The output of the projection view appears as shown in the
following screenshot.

84
SAP ABAP

The table ZCUSTOMERS1 consists of 5 fields. Here the displayed fields are 3 (Client,
Customer Number and Name) with 4 entries. Customer numbers are from 100001 to
100004 with appropriate names.

85
31. ABAP – Search Help SAP ABAP

Search Help, another repository object of ABAP Dictionary, is used to display all the
possible values for a field in the form of a list. This list is also known as a hit list. You can
select the values that are to be entered in the fields from this hit list instead of manually
entering the value, which is tedious and error prone.

Creating Search Help


Step 1: Go to transaction SE11. Select the radio button for Search help. Enter the name
of the search help to be created. Let's enter the name ZSRCH1. Click on the Create button.

Step 2: The system will prompt for the search help type to be created. Select the
Elementary search help, which is default. The screen to create elementary search help as
shown in the following screenshot appears.

Step 3: In the selection method, we need to indicate whether our source of data is a table
or a view. In our case it happens to be a table. The table is ZCUSTOMERS1. It is selected
from a selection list.

Step 4: After the selection method is entered, the next field is the Dialog type. This
controls the appearance of the restrictive dialog box. There is a drop-down list with three
options. Let's select the option 'Display values immediately'.

Step 5: Next is the parameter area. For each Search help parameter or field, these column
fields have to be entered as per the requirements.

 Search help parameter: This is a field from the source of data. The fields from
the table are listed in the selection list. The fields participating in the search help
would be entered, one field in each row. Let's include the two fields CUSTOMER and
NAME. How these two fields participate is indicated in the rest of the columns.

86
SAP ABAP

 Import: This field is a checkbox for indicating whether a Search help parameter is
an import parameter. The export or import is with reference to the search help.

 Export: This field is a checkbox for indicating whether a Search help parameter is
an export parameter. The export will be transfer of field values from the selection
list to screen fields.

 LPos: Its value controls the physical position of Search help parameter or field in
the selection list. If you enter a value 1, the field will appear in the first position in
the selection list and so on.

 SPos: It controls the physical position of Search Help parameter or field in the
restrictive dialog box. If you enter a value of 1, the field will appear in the first
position in the restrictive dialog box and so on.

 Data element: Every Search Help parameter or field by default is assigned a data
element that was assigned to it in the source of data (Table or View). This data
element name appears in display mode.

Step 6: Perform a consistency check and activate the search help. Press F8 to execute.
The 'Test Search Help ZSRCH1' screen appears as shown in the following screenshot.

87
SAP ABAP

Step 7: Let's enter the number 100004 in the CUSTOMER's 'Ready for inp' screen field.
Press Enter.

The customer number, 100004, and the name ‘STEPHEN’ is displayed.

88
32. ABAP – Lock Objects SAP ABAP

Lock Object is a feature offered by ABAP Dictionary that is used to synchronize access to
the same data by more than one program. Data records are accessed with the help of
specific programs. Lock objects are used in SAP to avoid the inconsistency when data is
inserted into or changed in the database. Tables whose data records are to be locked must
be defined in a Lock Object, along with their key fields.

Lock Mechanism
Following are the two main functions accomplished with the lock mechanism:

 A program can communicate with other programs about data records that it is just
reading or changing.

 A program can prevent itself from reading data that has just been changed by
another program.

A lock request is first generated by the program. Then this request goes to the Enqueue
server and the lock is created in the lock table. The Enqueue server sets the lock and the
program is finally ready to access data.

89
SAP ABAP

Creating Lock Objects


Step 1: Go to transaction SE11. The following screen opens.

Step 2: Click ‘Lock Object’ radio button. Enter the name of lock object starting with E and
click the Create button. Here we use EZLOCK12.

Step 3: Enter the short description field and click on Tables tab.

Step 4: Enter the table name in Name field and select the lock mode as Write Lock.

Step 5: Click on Lock parameter tab, the following screen will appear.

90
SAP ABAP

Step 6: Save and activate. Automatically 2 function modules will generate. To check
function modules, we can use Go to  Lock Modules.

Step 7: Click Lock Modules and the following screen will open.

The lock object is created successfully.

The key fields of a table included in a Lock Object are called lock arguments and they are
used as input parameters in function modules. These arguments are used to set and
remove the locks generated by the Lock Object definition.

91
33. ABAP – Modularization SAP ABAP

It is a good practice to keep your programs as self-contained and easy to read as possible.
Just try to split large and complicated tasks into smaller and simpler ones by placing each
task in its individual module, on which the developer can concentrate on without other
distractions.

In SAP ABAP environment, modularization involves the organization of programs into


modular units, also known as logical blocks. It reduces redundancy and increases
program readability even as you are creating it and subsequently during the maintenance
cycle. Modularization also enables reusability of the same code again. ABAP has made it
necessary for developers to modularize, i.e. organizing the programs relatively more, than
in the OOPS-based languages that have relatively more built-in modular features. Once a
small, modularized section of code is complete, debugged and so on, it does not
subsequently have to be returned to, and developers can then move on and focus on other
issues.

ABAP programs are made up of processing blocks known as modularizing processing


blocks. They are:

 The processing blocks called from outside the program and from the ABAP run-time
environment (i.e., event blocks and dialog modules).

 Processing blocks called from ABAP programs.

Apart from the modularization with processing blocks, source code modules are used to
modularize your source code through macros and include programs.

Modularization at source code level:

 Local Macros
 Global Include programs

Modularization through processing blocks called from ABAP programs:

 Subroutines
 Function modules

Modularizing a source code means placing a sequence of ABAP statements in a module.


The modularized source code can be called in a program as per the requirement of the
user. Source code modules enhance the readability and understandability of ABAP
programs. Creating individual source code modules also prevents one from having to
repeatedly write the same statements again and again that in turn makes the code easier
to understand for anyone going through it for the first time.

92
34. ABAP – Subroutines SAP ABAP

A subroutine is a reusable section of code. It is a modularization unit within the program


where a function is encapsulated in the form of source code. You page out a part of a
program to a subroutine to get a better overview of the main program, and to use the
corresponding sequence of statements many times as depicted in the following diagram.

We have program X with 3 different source code blocks. Each block has the same ABAP
statements. Basically, they are the same code blocks. To make this code easier to
maintain, we can encapsulate the code into a subroutine. We can call this subroutine in
our programs as many times as we wish. A subroutine can be defined using Form and
EndForm statements.

93
SAP ABAP

Following is the general syntax of a subroutine definition.

FORM <subroutine_name>.

<statements>

ENDFORM.

We can call a subroutine by using PERFORM statement. The control jumps to the first
executable statement in the subroutine <subroutine_name>. When ENDFORM is
encountered, control jumps back to the statement following the PERFORM statement.

Example
Step 1: Go to transaction SE80. Open the existing program and then right-click on
program. In this case, it is 'ZSUBTEST'.

Step 2: Select Create and then select Subroutine. Write the subroutine name in the field
and then click the continue button. The subroutine name is 'Sub_Display' as shown in the
following screenshot.

Step 3: Write the code in FORM and ENDFORM statement block. The subroutine has been
created successfully.

94
SAP ABAP

We need to include PERFORM statement to call the subroutine. Let’s take a look at the
code:

REPORT ZSUBTEST.
PERFORM Sub_Display.

* Form Sub_Display
* --> p1 text
* <-- p2 text

FORM Sub_Display.
Write: 'This is Subroutine'.
Write: / 'Subroutine created successfully'.
ENDFORM. " Sub_Display

Step 4: Save, activate and execute the program. The above code produces the following
output:

Subroutine Test:

This is Subroutine

Subroutine created successfully

Hence, using subroutines makes your program more function-oriented. It splits the
program's task into sub-functions, so that each subroutine is responsible for one sub-
function. Your program becomes easier to maintain as changes to functions often only
have to be implemented in the subroutine.

95
35. ABAP – Macros SAP ABAP

If we want to reuse the same set of statements more than once in a program, we need to
include them in a macro. For example, a macro can be useful for long calculations or for
writing complex WRITE statements. We can only use a macro within a program in which
it is defined. Macro definition should occur before the macro is used in the program.

Macros are designed based on placeholders. Placeholder works like pointers in C language.
You can define a macro within the DEFINE...END-OF-DEFINITION statement.

Following is the basic syntax of a macro definition:

DEFINE <macro_name>.
<statements>
END-OF-DEFINITION.
......

<macro_name> [<param1> <param2>....].

It is necessary to define a macro first before invoking it. The <param1>…. replaces the
placeholders &1...in the ABAP statements contained in the macro definition.

The maximum number of placeholders in a macro definition is nine. That is, when a
program is executed, the SAP system replaces the macro by appropriate statements and
the placeholders &1, &2,….&9 are replaced by the parameters param1,
param2,....param9. We may invoke a macro within another macro, but not the same
macro.

Example
Go to transaction SE38. Create a new program ZMACRO_TEST along with the description
in the short text field, and also with appropriate attributes such as Type and Status as
shown in the following screenshot:

96
SAP ABAP

Following is the code:

REPORT ZMACRO_TEST.
DEFINE mac_test.
WRITE: 'This is Macro &1'.
END-OF-DEFINITION.
PARAMETERS: s1 type C as checkbox.
PARAMETERS: s2 type C as checkbox.
PARAMETERS: s3 type C as checkbox default 'X'.
START-OF-SELECTION.
IF s1 = 'X'.
mac_test 1.
ENDIF.
IF s2 = 'X'.
mac_test 2.
ENDIF.
IF s3 = 'X'.
mac_test 3.
ENDIF.

We have 3 checkboxes. While executing the program, let’s select the S2 checkbox.

The above code produces the following output:

A Macro Program

This is Macro 2

If all checkboxes are selected, the code produces the following output:

A Macro Program

This is Macro 1 This is Macro 2 This is Macro 3

97
36. Function Modules SAP ABAP

Function modules make up a major part of a SAP system, because for years SAP has
modularized code using function modules, allowing for code reuse, by themselves, their
developers and also by their customers.

Function modules are sub-programs that contain a set of reusable statements with
importing and exporting parameters. Unlike Include programs, function modules can be
executed independently. SAP system contains several predefined function modules that
can be called from any ABAP program. The function group acts as a kind of container for
a number of function modules that would logically belong together. For instance, the
function modules for an HR payroll system would be put together into a function group.

To look at how to create function modules, the function builder must be explored. You can
find the function builder with transaction code SE37. Just type a part of a function module
name with a wild card character to demonstrate the way function modules can be searched
for. Type *amount* and then press the F4 key.

The results of the search will be displayed in a new window. The function modules are
displayed in the lines with blue background and their function groups in pink lines. You
may look further at the function group ISOC by using the Object Navigator screen
(Transaction SE80). You can see a list of function modules and also other objects held in
the function group. Let's consider the function module SPELL_AMOUNT. This function
module converts numeric figures into words.

Creating a New Program


Step 1: Go to transaction SE38 and create a new program called Z_SPELLAMOUNT.

Step 2: Enter some code so that a parameter can be set up where a value could be entered
and passed on to the function module. The text element text-001 here reads ‘Enter a
Value’.

98
SAP ABAP

Step 3: To write the code for this, use CTRL+F6. After this, a window appears where ‘CALL
FUNCTION’ is the first option in a list. Enter 'spell_amount' in the text box and click the
continue button.

Step 4: Some code is generated automatically. But we need to enhance the IF statement
to include a code to WRITE a message to the screen to say "The function module returned
a value of: sy-subrc” and add the ELSE statement so as to write the correct result out
when the function module is successful. Here, a new variable must be set up to hold the
value returned from the function module. Let's call this as 'result'.

Following is the code:

REPORT Z_SPELLAMOUNT.
data result like SPELL.
selection-screen begin of line.
selection-screen comment 1(15) text-001.
parameter num_1 Type I.
selection-screen end of line.
CALL FUNCTION 'SPELL_AMOUNT'
EXPORTING
AMOUNT = num_1
IMPORTING
IN_WORDS = result.
IF SY-SUBRC <> 0.
Write: 'Value returned is:', SY-SUBRC.
else.
Write: 'Amount in words is:', result-word.
ENDIF.

Step 5: The variable which the function module returns is called IN_WORDS. Set up the
corresponding variable in the program called ‘result’. Define IN_WORDS by using the LIKE
statement to refer to a structure called SPELL.
99
SAP ABAP

Step 6: Save, activate and execute the program. Enter a value as shown in the following
screenshot and press F8.

The above code produces the following output:

Spelling the Amount


Amount in words is:
FIVE THOUSAND SIX HUNDRED EIGHTY

100
37. ABAP – Include Programs SAP ABAP

Include programs are global repository objects used to modularize the source code. They
allow you to use the same source code in different programs. Include programs also allow
you to manage complex programs in an orderly way. In order to use an include program
in another program, we use the following syntax:

INCLUDE <program_name>.

INCLUDE statement has the same effect as copying the source code of the include program
<program_name> into another program. As include program can’t run independently, it
has to be built into other programs. You may also nest include programs.

Following are a couple of restrictions while writing the code for Include programs:

 Include programs can't call themselves.


 Include programs must contain complete statements.

Following are the steps to create and use an Include program:

Step 1: Create the program (Z_TOBEINCLUDED) to be included in ABAP Editor. Code to


be included in ABAP Editor is:

PROGRAM Z_TOBEINCLUDED.
Write: / 'This program is started by:', SY-UNAME,
/ 'The Date is:', SY-DATUM,
/ 'Time is', SY-UZEIT.

Step 2: Set the Type of the program to INCLUDE program, as shown in the following
screenshot.

101
SAP ABAP

Step 3: Click the ‘Save’ button and save the program in a package named ZINCL_PCKG.

Step 4: Create another program where the program Z_TOBEINCLUDED has to be used.
Here we have created another program named Z_INCLUDINGTEST and assigned the type
for the program as Executable program.

Step 5: The coding for Z_INCLUDINGTEST program includes the Z_TOBEINCLUDED


program with the help of the INCLUDE statement as shown in the following code.

REPORT Z_INCLUDINGTEST.

INCLUDE Z_TOBEINCLUDED.

Step 6: Save, activate and execute the program.

The above code produces the following output:

This program is started by: SAPUSER


The Date is: 06.10.2015
Time is 13:25:11

102
38. ABAP – Open SQL Overview SAP ABAP

Open SQL indicates the subset of ABAP statements that enable direct access to the data
in the central database of the current AS ABAP. Open SQL statements map the Data
Manipulation Language functionality of SQL in ABAP that is supported by all database
systems.

The statements of Open SQL are converted to database specific SQL in the Open SQL
interface of the database interface. They are then transferred to the database system and
executed. Open SQL statements can be used to access database tables that are declared
in the ABAP Dictionary. The central database of AS ABAP is accessed by default and also
access to other databases is possible via secondary database connections.

Whenever any of these statements are used in an ABAP program, it is important to check
whether the action executed has been successful. If one tries to insert a record into a
database table and it is not inserted correctly, it is very essential to know so that the
appropriate action can be taken in the program. This can done using a system field that
has already been used, that is SY-SUBRC. When a statement is executed successfully, the
SY-SUBRC field will contain a value of 0, so this can be checked for and one can continue
with the program if it appears.

The DATA statement is used to declare a work area. Let's give this the name
'wa_customers1'. Rather than declaring one data type for this, several fields that make up
the table can be declared. The easiest way to do this is using the LIKE statement.

INSERT Statement
The wa_customers1 work area is declared here LIKE the ZCUSTOMERS1 table, taking on
the same structure without becoming a table itself. This work area can only store one
record. Once it has been declared, the INSERT statement can be used to insert the work
area and the record it holds into the table. The code here will read as 'INSERT
ZCUSTOMERS1 FROM wa_customers1'.

The work area has to be filled with some data. Use the field names from the ZCUSTOMERS1
table. This can be done by forward navigation, double clicking the table name in the code
or by opening a new session and using the transaction SE11. The fields of the table can
then be copied and pasted into the ABAP editor.

Following is the code snippet:

DATA wa_customers1 LIKE ZCUSTOMERS1.


wa_customers1-customer = '100006'.
wa_customers1-name = 'DAVE'.
wa_customers1-title = 'MR'.
wa_customers1-dob = '19931017'.
INSERT ZCUSTOMERS1 FROM wa_customers1.

103
SAP ABAP

CHECK statement can then be used as follows. It means that if the record is inserted
correctly, the system will state this. If not, then the SY-SUBRC code which will not equal
zero will be displayed. Following is the code snippet:

IF SY-SUBRC = 0.
WRITE 'Record Inserted Successfully'.
ELSE.
WRITE: 'The return code is ', SY-SUBRC.
ENDIF.

Check the program, save, activate the code, and then test it. The output window should
display as 'Record Inserted Successfully'.

CLEAR Statement
CLEAR statement allows a field or variable to be cleared out for the insertion of new data
in its place, allowing it to be reused. CLEAR statement is generally used in programs and
it allows existing fields to be used many times.

In the previous code snippet, the work area structure has been filled with data to create a
new record to be inserted into the ZCUSTOMERS1 table and then a validation check is
performed. If we want to insert a new record, CLEAR statement must be used so that it
can then be filled again with the new data.

UPDATE Statement
If you want to update one or more existing records in a table at the same time then use
UPDATE statement. Similar to INSERT statement, a work area is declared, filled with the
new data that is then put into the record as the program is executed. The record previously
created with the INSERT statement will be updated here. Just edit the text stored in the
NAME and TITLE fields. Then on a new line, the same structure as for the INSERT
statement is used, and this time by using the UPDATE statement as shown in the following
code snippet:

DATA wa_customers1 LIKE ZCUSTOMERS1.


wa_customers1-customer = '100006'.
wa_customers1-name = 'RICHARD'.
wa_customers1-title = 'MR'.
wa_customers1-dob = '19931017'.
UPDATE ZCUSTOMERS1 FROM wa_customers1.

As UPDATE statement gets executed, you can view the Data Browser in the ABAP
Dictionary to see that the record has been updated successfully.

MODIFY Statement
MODIFY statement can be considered as a combination of the INSERT and UPDATE
statements. It can be used to either insert a new record or modify an existing record. It
follows a similar syntax to the previous two statements in modifying the record from the
data entered into a work area.

104
SAP ABAP

When this statement is executed, the key fields involved will be checked against those in
the table. If a record with these key field values already exist, it will be updated. If not,
then a new record will be created.

Following is the code snippet for creating a new record:

CLEAR wa_customers1.
DATA wa_customers1 LIKE ZCUSTOMERS1.
wa_customers1-customer = '100007'.
wa_customers1-name = 'RALPH'.
wa_customers1-title = 'MR'.
wa_customers1-dob = '19910921'.
MODIFY ZCUSTOMERS1 FROM wa_customers1.

In this example, CLEAR statement is used so that a new entry can be put into the work
area, and then customer (number) 100007 is added. Since this is a new, unique key field
value, a new record will be inserted, and another validation check is executed.

When this is executed and the data is viewed in the Data Browser, a new record will have
been created for the customer number 100007 (RALPH).

The above code produces the following output (table contents):

105
39. ABAP – Native SQL Overview SAP ABAP

The term ‘Native SQL’ refers to all statements that can be statically transferred to the
Native SQL interface of the database interface. Native SQL statements do not fall within
the language scope of ABAP and do not follow the ABAP syntax. ABAP merely contains
statements for isolating program sections in which Native SQL statements can be listed.

In native SQL, mainly database-specific SQL statements can be used. These are
transferred unchanged from the native SQL interface to a database system and executed.
The full SQL language scope of the relevant database can be used and the addressed
database tables do not have to be declared in the ABAP Dictionary. There is also a small
set of SAP specific Native SQL statements that are handled in a specific way by the native
SQL interface.

106
SAP ABAP

To use a Native SQL statement, you have to precede it with the EXEC SQL statement and
end with ENDEXEC statement.

Following is the syntax:

EXEC SQL PERFORMING <form>.


<Native SQL statement>
ENDEXEC.

These statements define an area in an ABAP program where one or more Native SQL
statements can be listed. The statements entered are passed to the Native SQL interface
and then processed as follows:

 All SQL statements that are valid for the program interface of the addressed
database system can be listed between EXEC and ENDEXEC, in particular the DDL
(data definition language) statements.

 These SQL statements are passed from the Native SQL interface to the database
system largely unchanged. The syntax rules are specified by the database system,
especially the case sensitivity rules for database objects.

 If the syntax allows a separator between individual statements, you may include
many Native SQL statements between EXEC and ENDEXEC.

 SAP specific Native SQL language elements can be specified between EXEC and
ENDEXEC. These statements are not passed directly from the Native SQL interface
to the database, but they are transformed appropriately.

Example
SPFLI is a standard SAP Table that is used to store Flight schedule information. This is
available within R/3 SAP systems depending on the version and release level. You can view
this information when you enter the Table name SPFLI into the relevant SAP transaction
such as SE11 or SE80. You can also view the data contained in this database table by
using these two transactions.

REPORT ZDEMONATIVE_SQL.
DATA: BEGIN OF wa,
connid TYPE SPFLI-connid,
cityfrom TYPE SPFLI-cityfrom,
cityto TYPE SPFLI-cityto,
END OF wa.
DATA c1 TYPE SPFLI-carrid VALUE 'LH'.
EXEC SQL PERFORMING loop_output.
SELECT connid, cityfrom, cityto
INTO :wa
FROM SPFLI
WHERE carrid = :c1
ENDEXEC.
FORM loop_output.
WRITE: / wa-connid, wa-cityfrom, wa-cityto.
ENDFORM.

107
SAP ABAP

The above code produces the following output:

0400 FRANKFURT NEW YORK


2402 FRANKFURT BERLIN
0402 FRANKFURT NEW YORK

108
40. ABAP – Internal Tables SAP ABAP

Internal table is actually a temporary table, which contains the records of an ABAP program
that it is being executed. An internal table exists only during the run-time of a SAP
program. They are used to process large volumes of data by using ABAP language. We
need to declare an internal table in an ABAP program when you need to retrieve data from
database tables.

Data in an internal table is stored in rows and columns. Each row is called a line and each
column is called a field. In an internal table, all the records have the same structure and
key. The individual records of an internal table are accessed with an index or a key. As
internal table exists till the associated program is being executed, the records of the
internal table are discarded when the execution of the program is terminated. So internal
tables can be used as temporary storage areas or temporary buffers where data can be
modified as required. These tables occupy memory only at run-time and not at the time
of their declaration.

Internal tables only exist when a program is running, so when the code is written, the
internal table must be structured in such a way that the program can make use of it. You
will find that internal tables operate in the same way as structures. The main difference
being that structures only have one line, while an internal table can have as many lines as
required.

An internal table can be made up of a number of fields, corresponding to the columns of


a table, just as in the ABAP dictionary a table was created using a number of fields. Key
fields can also be used with internal tables, and while creating these internal tables they
offer slightly more flexibility. With internal tables, one can specify a non-unique key,
allowing any number of non-unique records to be stored, and allowing duplicate records
to be stored if required.

The size of an internal table or the number of lines it contains is not fixed. The size of an
internal table changes according to the requirement of the program associated with the
internal table. But it is recommended to keep internal tables as small as possible. This is
to avoid the system running slowly as it struggles to process enormous amounts of data.

Internal tables are used for many purposes:

 They can be used to hold results of calculations that could be used later in the
program.

 An internal table can also hold records and data so that this can be accessed quickly
rather than having to access this data from database tables.

 They are hugely versatile. They can be defined using any number of other defined
structures.

109
SAP ABAP

Example
Assume that a user wants to create a list of contact numbers of various customers from
one or several large tables. The user first creates an internal table, selects the relevant
data from customer tables and then places the data in the internal table. Other users can
access and use this internal table directly to retrieve the desired information, instead of
writing database queries to perform each operation during the run-time of the program.

110
41. ABAP – Creating Internal Tables SAP ABAP

DATA statement is used to declare an internal table. The program must be told where the
table begins and ends. So use the BEGIN OF statement and then declare the table name.
After this, the OCCURS addition is used, followed by a number, here 0. OCCURS tells SAP
that an internal table is being created, and the 0 states that it will not contain any records
initially. It will then expand as it is filled with data.

Following is the syntax:

DATA: BEGIN OF <internal_tab> Occurs 0,

Let’s create the fields on a new line. For instance, create ‘name’ which is declared as LIKE
ZCUSTOMERS1-name. Create another field called ‘dob’, LIKE ZCUSTOMERS1-dob. It is
useful initially to give the field names in internal tables the same names as other fields
that have been created elsewhere. Finally, declare the end of the internal table with “END
OF <internal_tab>.” as shown in the following code:

DATA: BEGIN OF itab01 Occurs 0,


name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.

Here ‘itab01’ is commonly used shorthand when creating temporary tables in SAP. The
OCCURS clause is used to define the body of an internal table by declaring the fields for
the table. When the OCCURS clause is used, you can specify a numeric constant ‘n’ to
determine additional default memory if required. The default size of memory that is used
by the OCCUR 0 clause is 8 KB. The structure of the internal table is now created, and the
code can be written to fill it with records.

An internal table can be created with or without using a header line. To create an internal
table with a header line, use either the BEGIN OF clause before the OCCURS clause or the
WITH HEADER LINE clause after the OCCURS clause in the definition of the internal table.
To create an internal table without a header line, use the OCCURS clause without the
BEGIN OF clause.

You can also create an internal table as a local data type (a data type used only in the
context of the current program) by using the TYPES statement. This statement uses the
TYPE or LIKE clause to refer to an existing table.

The syntax to create an internal table as a local data type is:

TYPES <internal_tab> TYPE|LIKE <internal_tab_type> OF <line_type_itab> WITH


<key> INITIAL SIZE <size_number>.

Here the <internal_tab_type> specifies a table type for an internal table <internal_tab>
and <line_type_itab> specifies the type for a line of an internal table. In TYPES statement,
you can use the TYPE clause to specify the line type of an internal table as a data type and
LIKE clause to specify the line type as a data object. Specifying a key for an internal table

111
SAP ABAP

is optional and if the user does not specify a key, the SAP system defines a table type with
an arbitrary key.

INITIAL SIZE <size_number> creates an internal table object by allocating an initial


amount of memory to it. In the preceding syntax, the INITIAL SIZE clause reserves a
memory space for size_number table lines. Whenever an internal table object is declared,
the size of the table does not belong to the data type of the table.

Note: Much less memory is consumed when an internal table is populated for the first
time.

Example
Step 1: Open the ABAP Editor by executing the SE38 transaction code. The initial screen
of ABAP Editor appears.

Step 2: In the initial screen, enter a name for the program, select the Source code radio
button and click the Create button to create a new program.

Step 3: In the 'ABAP: Program Attributes' dialog box, enter a short description for the
program in the Title field, select the 'Executable program' option from the Type drop-down
menu in the Attributes group box. Click the Save button.

Step 4: Write the following code in ABAP editor.

REPORT ZINTERNAL_DEMO.
TYPES: BEGIN OF CustomerLine,
Cust_ID TYPE C,
Cust_Name(20) TYPE C,
END OF CustomerLine.

TYPES mytable TYPE SORTED TABLE OF CustomerLine


WITH UNIQUE KEY Cust_ID.
WRITE:/'The mytable is an Internal Table'.

Step 5: Save, activate and execute the program as usual.

In this example, mytable is an internal table and a unique key is defined on the Cust_ID
field.

The above code produces the following output:

The mytable is an Internal Table.

112
42. ABAP – Populating Internal Tables SAP ABAP

In internal tables, populating includes features such as selection, insertion and append.
This chapter focuses on INSERT and APPEND statements.

INSERT Statement
INSERT statement is used to insert a single line or a group of lines into an internal table.

Following is the syntax to add a single line to an internal table:

INSERT <work_area_itab> INTO <internal_tab> INDEX <index_num>.

In this syntax, the INSERT statement inserts a new line in the internal_tab internal table.
A new line can be inserted by using the work_area_itab INTO expression before the
internal_tab parameter. When the work_area_itab INTO expression is used, the new line
is taken from the work_area_itab work area and inserted into the internal_tab table.
However, when the work_area_itab INTO expression is not used to insert a line, the line
is taken from the header line of the internal_tab table.

When a new line is inserted in an internal table by using the INDEX clause, the index
number of the lines after the inserted line is incremented by 1. If an internal table contains
<index_num> - 1 lines, the new line is added at the end of the table. When the SAP
system successfully adds a line to an internal table, the SY-SUBRC variable is set to 0.

Example
Following is a sample program that uses the insert statement.

REPORT ZCUSLIST1.
DATA: BEGIN OF itable1 OCCURS 4,
F1 LIKE SY-INDEX,
END OF itable1.
DO 4 TIMES.
itable1-F1 = sy-index.
APPEND itable1.
ENDDO.
itable1-F1 = -96.
INSERT itable1 INDEX 2.
LOOP AT itable1.
Write / itable1-F1.
ENDLOOP.
LOOP AT itable1 Where F1 >= 3.
itable1-F1 = -78.
INSERT itable1.
ENDLOOP.
Skip.
LOOP AT itable1.
Write / itable1-F1.
ENDLOOP.

113
SAP ABAP

The above code produces the following output:

1
96-
2
3
4

1
96-
2
78-
3
78-
4

In the above example, the DO loop appends 4 rows containing the numbers 1 through 4
to it. The header line component itable1-F1 has been assigned a value of -96. Insert
statement inserts the header line as new row into the body before row 3. The existing row
3 becomes row 4 after the insert. The LOOP AT statement retrieves those rows from the
internal table that have an F1 value greater than or equal to 3. Before each row, Insert
statement inserts a new row from the header line of it. Prior to the insert, the F1
component has been changed to contain -78.

After each insert statement is executed, the system re-indexes all rows below the one
inserted. This introduces overhead when you insert rows near the top of a large internal
table. If you need to insert a block of rows into a large internal table, prepare another
table with the rows to be inserted and use insert lines instead.

When inserting a new row inside itable1 inside of a loop at itable1, it doesn’t affect the
internal table instantly. It actually becomes effective on the next loop pass. While inserting
a row after the current row, the table is re-indexed at the ENDLOOP. The sy-tabix is
incremented and the next loop processes the row pointed to by sy-tabix. For instance, if
you are in the second loop pass and you insert a record before row 3. When endloop is
executed, the new row becomes row 3 and the old row 3 becomes row 4 and so on. Sy-
tabix is incremented by 1, and the next loop pass processes the newly inserted record.

APPEND Statement
The APPEND statement is used to add a single row or line to an existing internal table.
This statement copies a single line from a work area and inserts it after the last existing
line in an internal table. The work area can be either a header line or any other field string
with the same structure as a line of an internal table. Following is the syntax of the APPEND
statement that is used to append a single line in an internal table:

APPEND <record_for_itab> TO <internal_tab>.

114
SAP ABAP

In this syntax, the <record_for_itab> expression can be represented by the


<work_area_itab> work area, which is convertible to a line type or by the INITIAL LINE
clause. If the user uses a <work_area_itab> work area, the SAP system adds a new line
to the <internal_tab> internal table and populates it with the content of the work area.
The INITIAL LINE clause appends a blank line that contains the initial value for each field
of the table structure. After each APPEND statement, the SY-TABIX variable contains the
index number of the appended line.

Appending lines to standard and sorted tables with a non-unique key works regardless of
whether the lines with the same key already exist in the table. In other words, duplicate
entries may occur. However, a run-time error occurs if the user attempts to add a duplicate
entry to a sorted table with a unique key or if the user violates the sort order of a sorted
table by appending the lines to it.

Example
REPORT ZCUSLIST1.
DATA: BEGIN OF linv Occurs 0,
Name(20) TYPE C,
ID_Number TYPE I,
END OF linv.
DATA table1 LIKE TABLE OF linv.
linv-Name = 'Melissa'.
linv-ID_Number = 105467.
APPEND linv TO table1.
LOOP AT table1 INTO linv.
Write: / linv-name, linv-ID_Number.
ENDLOOP.

The above code produces the following output:

Melissa 105467

115
43. ABAP – Copying Internal Tables SAP ABAP

When we read a record from an internal table with a header line, that record is moved
from the table itself into the header line. It is then the header line that our program works
with. The same applies while creating a new record. It is the header line with which you
work with and from which the new record is sent to the table body itself.

To copy the records, we can use a SELECT statement to select all of the records from the
table and then use MOVE statement that will move the records from the original table into
the new internal table into the fields where the names correspond.

Following is the syntax for MOVE statement:

MOVE <table_field> TO <internal_tab_field>.

Example
REPORT ZCUSLIST1.
TABLES: ZCUSTOMERS1.
DATA: BEGIN OF itab01 Occurs 0,
name LIKE ZCUSTOMERS1-name,
dob LIKE ZCUSTOMERS1-dob,
END OF itab01.
Select * FROM ZCUSTOMERS1.
MOVE ZCUSTOMERS1-name TO itab01-name.
MOVE ZCUSTOMERS1-dob TO itab01-dob.
ENDSELECT.
Write: / itab01-name, itab01-dob.

The above code produces the following output:

MARGARET 02.11.1994

The select loop fills each field one at a time, using the MOVE statement to move the data
from one table’s field to the other. In the above example, MOVE statements were used to
move the contents of the ZCUSTOMERS1 table to the corresponding fields in the internal
table. You can accomplish this action with just one line of code. You can use the MOVE-
CORRESPONDING statement.

Following is the syntax for MOVE-CORRESPONDING statement:

MOVE-CORRESPONDING <table_name> TO <internal_tab>.

It tells the system to move the data from the fields of ZCUSTOMERS1 to their
corresponding fields in itab01.

116

You might also like