You are on page 1of 287

SAP ABAP/4 Training

Agenda
1

Objectives

Introduction to the ABAP Workbench

ABAP Dictionary

ABAP Programming Overview

Data Declarations

Report Development

Conversion and Interface Development

Q&A
End of Meeting

Objectives

Chapter

Objectives
This course will enable you to:
Acquire knowledge of ABAP Workbench components and capabilities
Learn the basics of ABAP

Introduction to the ABAP Workbench

Chapter

Client Server Concepts


This architecture allows the same application programs to be used to process
information regardless of the type of front-end or database in use

Presentation and
user interaction with
the system

Programs required
to process a
business transaction
Contains the
database

R/3 Repository
Database contains, along with the Repository, application and customizing tables that are
usually client-specific.
Repository objects are not client-specific (cross-client).

Presentation
Server
Layer

Application
Server
Layer

ABAP Program

Cross-client

Database

Repository

Client-specific
Customizing tables
Application tables

ABAP Workbench Tools and Transaction Codes


ABAP Editor (SE38) writing and editing program code
ABAP Dictionary (SE16) processing database table definitions and
retrieving global types

Menu Painter (SE41) - designing the user interface


Screen Painter (SE51) - designing screens (dynamic) for user dialogs
Function Builder (SE 37) - displaying and processing function modules
Class Builder (SE24) - displaying and processing central classes
Object Navigator (SE80) - provides you with a tree-like overview of all
objects within a development class or program

Transporting Repository Objects

Change
Request

Development System

Production System

Transport Requests
Workbench Organizer: Transportable Requests
Report source
ZBC400_00_GETTING_STARTED
Request
IT3K900051

Transportable change request

Exercises for participants on Course BC400 as of May 8,


2000
My requests

Workbench Organizer: Transportable Requests


Change requests involving user BC400-00
Changeable
Transportable
IT3K900051 CARSON
IT3K900052 CARSON
IT3K900053 BC400-00
IT3K900054 BC400-01

Double-click
on the
request number

ABAP Dictionary

Chapter

What is the Data Dictionary?


Centralized and structured source of
information for business applications
A system-independent interface to a
database
A virtual database containing metadata
(data that describes another data).
Provides tools for data manipulation and
data processing (create, modify, delete,
display)

Dictionary Transactions

REPOSITORY INFORMATION SYSTEM

SE15

DATA DICTIONARY

SE11

DATA BROWSER

SE16

MAINTAIN TABLE VIEWS

SM30

TABLE MAINTENANCE

SM31

Functions of the ABAP Dictionary

DB objects

Type definitions

Table

Structure

DB Table
Data elements Table type

Services
Poss. Values

Screen
F4
F4

Basic Objects of the ABAP Dictionary

Table

Table
field

uses

Data Element

uses
Domain

Difference between the Domain and the Data Element


Domain describes the technical attributes / value set of a field (ie. data type, field
length, range values)
Data Element describes the semantic attributes or business function of a field (ie.
context / usage )

Personnel No.

NUMC10

PO No.
Invoice No.

DOMAIN

DATA ELEMENT

DOMAINS: Two-Level Domain Concept Example


The ABAP Dictionary employs a two-level domain concept involving technical domains (referred to as domains in
SAP) and semantic domains (referred to as data elements in SAP).

MANDT

Table:: SPLFI
SPLFI
Table
CARRID CONNID ... AIRPFROM ... AIRPTO

Data Element S_FROMAIRP

Data Element S_TOAIRP

Domain S_AIRPID

DOMAINS: Specifying Value Ranges


The value range of a domain is initially specified defined by specifying a data type and a length for
that domain
Fixed values are typically specified for a domain when the list of possible values for a domain is short
and the values are going to be static. They will be used as an input check on screen fields.
A value table is typically specified for a domain when the list of possible values for a domain are
contained within another table in the system.

Fixed Values Example:


Domain:
S_CLASS (Classes for a Flight Booking)
Values:
C
(business class)
F
(first class)
Y
(economy class)
Value Table Example:
Domain:
S_CARR_ID (Carrier ID)
Value Table:
SCARR

Table: SCARR
Carrier ID
AA
DL
LH
SA
UA

Name
American
Delta
Lufthansa
Singapore
United

Tables
Table - a two-dimensional matrix which describes a relation in the database system, each
row in a table contains precisely one data value or each of the fields defined in the table
structure

Table structure defined by a number of logically related fields


Primary key - made up of one or more table fields that uniquely identify each table row, a
row then may only occur once within a table

Table SCARR Airline Carriers

Rows (tuples)

Carrier ID
AA
DL
LH
UA
...
Primary key

Carrier Name
American Airlines
Delta
Lufthansa
United Airlines
...
(Field) values

TABLES: Transparent Tables and Structures

Table
Field 1 Field 2

ABAP Dictionary
Field 3 Field 4

Field 1 Field 2

Structure
Field 3 Field 4

Database
Table
Field 1

Field 2

Field 3

Field 4

Physical definition of the table

TABLES: Technical Settings


The technical attributes of a table are normally defined when the table is created
and cannot afterwards be changed
Data class: assigns the table to a physical area in the database
Master Data, Transaction Data, Organization & Customizing Data, Customer Data

Size category: determines the space required for a table in the database
Buffering type: determines whether and how a table is to be buffered
Single, Generic, Full, Not Buffered

Logging: automatic logging of database changes by users for the table (for row
size < 455)

TABLES: Technical Settings Data Class


Master Data data that is rarely modified
Transactional Data data that is frequently modified
Organizational Data - data that is defined during customizing when the system is installed
and that is rarely modified thereafter

System Data data that the R/3 system itself needs


Customer Data Classes provided for customer developments allocated in a special
storage in the database

Tables in the ABAP Dictionary


Master data

Organizational data

Table 1
Table 3
Table 4

Table 2
Table 6

Transaction data
Table 5
Table 9

System data
Table 7
Table 8

Database
Tablespace

Master data
Table 1
Table 3
Table 4

Tablespace

Tablespace

Table 2
Table 6

Table 5
Table 9

Org. data

Trans. data

Tablespace

System data
Table 7
Table 8

TABLES: Technical Settings Size Category


describes the expected storage requirements for the table on the database
An initial extent is reserved when a table is created on the database. Extents are
added if theres a need for more space at a later time.
Technical Settings
Initial
Extent

First
Extent

Second
Extent

Database

TABA
TABB
TABC

Size category
TABA

TABB

TABC

TABLES: Technical Settings Table Buffering


Buffering type determines how a table is buffered (i.e. partially, generically, or completely).
UPDATE command always accesses the database
Data type of the key fields must be CHAR
Application server 1

Application server 2

Program
Table buffer

Records are loaded


into the buffer

Program
Table buffer

Program reads data


from a buffered table

TAB

Database

TABLES: Technical Settings Full Buffering

Database table SCOUNTER


MANDT
001
001
001
001
001
001
001
001
001
001
001
001
001
001

CARRID
AA
BA
BA
BA
BA
LH
LH
LH
LH
LH
LH
LH
LH
UA

Buffer contents

COUNTNUM

AIRPORT

00000001
00000001
00000002
00000003
00000004
00000001
00000002
00000003
00000004
00000005
00000006
00000007
00000008
00000001

ACA
ACE
BER
LCY
LHR
BER
DEN
FRA
LCY
LGW
LHR
MUC
RTM
HAM

001
001
001
001
001
001
001
001
001
001
001
001
001
001

AA
BA
BA
BA
BA
LH
LH
LH
LH
LH
LH
LH
LH
UA

00000001
00000001
00000002
00000003
00000004
00000001
00000002
00000003
00000004
00000005
00000006
00000007
00000008
00000001

ACA
ACE
BER
LCY
LHR
BER
DEN
FRA
LCY
LGW
LHR
MUC
RTM
HAM

Application server
SELECT * FROM SCOUNTER WHERE
MANDT = '001' AND CARRID = 'LH'
AND COUNTNUM = '00000004'.

TABLES: Technical Settings Generic Buffering


Database table SCOUNTER
MANDT

CARRID

COUNTNUM

Buffer contents
AIRPORT

001

AA

00000001

ACA

001

LH

00000001

BER

001

BA

00000001

ACE

001

LH

00000002

DEN

001

BA

00000002

BER

001

LH

00000003

FRA

001

BA

00000003

LCY

001

LH

00000004

LCY

001

BA

00000004

LHR

001

LH

00000005

LGW

001

LH

00000001

BER

001

LH

00000006

LHR

001

LH

00000002

DEN

001

LH

00000007

MUC

001

LH

00000003

FRA

001

LH

00000008

RTM

001

LH

00000004

LCY

001

LH

00000005

LGW

001

LH

00000006

LHR

001

LH

00000007

MUC

001

LH

00000008

RTM

001

UA

00000001

HAM
Application server

Generic key

SELECT * FROM SCOUNTER WHERE


MANDT = '001' AND CARRID = 'LH'
AND COUNTNUM = '00000004'.

TABLES: Technical Settings Single Record Buffering


Database table SCOUNTER
MANDT

CARRID

COUNTNUM

Buffer contents
AIRPORT

001

AA

00000001

ACA

001

BA

00000001

ACE

001

BA

00000002

BER

001

BA

00000003

LCY

001

BA

00000004

LHR

001

LH

00000001

BER

001

LH

00000002

DEN

001

LH

00000003

FRA

001

LH

00000004

LCY

001

LH

00000005

LGW

001

LH

00000006

LHR

001

LH

00000007

MUC

001

LH

00000008

RTM

001

UA

00000001

HAM

001

LH

00000004

LCY

Application server
SELECT SINGLE * FROM SCOUNTER WHERE
MANDT = '001' AND CARRID = 'LH' AND
COUNTNUM = '00000004'.

TABLES: Technical Settings Decision Tree for Buffering


Start

Are temp. inconsistencies in the


read data acceptable?
Are most
accesses read only?

No

Table may not be buffered.

Yes
Table may be buffered.

Is the expected table size


smaller than 8KB?

Yes

Full buffering

No
Is the table mostly accessed with
SELECT SINGLE?

Yes

No
Is the expected table size larger
than 1MB (>> 1000 records)?

Yes

No
Yes
Is a left-justified part of the
key usually specified when
the table is accessed

No

Single-record buffering

Buffering depends on installation


Further considerations must be made:
Full or generic buffering possible?
Secondary indexes or buffering?
Generic buffering with suitable
number of generic key fields
Full buffering

Indexes
To improve performance, database indexes are created in the Data Dictionary via
transparent tables

Index on
AIRPORT
SELECT
SELECT* *FROM
FROM
SCOUNTER
SCOUNTERWHERE
WHERE
AIRPORT
AIRPORT==LHR.
LHR.

Binary
search

AIRPORT P
ACA
1
ACE
2
BER
3
BER
6
DEN
7
FRA
8
HAM
14
LCY
4
LCY
9
LGW 10
LHR
5
LHR
11
MUC 12
RTM
13

MANDT CARRID COUNTNUM AIRPORT


001
LH
00000005
ACA
001
BA
00000004
ACE
001
UA
00000001
BER
001
LH
00000002
LCY
001
BA
00000003
LHR
001
LH
00000007
BER
001
AA
00000001
DEN
001
LH
00000003
FRA
001
BA
00000001
LCY
001
LH
00000001
LGW
001
LH
00000004
LHR
001
BA
00000002
MUC
001
LH
00000006
RTM
001
LH
00000008
HAM

Database Views
A view is a virtual table that doesnt physically contain any data, information is generated at run-time
A view is a definition based on the relationship between one or more tables
Benefits of views:
Allows for restricting or limiting the access to information by areas, plants, etc.
Reduces the need to create new tables with specific data for each application.
Can be used to improve performance. Using a view is more efficient than programming nested selects or joins.

ABAP program

View definition in the ABAP Dictionary

F1

F2

F3

F5

F8

Database interface

Is created in the
DB during activation

F1
F1

F2

Table 1

F3

View definition in
the database

F2

F3

F4

F5

Table 2

F5

F8
F6

F7

F8

Table 3

How are tables linked to Views?


MANDT

ID

001

NAME

122356

MANDT

Smith

CARRID

CITY

...

New York

...

SCUSTOM

CONNID

FLDATE

BOOKID

CUSTOMID

...

001

AA

48

...

3689

122356

...

001

LH

324

...

3690

122356

...

CONNID

... CITYFROM

...

CITYTO

...

New York

...

Berlin

...

MANDT

CARRID

001

AA

48

...

001

LH

324

...

Berlin

...

Tokyo

SBOOK

SPFLI

...

View SCUS_BOOK for customer bookings


MANDT

ID

NAME

CITY

CARRID CONNID

FLDATE

BOOKID CITYFROM CITYTO

001

122356 Smith

New York

AA

48

4.9.1999

3689

001

122356 Smith

New York

LH

324

9.9.1999

3690

New York
Berlin

Berlin
Tokyo

ABAP Dictionary Objects

Exercise 1 Create Basic ABAP Dictionary Objects, 60 min


Exercise 2 Create Table Indexes, 20 min

Search Helps
offer the advantage of being able to return multiple field values to the underlying screen
The search key is invoked automatically from a search help when the user presses the F4
key to display allowable values for the field.
The Search path used the last
time is displayed, user may
choose a different search path

User chooses
F4 on field

Hit list is displayed

Values are returned

User selects a row

Search Help Selection Method, Dialog Type, and Fields

Selection
Method
(transparent
table)

Fields
(search help
components)

Dialog Type

34

Search Helps
2 Types of Search Helps:
Elementary search help - this search help corresponds to a search path. The
elementary search help must define where the data of the hit list should be read
(selection method), how the exchange of values between the screen mask and selection
method is implemented (interface of the search help) and how the online input help
should be defined (online behavior of the screen help).

Collective search help - this search help comprises several elementary search helps.
It combines all the search paths which make sense for a field.

Search Help

Exercise 3 Using a Search Help

Data Browser (SE16)


Menu path: Tools>Workbench>Overview>Data Browser
Transaction code: SE16
The Data Browser is a tool that is fully integrated into the ABAP Development
Workbench which allows the user to display data from clients.
Used to determine what data exists in the system

Data Browser: User Parameters


SE16>Settings>User Parameters

Using the Data Browser


The Selection Screen allows values to be entered in order to restrict the entries retrieved
from the table. Once data has been entered in the selection criteria, click on the Execute
pushbutton, and the resulting list is displayed

Data Browser

Exercise 4 ABAP Dictionary Search, 30 min.


Exercise 5 View a Table with the Data Browser, 20 min.

ABAP Programming Overview

Chapter

ABAP Editor
Menu path: Tools>ABAP Workbench>Development>ABAP Editor
Transaction code: SE38
Used to develop, debug, and run programs

ABAP Editor: Program Types


1. Executable Programs (1) - Can be started without a transaction code,
either directly or in the background.
2. Module Pools for Screen Painter Screens (M) - contain processing steps for screen
modules from the transaction and can only be executed with a transaction code or a
menu function.
3. Includes (I) - Contain program code that cannot be run on its own. You call them from
another program using INCLUDE statements.
4. Subroutines (S) - Contain parts of programs (FORM routines) that can be called
using external PERFORM statements.
5. Function Groups (F) - Contain function modules. Function groups and function
modules are managed in the Function Builder. Program type F is set by the Function
Builder, and cannot be changed in the program attributes.
6. Interface Pools (J) - Contain interfaces. Classes and interfaces are managed
(administered).
7. Class Pools (K) - Contain interfaces. Classes and interfaces are managed
(administered)

ABAP Editor: Program Attributes

F4

F4

ABAP Editor: Package or Development Class


Development Classes / Packages support the distributed development of large
applications in SAP; also used to group the modules of SAP together
The SAP transport system requires the assignment of an ABAP program to a development
class, or to identify it as a local object (not transportable)

General ABAP Syntax


ABAP Programs are made up of individual statements.
Each statement ends with a period.
The first word in a statement is called a keyword.
Words must always be separated by at least one space.
Statements can be indented.
Statements can take up more than one line.
You may have multiple statements in a single line.

General ABAP Syntax


sapbc400d_getting_started.

REPORT

sbc400_carrier.
TABLES
DATA
wa_sbc400 TYPE sbc400_carrier.
PARAMETERS pa_car TYPE scarr-carrid.

ABAP
KEYWORD

START-OF-SELECTION.
SELECT SINGLE * FROM scarr
INTO CORRESPONDING FIELDS OF wa_sbc400
WHERE carrid = pa_car.
IF sy-subrc = 0.
MOVE-CORRESPONDING wa_sbc400 TO sbc400_carrier.
CALL SCREEN 100.
MOVE-CORRESPONDING sbc400_carrier TO wa_sbc400.
WRITE wa_sbc400-carrid COLOR COL_KEY.
WRITE wa_sbc400-carrname.
ENDIF.

Chained Statements and Comments


START-OF-SELECTION.

* Read data record from database table SCARR


SELECT SINGLE * FROM scarr
INTO CORRESPONDING FIELDS OF wa_sbc400
WHERE carrid = pa_car.
IF sy-subrc = 0.
MOVE-CORRESPONDING wa_sbc400 TO sbc400_carrier.
CALL SCREEN 100. Process screen 100
MOVE-CORRESPONDING sbc400_carrier TO wa_sbc400.
WRITE:/ wa_sbc400-carrid COLOR COL_KEY ,
wa_sbc400-carrname ,
wa_sbc400-currcode .
ENDIF.

COMMENT

COMMENT

CHAINED
STATEMENT

Navigation in the Editor


Definition of Database Table in
the ABAP Dictionary
START-OF-SELECTION.

Definition of Structure
(or of structured field)

SELECT SINGLE * FROM scarr


INTO CORRESPONDING FIELDS OF wa_sbc400
WHERE carrid = pa_car.
IF sy-subrc = 0.
MOVE-CORRESPONDING wa_sbc400 TO sbc400_carrier.
CALL SCREEN 100.
Screen Definition
(in
MOVE-CORRESPONDING sbc400_carrier TO wa_sbc400.
the Screen Painter)
WRITE: / wa_sbc400-carrid COLOR COL_KEY,
wa_sbc400-carrname ,
wa_sbc400-currcode .
ENDIF.

Keyword Documentation
Keyword Documentation in the Editor

Editor

Help

START-OF-SELECTION.
SELECT SINGLE * FROM scarr
Editor Help
INTO wa_scarr
ABAP Overview
WHERE
carrid = pa_car.
ABAP Term
WRITE
IF
sy-subrc
=
0.
ABAP News
MOVE-CORRESPONDING wa_scarr TO
ABAP Docu and Examples
sbc400_carrier.
CALL SCREEN 100.
MOVE-CORRESPONDING sbc400_carrier
TO wa_scarr.
WRITE
WRITE: wa_scarr-carrid,
F1 wa_scarr-carrname,
wa_scarr-currcode.

Keyword
ENDIF.

Documentation

New Session

Pattern Pushbutton
allows the user to insert statement templates into the program code by providing a skeleton
for the program code
It is possible to select one of the following:
CALL FUNCTION - inserts a function call.
MESSAGE - inserts a MESSAGE statement for a specified message. Enter a message ID,
message type, and a number.
SELECT * FROM - inserts a SELECT from <table> statement. Enter the table name in the
field provided.
PERFORM - inserts a PERORM statement for a specified form routine.
AUTHORITY - CHECK - inserts an AUTHORITY - CHECK statement for a specified
authorization object.
WRITE - inserts a WRITE statement for a specified structure or table.
CASE for status - inserts a CASE statement for a specified status.
Internal table - inserts an internal table. It is possible to copy the fields or the structure of
an existing table.
CALL DIALOG - inserts a CALL DIALOG statement for a specified dialog module.
Other pattern - inserts a predefined or user-defined ABAP statement.
After selecting a statement in code, fill out the template as the program requires.

Pattern Pushbutton

Ctrl + F6

Program Checks
In the ABAP Editor, Program>Check
SYNTAX
CHECK

EXTENDED
PROGRAM CHECK

CODE INSPECTOR

ABAP Editor

Exercise 6 Using the ABAP Editor, 35 min.

Data Declaration

Chapter

Data Types
DATA TYPE
Pre-Defined

User Defined

(P,I,F,C,N,D,T,X)
Elementary

Structured

Structure Type

Table Type

Pre-defined Data Types

Initial value

Standard
length

type
type
Permitted
length

numeric

Meaning

packed number

1-16

integer

floating point no.

0.000...

alpha-numeric

Data type

numeric text

00...0

1-max.

text

blank

1-max.

date (YYYYMMDD)

00000000

time (HHMMSS)

000000

hexadecimal

X'00'

1-max.
R

max = 65,535 bytes

Defining Variables: Overview

TYPE <ABAP-data-type>.
DATA: <varname>

TYPE <user-defined-type>.
LIKE <ABAP-dictionary-object>.
. . . VALUE <literal>
. . . DECIMALS <n>

Defining Variables: ABAP Data Types

DATA: <varname> TYPE <ABAP-data-type>.


DATA: counter
name(25)
start_date
first_line
sum(5)

TYPE I,
TYPE C,
TYPE D,
TYPE I VALUE 1,
TYPE P DECIMALS 2.

0000
00000000
0001
00000

Defining Variables: User-defined Data Types


DATA: <varname> TYPE <user-defined-type>.
*************************************
* Using Standard Type (Ex.1)
*
*************************************
DATA : office_tel(15) TYPE C,
home_tel(15) TYPE C,
fax_tel(15) TYPE C.
**************************************
* Using User Defined Data Type (Ex.2)*
**************************************
TYPES tel_no(15) TYPE C.
DATA : office_tel TYPE tel_no,
home_tel TYPE tel_no,
fax_tel TYPE tel_no.

Defining Variables: ABAP Dictionary Objects

DATA: <varname> LIKE <ABAP-dictionary-object>.

DATA: date LIKE sy-datum


DATA: flight_date LIKE sflight-fldate.
DATA: wa_spfli LIKE spfli.

Defining Data Types

TYPE <ABAP-data-type>.
TYPES: <varname>

TYPE <user-defined-data-type>.
LIKE <ABAP-dictionary-object>.

TYPES BEGIN rec_type,


..,
END OF rec_type.

Grouping of Variables into Records


TYPES: BEGIN OF <rec-type>,
... ,
END OF <rec-type>.
DATA: <varname> TYPE <rec-type>.
TYPES: BEGIN OF rec_type,
flag TYPE C,
name(30) TYPE C,
sum_field TYPE P DECIMALS 2,
END OF rec_type.
DATA: wa_rec TYPE rec_type.

Structure types can be nested


R

Defining Records (Include Structure)


DATA: BEGIN OF rec,
INCLUDE STRUCTURE s.
DATA: END OF rec.
OR
DATA: BEGIN OF rec,
...
rec LIKE s,
...
END OF rec.
DATA: <varname> TYPE <rec-type>.

Structure types can be nested


R

Literals and Constants


ABAP recognizes two types of constants:
Number literals for data types P and I
Text literals for data types C and N.
Since there are no type-specific constants for the remaining pre-defined data types, use a
text literal.
Fields defined with the keyword CONSTANTS (discussed later)
To assign a value with decimal places to a field of type P, define it as a text literal (for
example, 2.17).
ABAP generates a value appropriate to each type internally.
If a text literal contains an inverted comma, the inverted comma must be entered twice.
The CONSTANTS statement defines global and local fields as constants.
In contrast to fields defined using the DATA statement (variables), it is not possible to
change the value of a field defined using the CONSTANTS. This is part of the ABAP
syntax check.
The addition VALUE is required. It must be followed by a value in single quotes or the
name of another field which has also been defined using the CONSTANTS statement.

Literals and Constants


CONSTANTS <constants> TYPE <type> VALUE <literal>.

CONSTANTS: pi
TYPE P DECIMALS 4 VALUE '3.1415',
boss(4) TYPE C VALUE 'Hugo'.
Number literals

Lit eral type

715, -431

nine digits or fewer

Whole number (with preceding


minus sign if negative)

ten or more digits

Text literals
'abc', '2.17', '1.213E15', '0FFF', 'A''B'
Sequence of characters enclosed in
apostrophes. Max. 255 chars

Literal type

type conversion if necessary

Assigning Values
There are a number of ABAP statements which assign a value to a field. One of
the most important is the MOVE statement.
The equals symbol = can also be used to assign a value to a field. In this case
the field on the left of the equals symbol is assigned the value of the
field/literal/arithmetic expression on the right.
If the type and length of the field does not match the assigned value, the system
carries out automatic type conversion.

Assigning Values
MOVE <data object1> TO <data object2>.
<data object2> = <data object1>.
TYPES: BEGIN OF rec_type,
flag
TYPE c,
name(30) TYPE c,
sum_field TYPE p DECIMALS 2,
END OF rec_type.
DATA: name(25)
TYPE c,
sort_name
LIKE name,
first_line(4)
TYPE n,
rec1
TYPE rec_type,
rec2
TYPE rec_type.
MOVE BEN' TO name.
MOVE 5 TO FIRST_LINE.
sort_name
= name.
rec2
= rec1.

Type Conversion
Fields of type C are stored left-justified and filled with blanks from the right if they
are longer than the destination field.
If a field of type C is assigned to a field of type P, only figures, the plus/minus
sign, and the decimal point are allowed otherwise a RUNTIME ERROR will
occur.
If a packed field is assigned to a field of type C, the numerical value is formatted
(commas to separate thousands, decimal comma, sign) and the leading zeros
are converted to blanks (see WRITE statement).
If this type of formatting is undesirable, use the UNPACK statement.
Depending on whether the packed field is defined with decimal places, the
appropriate number of figures after an existing decimal point are transferred from
the C field:
For example: C field
-47.110

P field (DECIMALS 2)
47.11-

For a list of all possible type conversions and their results, refer to the online
documentation for the MOVE statement.

Assigning Values (Example)

Target field

Source field
Type

Length
1

Value
A8

Type

Length

Value

A____

ABCD

AB

-47110

47110-

12345-

12.345-

Dangers of Assigning Values Between Incompatible Structures

Field does not


have a string type
rec1
DATA: BEGIN OF rec1,
text1(3) TYPE c
VALUE 'AAA',
text2(4) TYPE c
VALUE 'BBCC',
pack(8) TYPE p DECIMALS 2 VALUE '2.26',
text3(10) TYPE c
VALUE 'DD',
END OF rec1,
BEGIN OF rec2,
rec2
text1(5) TYPE c
VALUE 'YYYYY',
pack(8) TYPE p DECIMALS 2 VALUE '72.34',
text3(1) TYPE c
VALUE 'Z',
END OF rec2.
rec2.
MOVE rec1 TO rec2
rec1 text1 text2

pack

text3

AAA BBCC 0000000000002.26 DD _ _ _ _ _ _ _ _

rec2 text1
YYYYY

pack

text3

0000000000072.34 Z

rec2 text1

pack

AAABB C ? ? ?

text3
?

Assigning Values Field for Field


MOVE-CORRESPONDING <rec1> TO <rec2>.
TYPES:

BEGIN OF rec_type,
flag TYPE C,
carrid LIKE spfli
- carrid,
connid LIKE spfli
- connid,
END OF rec_type.
DATA: wa_spfli LIKE spfli,
rec TYPE rec_type.
SELECT mandt carrid connid from spfli
INTO CORRESPONDING FIELDS OF wa_spfli.
...
MOVE
- CORRESPONDING wa_spfli TO rec.
MANDT
401

CARRID
LH

CONNID
2407

...
wa_spfli

MOVE-CORRESPONDING wa_spfli TO rec.


FLAG

CARRID
LH

CONNI D
2407

rec

Using Field Symbols


FIELD-SYMBOLS <fs>.
DATA : name(25) TYPE C VALUE SOMEONE,
address(25) TYPE C VALUE SOMEWHERE.
FIELD-SYMBOLS <temp>.
ASSIGN name TO <temp>.
WRITE <temp>.
ASSIGN address TO <temp>.
WRITE <temp>.
OUTPUT:
SOMEONE

SOMEWHERE

PARAMETERS Statement
The PARAMETERS statement is used to declare fields for use within a program.
In contrast to fields declared with the DATA statement, the user is prompted to
enter initial values for these fields on a selection screen when the program is
invoked. The user supplies the necessary value(s) and then clicks on the
Execute pushbutton to execute the program.
Some of the additions of the DATA statement can also be used with the
PARAMETERS statement (for example, TYPE, LIKE, DECIMALS, etc.).
While DATA allows the assignment of initial values to fields with VALUE,
PARAMETERS allows the assignment of a default value with DEFAULT. These
default values are shown on the selection screen. The user does have the ability
to change these values prior to clicking on the Execute pushbutton.
Fields defined using the PARAMETERS statement can be used within a program
in the same way as fields defined using the DATA statement.
Note - the length of PAR1 and PAR2 is defined by the standard lengths
belonging to the field type.

PARAMETERS Statement
PARAMETERS <field>.
REPORT YA70D050.
PARAMETERS: p_PAR1 TYPE P,
p_PAR2
DEFAULT 'X'.
..
.
MOVE

p_PAR1 TO ... .

WRITE: p_PAR1, p_PAR2.


.
.
.

P_PAR1
P_PAR2 X

Selection
Screen

PARAMETER AS CHECKBOX Statement


Fields declared using the PARAMETERS statement can be displayed as
Checkboxes on the reports selection screen. The display characteristics of the
checkbox are handled by SAPGUI.
Data type or length cannot be specified for a field to be displayed as a checkbox.
A checkbox field is defined as a type C field of 1 character in length.
A checkbox can given an initial value by using the DEFAULT option. Specifying
DEFAULT X will result in the checkbox being selected when the selection
screen appears. No default value results in the checkbox not being selected.
The text that appears next to a checkbox can be modified via Text Elements ->
Selection Texts.

PARAMETER AS CHECKBOX Statement


PARAMETERS: <field> AS CHECKBOX.

REPORT YA70D051 MESSAGE-ID AT.


PARAMETERS: p_PARM1 AS CHECKBOX,
p_PARM2 TYPE I DEFAULT 300,
p_PARM3 AS CHECKBOX DEFAULT 'X'.

P_PARM1
P_PARM2
P_PARM3

300

PARAMETERS AS RADIOBUTTON Statement


Fields declared using the PARAMETERS statement can be displayed as
Radiobuttons. The display characteristics of the Radiobuttons are handled by
SAPGUI.
Data type or length cannot be specified for fields to be displayed as
Radiobuttons. Each of these fields is defined as a type C field of 1 character in
length. A radio button parameter cannot be given a default of space.
Radiobutton fields must be grouped using the RADIOBUTTON GROUP group
option.
The Radiobutton Group name can be up to 4 characters in length and should not
be enclosed in quotes.
A minimum of 2 parameters must be assigned to the same Radiobutton Group
(syntax checked).
The Radiobutton defaults is specified using the DEFAULT option.
The text that appears next to each Radiobutton can be modified via Text
Elements -> Selection Texts.

PARAMETERS AS RADIOBUTTON Statement


PARAMETERS: <field> RADIOBUTTON GROUP group.
REPORT B170D052 MESSAGE-ID AT.
PARAMETERS: p_PARM1 RADIOBUTTON GROUP G1,
p_PARM2 RADIOBUTTON GROUP G1,
p_PARM3 RADIOBUTTON GROUP G2,
p_PARM4 RADIOBUTTON GROUP G2 DEFAULT 'X'.

p_PARM1
p_PARM2
p_PARM3
p_PARM4

Group G1
Group G2

SELECT-OPTIONS Statement
SELECT-OPTIONS: <field> FOR <type>.

REPORT B170D052 MESSAGE-ID AT.


DATA: gd_carrid TYPE s_carr_id.
SELECT-OPTIONS: s_carr FOR gd_carrid.

signoption low high

S_CARR

TO

RANGES Statement
Effect of SELECT-OPTIONS

RANGES: <varname> FOR <field> [DEFAULT] <val1> TO <val2>

RANGES : r_sonum FOR vbak-vbeln,


r_date FOR vbak-bldat
DEFAULT 20050101 TO 20050419.

System Fields
SYSTEM FIELD
Name

Type

Length

SY-DATUM

DATE

SY-UZEITTIME

Meaning
Date

Time

SY-UNAME

CHAR

12

User Name

SY-SUBRC

HEX

Return code

SY-RAPID

CHAR

Program name

SY-LANGU

CHAR

Logon language

Report Development

Chapter

WRITE Statement
The WRITE statement outputs the contents of a field or constant in a format appropriate to
the data type. ABAP data types will be discussed in detail during the next topic, ABAP
Data.
Successive WRITE statements output data, separated by one space, on the same
output line. When an output line is full, output continues on the next line.
The SKIP statement generates blank lines.

WRITE <varname>.
WRITE <constant>.
WRITE : <var1>, <var2>, <constant>.
DATA :

first_name(15) TYPE C,
last_name(15) TYPE C.
MOVE : MY FNAME TO first_name,
MY LNAME TO last_name.
WRITE FIRST NAME:.
WRITE first_name.
WRITE : / Full Name:, first_name, last_name.

WRITE Statement Formatting Option


The format specification must precede the output value.
There must be no spaces between the individual components of a format specification.
The complete format or individual format specifications can be omitted.
The sequence for the format specification must always be as above.
Individual output values within a line are separated by a blank unless a specific start
column is specified.
The formatting options must always appear after the output value.
Refer to the online documentation for a detailed overview of WRITE options.

WRITE Statement Formatting Option


WRITE / <varname>. New Line
WRITE /<column position>(<length>) <varname>. Column and Length
WRITE AT /<column position>(<length>) <constant>.
DATA :

first_name(15) TYPE C,
last_name(15) TYPE C.
first_name = MY FNAME.
last_name = MY LNAME.
WRITE / FIRST NAME:.
WRITE /12(15) first_name.
WRITE AT /25(15) Full Name:.
WRITE (2) last_name.

WRITE TO Statement Transferring Data


WRITE <var1> TO <var2>[+offset(length) [advance options]].

DATA:

W_FIELD1(8) TYPE C VALUE EXAMPLE,


W_FIELD2(10) TYPE C,
W_FIELD3(10) TYPE C.

WRITE W_FIELD1+2(2) TO W_FIELD2.


WRITE W_FIELD1 TO W_FIELD3.
WRITE W_FIELD2.
WRITE W_FIELD3.

WRITE Statement Advanced Feature


The formatting option DD/MM/YYYY formats a date field in accordance with the
information in the user master record (select System --> User profile --> own data).
The formatting option UNDER allows the display of a value (immediately left justified)
beneath a value which has already been output. (The line feed must be explicitly
programmed.). This assists in easy alignment of output values. The output value/field
from which column.
For additional Format Options, refer to the online dpositioning is taken need not be on the
previous line ocumentation for the ABAP keyword WRITE.

WRITE Statement Advanced Feature


WRITE <field> [USING EDIT MASK mask] [USING NO EDIT-MASK]
[NO-ZERO] [NO-SIGN] [DD/MM/YY] [MM/DD/YY]
[MM/DD/YYYY] [DD/MM/YYYY] [CURRENCY currency]
[UNDER field] [NO-GAP]
[DECIMALS number of decimal point]
[LEFT-JUSTIFIED, CENTERED, RIGHT-JUSTIFIED]
DATA:

w_field1(2) TYPE C VALUE '12',


w_field2(7) TYPE C VALUE '3456789',
w_field3(2) TYPE C VALUE '10'.
WRITE : w_field1 NO-GAP, w_field2, w_field3.
DATA:
WRITE:
WRITE:

w_date TYPE D VALUE '20041214',


w_date2(10) TYPE C.
w_date to w_date2 MM/DD/YY.
w_date2.

Other Display / Print Statement


ULINE. Insert horizontal line.
SKIP [<no of lines>] [TO LINE <line number>]. Skip line(s) on the page.
POSITION <N>. Horizontal Positioning (columns).
ULINE.
WRITE SAMPLE.
SKIP.
WRITE Next Line.
POSITION 5.

FORMAT Statement
FORMAT [INTENSIFIED] [INTENSIFIED OFF]
[COLOR color] [COLOR OFF]
[INVERSE] [INVERSE OFF]
[RESET]
DATA :

first_name(15) TYPE C,
last_name(15) TYPE C.

MOVE :

MY FNAME TO first_name,
MY LNAMETO last_name.

FORMAT COLOR 7.
WRITE FIRST NAME:.
FORMAT RESET.
FORMAT INTENSIFIED.
WRITE first_name.
FORMAT INTENSIFIED OFF.
FORMAT INVERSE.
WRITE : / Full Name:, first_name, last_name.

Text Elements
REPORT Z170D037.
WRITE: TEXT-001, 10 SY-Datum . . . .
'Time'(002), 10 SY-UZEIT . . .
ABAP Text Elements: Change Text Symbols

Text elements
Text symbols

Program name

ZDEMO001

Lang. E

Text - Text
Symbol ....+....1....+....2....+....3....+
Date
001
Date
002
Time
Time

01.01.1996
21:07:54

Text Symbols are maintained using the TEXT ELEMENTS function either from the
editors initial screen, from within the editor Edit -> Text elements, or from the
program code (Goto -> Text elements), or by double-clicking on the text(003) word.
The primary advantage of Text symbols is that they can be managed separately for
different languages (Goto -> Translation).

MESSAGE Statements
CONSTANTS c_ua TYPE s_carr_id VALUE 'UA'.

READ TABLE itab INTO wa_itab WITH TABLE KEY carrid = c_ua.
IF sy-subrc <> 0.
*Message
MESSAGE ID 'BC400' TYPE 'I'
NUMBER '041' WITH wa_itab-carrid.

ELSE.
MESSAGE ID 'BC400' TYPE 'I'
NUMBER '040' WITH wa_itab-carrid wa_itab-carrname

ENDIF.

Message classBC400
BC400
Message:
040
047: The name of the airline &1 is &2
041
048: Airline &1 is not available

MESSAGE xyyy(zzzz)[WITH <varname> <varname2>]


where x = msg type, yyy = msg num, zzz = msg class

Dialog Behavior of Messages


MESSAGE ID <message class> TYPE <message type>
NUMBER <message number>
WITH <var1> <var2> <var3> <var4>.
Type

Meaning

Behavior

Message appears in

Status Message

Program continues
without interruption

Status line in next screen

Information

Program interrupted

Modal dialog box

when dialog box is displayed


W

Warning

Depends on context

Status line (& modal dialog box)

Error

Depends on context

Status line (& modal dialog box)

Termination

Program aborted

Modal dialog box

Short dump

Runtime Error

Integrated in short dump

MESSAGE_TYPE_X

WRITE Statement

Exercise 7 Using the WRITE Statement, 30 minutes

Calculating Values for Numeric Fields


The key word COMPUTE is optional.
There is no limit to the number of nesting levels for parenthesized expressions.
Operators and parentheses are considered as words. Therefore, they must be
separated with blanks. With functions, however, the opening parentheses must
immediately follow the name, for example, SQRT( ... )
Incorrect:
Correct:

a = (B+EXP(C))*E/SIN(3-G).
a = ( B + EXP( C ) ) * E / SIN( 3 - G ).

Non-numerical values are converted to numerical values prior to the arithmetical


operation.
The operators DIV and MOD are whole number division functions (see the online
documentation HELP COMPUTE).
The STRLEN function returns the length of a string.
Arithmetical expressions can only be used within the framework of the
COMPUTE statement.

Calculating Values for Numeric Fields


[COMPUTE] <field> = <arithmetic expression>.
Functions

Operators
+ DIV

/ *
MOD **

SQRT EX P LOG
SIN COS STRLEN
TAN ...

PROGRAM ....
DATA: counter
TYPE I,
amount
TYPE P VALUE 1000,
sum
TYPE P,
result
TYPE P,
number(2)
TYPE C VALUE '99',
root
TYPE F.
counter = counter + 2.
result = amount * counter.
sum = result + number
- counter.
result = counter * ( amount + number ).
root = sqrt( number + counter ).

Processing Character Strings


The CONCATENATE statement provides the ability to concatenate multiple
fields and place the result in a single field.
All the operands are treated as type C (character) fields regardless of their data
type. No internal data conversion is performed.
Trailing blanks in the operands (<f1> ... <fn>) are ignored.
The system return code SY-SUBRC is set to 0 (zero) if the operation was
successful or 4 if the result was found to be too long for the destination field <g>.
The addition SEPARATED BY <h> allows the insertion of one or more characters
between the fields <f1> ... <fn>.

Processing Character Strings


<Variable>+offset(length)
CONDENSE c.
Addition : NO-GAPS
CONCATENATE f1 ... fn INTO g.
Addition : SEPARATED BY h
SPLIT f AT g INTO h1 ... hn.
SPLIT f AT g INTO TABLE itab.
REPLACE f ...WITH g ...INTO h.
Addition : LENGTH len
(length specification for field f)
TRANSLATE var1 TO (UPPER/LOWER) CASE
SEARCH var FOR string.

String Processing Sub-string with Offsets


By specifying offset and length, parts of fields can be referenced and changed.
Only a few statements (ASSIGN, actual parameters, WRITE ... TO) support variable offset
and length specifications. For example, components of fields cannot be tested using an IF
statement (with variable offset and length).
DATA

NAME (30).
NAME(10) = ' Dr..
NAME+10(10) = 'Michael.
NAME+20(10) = 'Hofmann'.
CONDENSE NAME.
WRITE NAME.

NAME = NAME+4(14).
WRITE NAME.

String Processing CONDENSE Statement


Condense c no-gaps.
DATA: BEGIN OF NAME,
TITLE(8)
VALUE ' Dr.',
FIRST_NAME(10) VALUE 'Michael',
SURNAME(10) VALUE 'Hofmann',
END OF NAME.
CONDENSE NAME NO-GAPS.

String Processing CONCATENATE Statement


The CONCATENATE statement provides the ability to concatenate multiple fields and
place the result in a single field.
All the operands are treated as type C (character) fields regardless of their data type. No
internal data conversion is performed.
Trailing blanks in the operands (<f1> ... <fn>) are ignored.
The system return code SY-SUBRC is set to 0 (zero) if the operation was successful or 4 if
the result was found to be too long for the destination field <g>.
The addition SEPARATED BY <h> allows the insertion of one or more characters between
the fields <f1> ... <fn>.

String Processing CONCATENATE Statement


CONCATENATE f1fn INTO g.
DATA: ONE(10) VALUE ' John ',
TWO(3) VALUE 'F.',
THREE(10) VALUE ' Kennedy',
NAME(20),
FIRST TYPE STRING.
CONCATENATE ONE TWO THREE INTO NAME.
DATA: ONE(10) VALUE 'John',
TWO(3) VALUE 'F.',
THREE(10) VALUE 'Kennedy',
NAME(20).
CONCATENATE ONE TWO THREE INTO NAME SEPARATED BY SPACE.

String Processing SPLIT Statement


SPLIT f AT g INTO h1hn.
DATA: NAMES(30) TYPE C VALUE 'Charly, John , Peter',
NAMES2
TYPE STRING,
ONE(10)
TYPE C,
TWO(10)
TYPE C,
THREE
TYPE STRING,
FOUR(4)
TYPE C VALUE 'FOUR',
DELIMITER(2) VALUE ','.
SPLIT NAMES AT ',' INTO ONE TWO THREE.

SPLIT NAMES AT DELIMITER INTO ONE TWO.

String Processing REPLACE and TRANSLATE Statements


REPLACE f WITH g INTO h.
DATA FIELD(10).
MOVE 'ABCB' TO FIELD.
REPLACE 'B' WITH 'string' INTO field.
TRANSLATE var1 TO (UPPER/LOWER) CASE.
DATA FIELD(10).
MOVE 'ABCB' TO FIELD.
TRANSLATE FIELD TO LOWER CASE.
WRITE FIELD.

Date Calculations
If a date field is assigned to a packed field, ABAP calculates the number of days
since the beginning of the year 1900.
Conversely, if a packed field is assigned to a date field, it is interpreted as the
number of days since the beginning of the year 1900.
Before an arithmetic operation is performed, the values of the date fields are
converted to packed values (number of days since the beginning of the year
1900).
Beware - it is not possible to ADD 1 to the current month like: DATE_2 (6) =
DATE_2 (6) +1
In this case a conversion is made and the field no longer contains 19980331 but
00000431!

Date Calculations

PROGRAM YA70D049.
DATA: v_DIFF TYPE P,
v_DATE_1 LIKE SY-DATUM,
v_DATE_2 LIKE SY-DATUM.
* Initialize to value of System Date
v_DATE_1 = SY-DATUM.
V_DATE_2 = SY-DATUM.

* Set DATE_2 to first day of current month


v_DATE_2+6(2) = '01'.
* Set DATE_2 to last day of previous month
v_DATE_2 = DATE_2 - 1.
* Calculate difference in days
v_DIFF = v_DATE_1 - v_DATE_2.

ABAP Events
ABAP is event driven. This means that program processing is not necessarily carried out
in the order which the code is written in. It is processed in the established events
sequence.
INITIALIZATION - processed prior to the display of the Selection Screen.
AT SELECTION-SCREEN - processed immediately after the selection screen is
processed.
START-OF-SELECTION - processed immediately after INITIALIZATION.
GET - retrieves data from a logical database (this will be discussed later in this course).
GET LATE - processed after all records in a lower logical database hierarchy have been
processed (this will be discussed later in this course).
END-OF-SELECTION - processed at the end of the program, after all GET events.
TOP-OF-PAGE - processed before the first Write statement of a new page.
AT LINE-SELECTION - picks up lines for drill-down reports (drill-down reports are not
covered in this course).

INITIALIZATION and START-OF-PAGE Events


The INITIALIZATION event occurs after the data declaration portion of the program. The code under
this event is typically used to define the initial values of the parameters and the select-options before
the initial selection screen appears.
The START-OF-SELECTION event defines code that will be processed initially. (NOTE: For simple
programs, most code will be contained within this event.) This event is particularly important when
working with logical databases, which will be introduced later in this course.
REPORT ZEXAMPLE.
PARAMETERS:

P_NAME LIKE SY-UNNAME,

P_DATE LIKE SY-DATUM.

INITIALIZATION.

P_NAME = SY-UNAME.

P_DATE = SY-DATUM - 1.

START-OF-SELECTION.

WRITE: / Start of Program.

WRITE: / P_NAME.

WRITE: / P_DATE.

AT-SELECTION-SCREEN Event
The event AT SELECTION-SCREEN is processed after the selection screen
from a program is processed. For example, the selection screen is brought up
on-screen, the user enters data, and then clicks the Execute button. Before any
code starts, the code after the AT SELECTION-SCREEN command is executed.
The event AT SELECTION-SCREEN is particularly useful to check user input for
valid or implausible values. The user can then reprocess the screen if the initial
data input was invalid.
Every error message processed at the event AT SELECTION-SCREEN
immediately stops the execution of the report and displays the selection screen
again. All selection criteria can be changed.
In the example above, if the user doesnt enter any data but clicks the Execute
button anyway, the message Please enter some data pops up, and the
selection screen is reprocessed.

AT-SELECTION-SCREEN Event

REPORT ZABAP.
PARAMETERS:

P_NAME LIKE SY-UNAME.

AT SELECTION-SCREEN.
IF P_NAME <> .
MESSAGE I999 WITH Please enter some data.
ENDIF.
START-OF-SELECTION.
WRITE: The current user is, P_NAME.

Creating Selection Screen Boxes


The syntax for creating a box around parameters on a selection screen is as above. The
screen output from the syntax is also shown.
A selection screen box is useful for grouping several questions/ criteria which are related
and it makes the screen easier to read.
A title can be inserted into the frame, to indicate what the box is for by using the syntax
with frame title title1 and then declaring the text for title1 by using an initialization
statement.

REPORT YA01DH01.
SELECTION-SCREEN BEGIN OF BLOCK B1
WITH FRAME TITLE TITLE1.
PARAMETERS: P_INT1 TYPE I DEFAULT 20,
P_INT2 TYPE I.
SELECTION-SCREEN END OF BLOCK B1.
INITIALIZATION.
TITLE1 = TEXT-001.

Processing Data

Exercise 8 Create an Adding Machine for Integers, 30 min.


Exercise 9 - Add Number of Days to Date, 40 minutes

Control Statements Overview

Case distinction
IF
CASE

ENDIF
ENDCASE

DO
WHILE

ENDDO
ENDWHILE

Loops

Other control statements


CHECK
EXIT

CONTINUE

CONTROL STATEMENTS Conditional Branching

* previous command
log_expr_1

true

Block 1

Statement block 1

false
log_expr_2

IF log_ expr _1.

true

Block 2

ELSEIF log_ expr _2.


Statement block 2

false

false
log_expr_n
false
Block n+1

Next statement

true

optional
Block n

ELSEIF log_ expr _n.


Statement block n

ELSE
ELSE.
Statement block n+1

ENDIF
ENDIF .
* next command

CONTROL STATEMENTS CASE Control Structure

do_1 = do_2

true

Block 1

false

do_1 = do_3
or
do_1 = do_4

* previous command
CASEdo_1.
CASE
WHENdo_2.
Statement block 1

true

Block 2

WHEN do
_3 OR
ORdo _4 ..
Statement block 2

false

optional
true

false
Block n+1

Next statement

Block n

Statement block n

WHEN OTHERS
OTHERS
WHEN
.
Statement block n+1

ENDCASE .
* next command

CASE DISTINCTIONS: CASE and IF Statements


An IF statement branches into a yes (IF) branch or an optional no (ELSE)
branch, depending on the result of the evaluation of a complex condition
The ELSE and ELSEIF statements are optional.
Any number of ELSEIF statements can be inserted between IF and ENDIF. Only
one of the statement sequences will be executed.
Control statements can be nested.
The most common condition should be included as the actions for the 1st IF
statement. This way, the IF statement should only be traversed one level deep
rather than going through several layers to find the most common condition.
A logical expression consists of comparisons, the logical operators NOT, AND,
and OR as well as parentheses.
Operators and parentheses are considered as words. Consequently, they must
be separated from one another by blanks.
When processing a logical expression, the order of priority for the logical
operators is: NOT AND OR.

CASE DISTINCTIONS: CASE and IF Statements


CASE <data object1>.
WHEN <data object2>.
statements

WHEN <data object4> OR <data object5>.


statements

WHEN OTHERS.
statements

ENDCASE.

IF <logical expression>.
statements

ELSEIF <logical expression>.


statements

ELSEIF <logical expression>.


statements

ELSE.
ENDIF.

statements

IF Statements: Logical Expressions


... <field>

<operator>

<literal> ...

... <field1> <operator>

<field2> ...

... <logical expression> AND <logical expression>


... <logical expression> O
R <logical expression>
... NOT <logical expression>
...

DATA:

start
sum1

IF sum2 GE 1000.
IF start IS INITIAL.
IF sum1 GT sum2 AND
sum1 BETWEEN 0 AND 100.
IF sum1 = 1000 AND
( sum2 LE 2000 OR
start IS INITIAL ).
IF NOT start IS INITIAL.

TYPE D,
TYPE P,
sum2

Operator
EQ
NE
GT
GE

=
<>
>
>=

LT
LE

<
<=

TYPE P.

Meaning

=>

Equal
Unequal
Greater than
Greater than or equal

=<

Less than
Less than or equal

><

BETWEEN f1 and f2

Interval

IS INITIAL

Initial value

LOOPING COMMANDS: DO and WHILE Loops


In a DO Loop Parameter <n> TIMES is optional - n can be a constant or a field.
If this parameter is not specified, a termination condition must be included within
the loop statement (see EXIT statement).
In a WHILE loop, the statement sequence will continue to be executed for as
long as the conditions of the logical expression at the top of the loop are fulfilled.
There is no limit to the number of nesting levels for loop statements.
The system field SY-INDEX holds the value of the current loop pass for DO and
WHILE loops. The first time that the statements within the loop are processed,
SY-INDEX will have a value of 1.
The number of loop passes can be controlled via the SY-INDEX system field.
For WHILE Loops: Log. Exp = ENTRY criteria
For DO Loops: Log. Exp = EXIT Criteria

LOOPING COMMANDS: DO and WHILE Loops

DO [ < n>
TIMES ].
statements

statements

ENDWHILE.

ENDDO.
DO.
WRITE / sy-index.
IF sy-index > 10.
EXIT.
ENDIF.
ENDDO.

SY-INDEX

WHILE <logical expression>.

Loop index

counter = 10.
WHILE counter > 0.
statements

SUBTRACT 1 FROM counter.


ENDWHILE.

OTHER CONTROL COMMANDS: CHECK Statement


The CHECK statement has three primary applications.
Conditional termination of a Loop pass
Conditional termination of a Subroutine
Conditional termination of a Processing Block

In this section the focus is on the 1st application, conditional termination of a loop
pass. The other uses for the CHECK statement will be discussed in later
sections of the course.
The CHECK statement is accompanied by a logical expression (i.e. v_counter >
1, v_date = 03/22/1999).
When the logical expression accompanying the CHECK is TRUE, processing of the loop
pass continues without interruption.
When the logical expression accompanying the CHECK is FALSE, the subsequent
statements in the current loop pass are skipped and processing resumes with the next
loop pass.

Key point -> A FALSE CHECK does not terminate the loop, it only affects the
current loop pass.

OTHER CONTROL COMMANDS: CHECK Statement


CHECK <logical expression>.
REPORT ZEXAMPLE.
DO 10 TIMES.
CHECK SY-INDEX BETWEEN 4 AND 7.
WRITE: / The index value is: , SY-INDEX.
ENDDO.
Report Output
Report ZEXAMPLE
-------------------The index value is 4
The index value is 5
The index value is 6
The index value is 7

Note that this line of code was


only executed when condition specified
in the CHECK statement was TRUE.

OTHER CONTROL STATEMENTS: EXIT Statement


The EXIT statement is used in a number of different ways in both ABAP report
programs and ABAP screen programs. This section focuses on the use of EXIT
within a loop construct.
Upon encountering an EXIT statement, the system immediately leaves the loop
and continues the processing after the closing statement (ENDDO, ENDWHILE,
ENDSELECT). Within nested loops, the system only leaves the current loop.
Note the difference between CHECK and EXIT - CHECK terminates the current
loop pass whereas EXIT terminates the entire loop (i.e. the current loop pass is
interrupted and no additional loop passes are processed).

OTHER CONTROL STATEMENTS: EXIT Statement


EXIT.
REPORT ZEXAMPLE.
DO 10 TIMES.
IF SY-INDEX = 4.
EXIT.
ENDIF.
WRITE: / The index value is: , SY-INDEX.
ENDDO.
Report Output
Report ZEXAMPLE
-------------------The index value is 1
The index value is 2
The index value is 3

Note that this line of code was


only executed 3 times. This is because
the EXIT statement terminated the loop
completely on the 4th loop pass prior to
this statement.

OTHER CONTROL STATEMENTS: CONTINUE Statement


The CONTINUE statement is the third statement that can be used to
conditionally terminate a loop pass. Unlike CHECK and EXIT, which can be
used outside of loops, the CONTINUE statement is only used in loop processing.
CONTINUE terminates the current loop pass, returns the processing to the
beginning of the loop, and starts the next loop pass (if there is one).

OTHER CONTROL STATEMENTS: CONTINUE Statement


CONTINUE.
REPORT ZEXAMPLE.
DO 10 TIMES.
IF SY-INDEX < 8.
CONTINUE.
ENDIF.
WRITE: / The index value is: , SY-INDEX.
ENDDO.

Report Output
Report ZEXAMPLE
-------------------The index value is 8
The index value is 9
The index value is 10

Note that this line of code was


only executed once the index value
because greater than 8. When the
index value was less than 8, the
CONTINUE statement caused this
statement to be skipped.
127

Flags
Flags are a good way to keep track of variable changes or first time loop entries/
exits. A flag can be defined as simply as a one character variable which initially
is left blank and populated when a change occurs.
Flags are often teamed up with IF statements and used to help determine the
next step of the program based on their value.
REPORT ZEXAMPLE.
DATA: FLAG TYPE C.
DO 3 TIMES.
IF FLAG IS INITIAL.
WRITE: / First Time Through.
FLAG = X.
ELSE.
WRITE: / Hello!.
ENDIF.
ENDDO.

Report Output
Report ZEXAMPLE
-------------------First Time Through
Hello!
Hello!

Control Statements

Exercise 10 Create a Calculator, 40 min.


Exercise 11 Calculate the Squares of Whole Numbers, 30 min.
Exercise 12 Calculate a Table, 50 min.

Internal Tables
Internal tables are tables which are defined within an ABAP program and exist
only within system memory. They are not stored or maintained in the database.
These tables are used within programs for temporary storage and processing
and are not meant for long term storage of information.
An internal table consists of a number of identically structured table lines.
Internal tables fulfil the same function as arrays in C. They are dynamic data
objects (dynamic in that they are created at runtime) and save the programmer
the task of dynamically managing memory within his or her ABAP program.
Internal tables are the best way of including complicated data structures within
an ABAP program.

Internal Tables
Data type
Predefined
(P, I, F, C, N, D, T, X)

User-defined

Elementary

Structure type

Structured

Table type

INTERNAL TABLES: Table Attributes


An internal table is specified by its:
Line TYPE - The line TYPE of an internal table refers to the TYPE statement that defines
the field string that will act as the template for each row of the internal table. Each row in
the internal table will contain each of the fields specified in the this TYPE definition.
Key - The key of the table is used to identify individual table rows. A key can be defined
as UNIQUE or NON-UNIQUE (duplicate entries cannot be contained within a table with a
UNIQUE key). There are two kinds of keys for internal tables:

standard key - made up of all non-numeric fields (columns) in the internal table
user-defined key - made up of fields specified by the user (in this example, the field
PERSBR is the key)
Table type - The table type defines how ABAP accesses individual table entries. There
are 3 types of internal tables (STANDARD, SORTED and HASHED), each with a
different access method. These will be discussed in more detail later in this section.

INTERNAL TABLES: Table Attributes

TYPES: itabtype TYPE table_kind OF line_type WITH key_def [INITIAL SIZE n].
DATA:

t_name TYPE itabtype.

TABLE KIND
STANDARD TABLE

KEY_DEF
[NON-UNIQUE] KEY col1coln
DEFAULT KEY

SORTED TABLE

{UNIQUE | NON-UNIQUE} KEY col1coln

HASHED TABLE

UNIQUE KEY col1coln

Declaring an Internal Table


With the addition of the new table types for release 4.0 can new syntax for
defining internal tables.
In the above example, note that TYPE declaration of the field string is done the
same way in release 3.x and release 4.x. All of the changes are within the
declaration of the table itself with the DATA statement.
When declaring an internal table in release 4.x, the programmer can specify:
The table name (Mandatory)
The table type: standard, sorted or hashed (Mandatory)
The field string (TYPE) that defines the layout of each table row (Mandatory)
The table key and its associated uniqueness qualifier (Optional for Standard Tables and
mandatory for sorted and hashed tables)
The initial size (in rows) of the table (Mandatory - this is used internally by SAP in order
to determine the amount of memory to allocate for the table)
A work area or header line to be used to facilitate table manipulation. (These concepts
will be discussed later in this section).

Declaring an Internal Table


PROGRAM Z40_EXAMPLE.
TYPES: BEGIN OF T_EMPLOYEE,
PERSNBR(6)
TYPE N,
LASTNAME(20) TYPE C,
END OF T_EMPLOYEE.
DATA: I_EMPLTAB TYPE STANDARD TABLE
Type
OF T_EMPLOYEE WITH KEY UNIQUE PERSNBR
declaration
remains the
INITIAL SIZE 10,
same.
WA_EMPLTAB TYPE T_EMPLOYEE.

New
Syntax

PROGRAM Z30_EXAMPLE.
TYPES: BEGIN OF T_EMPLOYEE,
PERSNBR(6)
TYPE N,
LASTNAME(20) TYPE C,
END OF T_EMPLOYEE.
DATA:
I_EMPLTAB TYPE T_EMPLOYEE OCCURS 10,
WA_EMPLTAB TYPE T_EMPLOYEE.

Old
Syntax

Defining Internal Tables


The table name (Mandatory)
The table type: standard, sorted or hashed (Mandatory)
The field string (TYPE) that defines the layout of each table row (Mandatory)
The table key and its associated uniqueness qualifier (Optional for Standard Tables and
mandatory for sorted and hashed tables)
The initial size (in rows) of the table (Mandatory - this is used internally by SAP in order
to determine the amount of memory to allocate for the table)
A work area or header line to be used to facilitate table manipulation. (These concepts
will be discussed later in this section).

Defining Internal Tables


TYPES

<itabtype> TYPE <tabkind> OF <linetype>


LIKE <tabkind> OF <lineobj>
[WITH {UNIQUE|NON-UNIQUE} KEY <keydef>]
[INITIAL SIZE <n>] [WITH HEADER LINE].

DATA

<itabname> TYPE <tabkind> OF <linetype>


LIKE <tabkind> OF <lineobj>
[WITH {UNIQUE|NON-UNIQUE} KEY <keydef>]
[INITIAL SIZE <n>] WITH HEADER LINE.

TYPES: BEGIN OF
struc ,
name(10) TYPE c,
age(3) TYPE n,
END OF struc .
TYPES: itab _type TYPE
STANDARD TABLE OF
struc
WITH KEY name.
DATA : itab
TYPE itab _type.

TYPES: atab _type LIKE


STANDARD TABLE OF
spfli WITH KEY
carrid.
DATA :

atab

TYPE atab

_type.

DATA : btab
LIKE STANDARD
TABLE OF spfli WITH KEY
carrid.

Internal Table Types and Keys


There are three different types of internal tables: standard, sorted and hashed.
Each of the three table types has a different characteristics:
Standard Table - Has an internal linear index. The system can access records either by
using the table index or the key. The response time for key access is proportional to the
number of entries in the table. A unique key cannot be specified for a standard table.
Sorted Table - Table entries are always saved according to the key. Sorted tables also
have a linear index. The system can access records by either the table index or the key.
The response time for key access is logarithmically proportional to the number of table
entries, since the system uses a binary search. The key of a sorted table can be either
unique or non-unique; this must be specified in the table definition.
Hashed Table - Has no linear index. Table entries can only be accessed using a key.
The response time is independent of the number of table entries, and is constant, since
the system uses a hashing algorithm (a complex mathematical formula outside the
scope of this course). The key of a hashed table must be unique; the UNIQUE qualifier
must be used when defining a hashed table.

The availability of 3 different internal table types is new for SAP 4.0. Prior to 4.0,
the standard table was the only table type.

Internal Table Types and Keys


Standard

Sorted

Hashed

Key access
Table Scan

Access time
for n entries

Binary Search

Hash Function

Increases linearly
(O(n))

Increases
logarithmically
(O(log(n)))

Predominantly index

Predominantly key

Key only

NONUNIQUE

UNIQUE | NON-UNIQUE

UNIQUE

Constant

Access using

Uniqueness

Overview: Accessing Single Records


Overview: Accessing Single Records
Append

APPEND
APPEND wa_itab to itab.

Insert

INSERT

Read

READ TABLE itab INTO

Change

MODIFY TABLE itab FROM

Delete

DELETE
DELETE itab <condition>.

wa_itab INTO TABLE

itab <condition>.

wa_itab <condition>.

wa [<condition>].

Internal Table Work Areas


Table entries (i.e., rows within an internal table) cannot be accessed directly via
subscripting. This is different from array processing in most other languages,
which tend to allow access in the manner of FIELDA(1), FIELDA(2) in order to
access fields in different table rows.
In order to manipulate (i.e. change, write, move) data within a row of an internal
table, that row must first be put into a work area. Commands commonly used
to put a table row into a work area are LOOP and READ. These commands will
be discussed in detail later in this section.
The work area can only hold one row of table data at a time.

Internal Table Work Areas

Work area <wa>

APPEND ... <itab>.


INSERT ... <itab>.

Internal table < itab >


AA
LH

0017
0400

MODIFY <itab>
DELETE <itab>
SORT <itab> BY <field1><fieldn>.
CLEAR < itab >.

LOOP AT < itab


READ TABLE <itab>

Internal Table with Header


Prior to SAP R/3 Release 3.x, table entries were manipulated in header lines, as opposed
to work areas. Work areas were a new concept introduced with 3.x.
Whereas a work area defined as a separate data object within in ABAP program, the work
area is defined as a part of the table definition itself by adding the WITH HEADER LINE
qualifier to that table definition.
The header line is used in the same manner as a work area. What is confusing, however,
is the fact that the table and the header line essentially have the same name. (This is a
function of the fact that the header line is defined as a part of the table definition and not as
a separate data object within the ABAP program.)
SAP would like to eliminate the use or header lines, as their existence in the ABAP
language creates some issues as ABAP becomes more and more object oriented. When
header lines are used with internal tables that are nested within other internal tables it can
lead to ambiguous expressions. Therefore, it is recommended that tables be created
without header lines whenever possible.
For upward compatibility reasons, all ABAP commands used with internal tables still
support header lines, and the usage of header lines is still fairly common, especially for
SAP customers that initially implemented SAP on a release prior to 3.x.

Internal Table with Header


DATA

<itab> TYPE < itabtype > [ [WITH


WITH
HEADER
HEADER
LINE]
LINE ].

Work area <wa>


Internal table < itab >
CARRID
AA
LH

CONNID
0017
0400

Header line < itab >


Internal table < itab >
CARRID
AA
LH

CONNID
0017
0400

APPEND < wa > TO <itab>.


MODIFY <itab> INDEX <n> FROM <wa >.

APPEND <itab>.
MODIFY <itab> INDEX <n>.

LOOP AT <itab> INTO < wa >.


WRITE <wa >-<field >.
ENDLOOP.

LOOP AT <itab>.
WRITE <itab>-< field>.
ENDLOOP.

READ TABLE <itab> INDEX <n> INTO < wa>.


WRITE <wa>-< field >.

READ TABLE <itab> INDEX <n>.


WRITE <itab>-< field >.

Filling Internal Tables


The APPEND statement appends the contents of the header line or (for internal

tables without a header line) the work area <wa> at the end of the internal table.
The maximum number of table entries is determined by the INITIAL SIZE
(OCCURS in R/3) parameter. If there is no space in the table for a further entry,
the last table entry is written to the roll area.
The APPEND <tab> SORTED BY <f> statement adds a new entry to an internal
table and sorts the table by field f in descending order. Again, the maximum
number of table entries is determined by the INITIAL SIZE parameter. However,
with this variation of the APPEND statement, if there is no space in the table for
a further entry, the last table entry is removed. This variation, therefore, is
most commonly used for created ranked lists - the top ten companies according
to sales figures, for example.

Filling Internal Tables


APPEND [<wa> TO] < itab>.
REPORT sapbc400itd_declaring_filling.
DATA: it_ flightinfo LIKE STANDARD TABLE OF spfli.
DATA: wa_flightinfo LIKE spfli.
SELECT * FROM spfli into wa_flightinfo
where carrid = 'AA'.
APPEND wa_flightinfo TO it_ flightinfo.
ENDSELECT.

Internal table
SPFLI
AA

SELECT

0026

AA

0026

Table work area

APPEND

it_flightinfo

CARRID

CONNID

...

AA

0026

...

Filling Internal Tables: Array Fetch


The statement SELECT <tab> INTO TABLE <i_tab> transfers the entire

contents of a database table to an internal table in one single statement. Any


existing contents of the internal table are overwritten. (To avoid overwriting, use
the APPENDING TABLE qualifier).
This SELECT statement is executed as a single statement, not a loop, so no
ENDSELECT statement is needed.
The INTO statement has several variants, including
INTO CORRESPONDING FIELDS OF TABLE <i_tab>
APPENDING TABLE <i_tab>.

If at least one record is selected, SY-SUBRC = 0 otherwise, SY-SUBRC = 4.


For more information, refer to SAP Help.

Filling Internal Tables: Array Fetch


REPORT sapbc400itd_declaring_filling.
:
DATA: it_ flightinfo
LIKE TABLE OF spfli.
DATA: wa_ flightinfo LIKE spfli.
* SELECT * FROM spfli INTO wa_flightinfo WHERE carrid = 'AA'
*
APPEND wa_flightinfo TO it_ flightinfo.
* ENDSELECT.
SELECT * FROM spfli INTO TABLE it_flightinfo WHERE carrid = 'AA'.
Internal Table
AA
AA
AA
AA
AA

SPFLI
0017
0017
0026
0026
0064

it_flightinfo

CARRID

CONNID

...

AA
AA
AA
AA
AA

0017
0017
0026
0026
0064

...
...
...
...
...

Sorting an Internal Table


It is possible to sort an internal table with the SORT statement (only for Standard
tables). If sort criteria is not specified, the table is sorted by all fields with the
exception of the fields of data types P, I, and F in ascending order in the
sequence in which they were declared. (A Sorted table cannot be resorted).
With the additional specifications BY <field name> and ASCENDING or
DESCENDING, the sort process can be restricted to specific fields (or to fields of
type P, I, or F) which determine the sorting sequence and hierarchy.
Where possible, limit the number of sort fields with the BY parameter. ABAP
then requires less storage space in the roll area for the sorting process.

Sorting an Internal Table


SORT < itab > BY <f1> <f2> . . . .
REPORT sapbc400itd_
itab_sort.
:
DATA: it_flightinfo TYPE TABLE OF spfli.
SELECT * FROM spfli INTO TABLE it_flightinfo.
SORTit_flightinfoBY cityfrom deptime.
.
.
SORT it_flightinfo BY cityfrom ASCENDING
deptime DESCENDING
carrid ASCENDING AS TEXT.

Loop Processing in Internal Tables


An internal table is processed with the LOOP AT ... ENDLOOP statement. On each loop pass, the
system places a table entry in the work area or header line. If table fields are referenced in the
program, these are the fields in the work area or header line (the fields found in the header line are
used).
If no entries are found to exist in the specified table, the loop cannot be executed and the system field
SY-SUBRC will be set to a value of 4. If one or more entries exist in the table SY-SUBRC will be set to
0 (zero).
After the WHERE parameter, a logical expression can be specified (see chapter on Control
Statements).

- select from i_tab where <log exp>.

The sequence in which the entries occur in the loop depend on the table type specified in the table
definition (unless the table has been explicitly resorted using the SORT statement:
STANDARD TABLE: The system processes entries according to their logical index. At the beginning
of a loop pass, SY-TABIX is set to the logical index of the current table entry.
SORTED TABLE: The system processes entries according to their sort order. As with standard
tables, the system sets SY-TABIX to the logical index of the current table entry.
HASHED TABLE: The system processes entries in the order in which they were inserted into the
table. Since hashed tables have no logical index, SY-TABIX is always set to 0.

Loop Processing in Internal Tables


LOOP AT <itab> [INTO <wa>]ENDLOOP.

REPORT sapbc400itd_itab_loop.
DATA: it_ flightinfo LIKE TABLE OF spfli WITH KEY carrid.
DATA: wa_ flightinfo LIKE spfli.
SELECT * FROM spfli INTO TABLE it_flightinfo.
LOOP AT it_flightinfo INTO wa_flightinfo FROM 5 TO 10.
WRITE: / wa_flightinfo-carrid,
ENDLOOP.
LOOP AT it_flightinfo INTO wa_flightinfo
WHERE carrid = 'LH'
.
WRITE: / wa_ flightinfo-carrid, wa_flightinfo -connid...
ENDLOOP.
IF sy- subrc NE 0.
WRITE: 'No records met selection criteria.'.
ENDIF.

Internal Tables

Exercise 13 Create a Ranked List for Highest Sales, 50 min.


Exercise 14 Using the For All Entries statement, 60 min.

Reading Individual Internal Table Entries


The READ TABLE statement is used to locate a specific entry within an internal table and
put the contents of that entry into the work area (or header line if a header line is being
used in lieu of a work area).
There are a number of variations of the read statement:
READ TABLE I_TAB INTO WA_TAB INDEX 7 (In this example, 7 is an index value that
refers to the 7th row in the table).
READ TABLE I_TAB INTO WA_TAB WITH KEY CAN (In this example, CAN is a value
contained within the table within the key field COUNTRY. Note that in the example,
COUNTRY is defined as a NON-UNIQUE key, meaning that there may be more than one
record containing CAN in the country field. If duplicates keys exist, the READ
statement will only return the 1st one that it encounters.)
READ TABLE I_TAB INTO WA_TAB WITH KEY USA BINARY SEARCH (Binary search
is a faster method for searching internal tables, however the internal table must be
sorted in order to use this method. If possible, SAP recommends keeping internal tables
sorted and using this method.)
Each time a READ statement is executed, SY-TABIX is updated to contain the index value
of the row that was read and placed in the work area (or header line).

Reading Individual Internal Table Entries


READ TABLE <itab> [INTO <wa>]
REPORT sapbc400itd_itab_read.
DATA: tab_index LIKE sy-tabix.
DATA: it_ flightinfo LIKE TABLE OF spfli WITH KEY carrid connid.
DATA: wa_flightinfo LIKE spfli.
SELECT * FROM spfli INTO TABLE it_flightinfo.
MOVE: 'LH' to wa_ flightinfo-carrid,
'0400' to wa_flightinfo-connid.
READ TABLE it_ flightinfo INTO wa_ flightinfo
FROM wa_flightinfo .
IF SY-SUBRC NE 0.... ENDIF.
tab_index = sy- tabix + 1.
READ TABLE it_flightinfo INTO wa_ flightinfo
INDEX tab_index .
IF sy- subrc NE 0. ... ENDIF.

SY-TABIX
R

Changing an Internal Table with an Index


The MODIFY <tab> INDEX <i> statement overwrites table line i with the contents
of the work area. The system field SY-SUBRC will be set to zero if the entry is
successfully updated or 4 if the entry to be updated did not exist.
The INSERT <tab> INDEX <i> statement generates a new table entry with the
contents of the header line. If no index value is specified, the new table entry will
be inserted immediately prior to the current line (i.e. the current value of SYTABIX). The system field SY-SUBRC will be set to zero if the entry is
successfully inserted in the table or 4 if the entry to be inserted already exists.
The DELETE <tab> INDEX <i> statement deletes the table line specified by
INDEX. The system field SY-SUBRC will be set to zero if the entry was
successfully deleted or 4 if the entry to be deleted did not exist.
The usage of these commands differs for SORTED and HASH tables. Please
refer to SAP R/3 Help for more information.

Changing an Internal Table with an Index


INSERT [<wa> INTO] < itab > ..[INDEX <n>].
MODIFY < itab >[FROM <wa>] [INDEX <n>].
DELETE < itab > [INDEX <n>].

REPORT sapbc400itd_itab_change_index.
:
MOVE: 'LH' to wa_flightinfo-carrid,
'0400' to wa_flightinfo-connid.
READ TABLE it_ flightinfo INTO wa_ flightinfo
FROM wa_flightinfo.
MOVE NEW YORK' TO wa_flightinfo-cityfrom .
MODIFY it_ flightinfo FROM wa_flightinfo INDEX sy- tabix.
IF sy-subrc
NE 0. ...ENDIF.
..
INSERT wa_flightinfo INTO it_ flightinfo INDEX 5.
IF sy-subrc
NE 0. ...ENDIF.
..
.
DELETE it_ flightinfo INDEX 3.
IF sy-subrc
NE 0. ...ENDIF.

Changing an Internal Table with Keys


INSERT [<wa> INTO] TABLE <itab>.
MODIFY TABLE <itab> [FROM <wa>].
DELETE TABLE <itab> [FROM <wa>].

REPORT sapbc400itd_itab_change_key.
MOVE: 'LH' to wa_flightinfo-carrid,
0400 to wa_flightinfo-connid.
READ TABLE it_flightinfo FROM wa_flightinfo INTO wa_flightinfo.
IF sy-subrc <> 0. ENDIF.
MOVE NEW YORK TO wa_flightinfo-cityfrom.
MODIFY TABLE it_flightinfo FROM wa_flightinfo.
IF sy-subrc <> 0. ENDIF.
..
INSERT wa_flightinfo INTO TABLE it_flightinfo.
..
.
DELETE TABLE it_flightinfo FROM wa_ flightinfo.
IF sy-subrc NE 0. ENDIF.

Changing an Internal Table within a Loop


Within a LOOP, changes can be made to an internal table. The line affected is always the
current line (in the work area). During loop processing, the system field SY-TABIX holds
the index of the entry currently being processed.
MODIFY: The current line is overwritten by the contents of the work area.
INSERT: A new line with the contents of the work area is inserted before the current line.
DELETE: The current line is deleted.
After each of these operations the value of SY-SUBRC will be 0 (zero).
REPORT <name>.

LOOP AT <itab> INTO <wa>.

MODIFY <itab> FROM <wa>.

INSERT <wa> INTO <itab>.

DELETE <itab>.
..
ENDLOOP.

Clearing and Deleting an Internal Table

CLEAR <wa>.

Work area<wa>

Internal table <itab>


CLEAR <itab>.
REFRESH <itab>.

CARRID
AA
LH

CONNID
0017
0400

DELETE <itab>.
DELETE <itab> WHERE <logical Expression>.
DELETE <itab> FROM <index1> TO <index2>.

Collecting Internal Table Records


COLLECT <itab>.
COLLECT <wa> INTO <itab>.
Field1
Field2
-------------- ------1 JET
200
2 PLANE
100
3 CAR
300

wa_table-field1 = JET.
wa_table-field2 = 25.
COLLECT wa_table INTO it_table .
Field1
Field2
-------------- ------1 JET
225
2 PLANE
100
3 CAR
300

Determining Table Properties


The DESCRIBE statement provides information about an internal table.
The LINES parameter allows the user to find out the number of existing table
entries.
The OCCURS parameter provides the OCCURS value as specified in the table
definition in R/3 or as designated in the TYPE statement.
For details about other parameters of the DESCRIBE TABLE statement, see the
online documentation for the keyword DESCRIBE.
NOTE: The optional INITIAL SIZE addition is used to set the initial amount of
memory allocated to the table.

Determining Table Properties


DESCRIBE <itab> LINES <var_lines>
OCCURS <var_occurs>.
DATA : BEGIN OF it_table OCCURS 10,
FIELD1(10) TYPE C,
FIELD2(10) TYPE C,
END OF it_table.
DATA : w_occurs TYPE I,
w_lines TYPE I.
DO 12 TIMES.
it_table-field1 = 'ABCD'.
MOVE sy-index TO it_table-field2.
APPEND it_table.
CLEAR it_table.
ENDDO.
DESCRIBE TABLE it_table LINES w_lines OCCURS w_occurs.
WRITE : 'LINES : ', w_lines, 'OCCURS : ',w_occurs.

Hashed Table Restrictions


Index operations including APPEND, INSERT..INDEX, cannot be used.
REPORT <name>.
TABLES: TABNA.
TYPES: BEGIN OF line_type,
f1,f2,
END OF line_type.
DATA: TAB1 TYPE HASHED TABLE OF line_type
WITH UNIQUE KEY f1 with HEADER LINE.
TAB1-f1 = Y. TAB1-f2 = 1. INSERT TABLE tab1.
TAB1-f1 = X. TAB1-f2 = 1. INSERT TABLE tab1.
TAB1-f1 = A. TAB1-f2 = 1. INSERT TABLE tab1.
READ TABLE TAB1 WITH TABLE KEY f1 = A.
SORT TAB1 BY f1.
LOOP AT TAB1.
WRITE:/ TAB1-f1, TAB1-f2.
ENDLOOP.

Sorted Table Restrictions


Sorted tables cannot be filled using index operations (INSERT wa INTO tab1 INDEX tabix,
APPEND tab1 FROM wa) because this can disrupt the sort sequence.
REPORT <name>.
TABLES: TABNA.
TYPES: BEGIN OF line_type,
f1,f2,
END OF line_type.
DATA: TAB1 TYPE SORTED TABLE OF line_type
WITH UNIQUE KEY f1 with HEADER LINE.
TAB1-f1 = Y. TAB1-f2 = 1. INSERT TABLE tab1.
TAB1-f1 = X. TAB1-f2 = 1. INSERT TABLE tab1.
TAB1-f1 = A. TAB1-f2 = 1. INSERT TABLE tab1.
READ TABLE TAB1 WITH TABLE KEY f1 = A.
SORT TAB1 BY f1.
LOOP AT TAB1.
WRITE:/ TAB1-f1, TAB1-f2.
ENDLOOP.

Internal Tables

Exercise 15 Modify an Internal Table, 60 min.

SAP SQL to Access Database Tables

ABAP
Open SQL Native SQL

Database interface

SELECT Statement Overview


Use the SELECT statement to read table entries (records) from a table
(database).
Because the SELECT statement can potentially read more than one record from
a table, an ENDSELECT statement is required to build a processing loop for the
table.
The structure (field names, field attributes) of a table can be displayed via the
Help pushbutton (or Utilities -> Help on...). If using the editor in Command
mode, type the command SHOW <table> on the editor command line.
The TABLES statement is used to declare the structure of a table to the ABAP
program. For help, double-click on the table name or press F2.
Reference the fields of a table by specifying the table name followed by the field
name separated by a hyphen. For example: TABNA-COUNTRY
The System field SY-SUBRC holds a return code from the SELECT operation. It
will have a value of 0 if one or more table entries were retrieved, or 4 if no table
entries were retrieved (table is empty). In the SELECT loop the SY-SUBRC
value is always 0.

SELECT Statement Overview

Which columns?

SELECT

<result>

FROM <table>

INTO <target>

Where to?

WHERE <condition>

Which entries?

GROUP BY <fields>

How are they grouped?

ORDER BY <fields>.

How are they arranged?

Single line

}
Particular
column

Which tables?

Several lines

WHERE Clause Overview


The WHERE clause restricts the quantity of table entries to be read. In the
example shown here, only table entries where the table field TABNA-COUNTRY
has the value USA will be read.
The field specified in the WHERE clause to the left of the relational operator
must be a table field from the table to be read. It must be referenced here
without the table name.
The value of SY-SUBRC should always be checked after any operation against a
database table to check whether the operation was successful or not and then
take the appropriate action - for example, write out a suitable a message.
In a SELECT. ENDSELECT processing loop, a SY-SUBRC value of 0
indicates at least one matching record was found.

WHERE Clause Overview

SELECT <result> FROM <table> ...


... WHERE <table field> <operator> <value>.
... WHERE <table field> BETWEEN <value1> AND <value2>.
... WHERE <table field> IN (<value1>, <value2>, ).
... WHERE <table field> IN <

seltab >.

ENDSELECT.

< operator >


EQ
GE
LE

=
>=
<=

NE
GT
LT

<>
>
<

=>
=<
><

Using the SELECT Statement for a Single Line


When the values of all key fields of a table entry are known, use the SELECT SINGLE
form of the SELECT statement. In this variation of the SELECT statement, all key fields
must be specified in the WHERE clause.
Because this variation of the SELECT statement can retrieve at most only 1 entry from a
table, no corresponding ENDSELECT statement is required.
The SELECT SINGLE allows the user to access a single table entry from the database
table.
The parameters it requires are :
the database table from which the record is to be selected
the condition in the WHERE clause, using the full key of the

table entry

multiple condition using logical gates like AND, OR, NOT, if required

It then locates the table entry meeting the WHERE condition in the table work area
Its return code (SY-SUBRC) is:
0 : if it does locate a table entry
4 : if such a table entry does not exist in the defined table work area

Using the SELECT Statement for a Single Line


SELECT SINGLE <f1> .. <fn >FROM < dbtab >
...

INTO <wa>

...

INTO (<f1>, ..., <fn>)

...

INTO CORRESPONDING FIELDS OF <wa>


WHERE

<key1> <op> ... AND <key2> <op> ...

Table fields and work area fields have the same names
REPORT sapbc400ddd_select_single.
DATA wa_spfli LIKE spfli.

Table SPFLI

SELECT SINGLE
carrid connid airpfrom airpto
FROM spfli
INTO CORRESPONDING FIELDS OF wa_spfli
WHERE carrid = 'LH' AND connid = '400'.
WRITE: / wa_spfli-carrid, wa_spfli-connid,
wa_spfli-airpfrom, wa_spfli-airpto.

Using the SELECT Statement for Several Lines


To select individual columns from a database table, use the above form of the
SELECT statement.
Immediately following the SELECT keyword, list the fields (columns) to be
retrieved. A work area must be specified for each field listed INTO which the
data will be placed. The table header (work area) is not populated by this form of
the SELECT statement - only the field work areas are loaded with the values for
the fields listed.
The fields must be enclosed in parentheses and must be separated by a comma
(as above).
Alternatively it is possible to specify an Internal Table to be populated. This will
be discussed in later topics.

Using the SELECT Statement for Several Lines


SELECT <f1> .. <fn> FROM <dbtab>
...

INTO <wa>

...

INTO (<f1>, ..., <fn>)

...

INTO CORRESPONDING FIELDS OF <wa>

SELECT loop

WHERE <tabfld> <operator> <value>.


ENDSELECT.
Fills work area
REPORT sapbc400ddd_select_sflight.
DATA wa_sflight LIKE sflight.

Table SPFLI

SELECT carrid connid fldate seatsmax seatsocc


FROM sflight
INTO CORRESPONDING FIELDS OF wa_sflight
WHERE carrid = pa_carr.
Statements for every entry read

ENDSELECT.

SELECT DISTINCT Statement (Excluding Duplicates)


To exclude duplicates when retrieving data with the SELECT statement, use the
addition DISTINCT.
In the first example above, the statements within the SELECT ... ENDSELECT
processing loop will only be executed once for each unique value of the field
TABNA-COUNTRY.
In the second example above, the statements within the SELECT ...
ENDSELECT processing loop will only be executed once for each unique
combination of the fields TABNA-COUNTRY and TABNA-ID.
A number of Aggregate Expressions can be specified as part of the SELECT
statement, such as SUM(), AVG(), COUNT(). See Help file.

SELECT DISTINCT Statement (Excluding Duplicates)


REPORT B170D068.
TABLES: TABNA.
DATA: W_COUNTRY LIKE TABNA-COUNTRY.
SELECT DISTINCT COUNTRY INTO (W_COUNTRY)
FROM TABNA.
1st pass
statements

2nd pass

ENDSELECT.
REPORT B170D069.
TABLES: TABNA.
DATA: W_ID
LIKE TABNA-ID,
W_COUNTRY LIKE TABNA-COUNTRY
SELECT DISTINCT ID COUNTRY
INTO (W_ID, W_COUNTRY)
FROM TABNA.
statements
ENDSELECT.

TABNA
Country
AU
AU
USA
USA
USA

ID
12345678
22009520
10034766
22009520
99985763

TABNA
Country

1st pass
2nd pass

AU
AU
USA
USA
USA

ID
12345678
22009520
10034766
22009520
99985763

Aggregate Expressions
A number of Aggregate Expressions can be specified as part of the SELECT
statement.
The Aggregate Expressions currently available are:
AVG( )

- determines the average value of the specified field

COUNT( DISTINCT <f1> )


- determines the number of unique values that
exist for
the specified field <f1>.
COUNT( * )

- determines the total number of lines retrieved

MAX( )

- returns the highest value found for the specified field

MIN( )

- returns the lowest value found for the specified field

SUM( )

- returns the sum of all values for the specified field

The previously mentioned additions to the SELECT statement (WHERE, etc.)


can be combined with these aggregate expressions.

Aggregate Expressions
TABNA
Country
REPORT B170D06A.
TABLES: TABNA.
DATA: W_TOTAL TYPE I,
W_HIGH_ID LIKE TABNA-ID,
W_LOW_ID LIKE TABNA-ID.
SELECT COUNT( DISTINCT ID )
MAX( ID )
MIN( ID )
FROM TABNA INTO (W_TOTAL, W_HIGH_ID,
W_LOW_ID).
statements
ENDSELECT.

AU
AU
USA
USA
USA

ID
12345678
22009520
10034766
22009520
99985763

After SELECT :
W_TOTAL

4
W_HIGH_ID

99985763
W_LOW_ID

10034766

SELECT Statements

Exercise 16 Using the SELECT Statement, 20 min


Exercise 17 Using the SELECT SINGLE Statement, 25 min
Exercise 18 Using Aggregate Expressions, 30 min

Subroutines
Large programs need modularization. Subroutines can be used to break
programs into logical groups.
Subroutines keep the source code clearer and allow the reuse of program
sections.
When a program contains several identical or similar statement sequences,
repetition can be avoided through the use of subroutines.
Subroutines can receive parameters and change parameters.
For the sake of clarity, all subroutines should be grouped together at the start or
end of a program. This is automatically done if systems tools are used to create
them.

Subroutines
PROGRAM RSDEM001.

Calculate tax

PROGRAM RSDEM004.

Call calculate_tax

Call calculate_tax

Calculate tax

Subroutine
Calculate_tax

Defining and Calling Subroutines


A subroutine is defined with the key words FORM and ENDFORM.
A subroutine is called using the PERFORM command.
The PERFORM command can occur in the code prior to the physical location of
the FORM. Forms should be grouped together at the end of the program, one
after another.
When a PERFORM is executed, the system executes the named form and then
continues execution with the next command following the PERFORM.
The name of the form can be up to 30 characters long and should be descriptive
as to the purpose of the form.
Subroutines can have parameters passed to them, such as F1 in the example
above. However, parameters do not have to be passed.

Defining and Calling Subroutines

Defining a Subroutine:
FORM subroutine USING lp1 lp2.
...
...

ENDFORM.

Calling a Subroutine:
PERFORM subroutine USING f1 f2.

Example:
PERFORM CALCULATE_TAX USING FL1.
FORM CALCULATE_TAX USING F1.
CLEAR ITAB.
MOVE:
F1
TO ITAB-FL1.
APPEND ITAB.
ENDFORM.

Subroutines: Using Parameters to Pass Data


ABAP provides three variations of parameter passing.
USING - The USING clause allows for passing of parameters by both reference and by
value.

By Reference - When parameters are passed by reference, any changes to the


parameter (formal parameter) during the execution of the subroutine immediately
change the variable passed in the PERFORM statement (current parameter).

By Value - When parameters are passed by value, any changes to the parameter
(formal parameter) during the execution of the subroutine wont affect the original
variable (current parameter).
TABLES - Tables can only be passed by reference to a subroutine. The TABLES
parameter must always appear first in the FORM statement, before any USING or
CHANGING.
CHANGING - The CHANGING option passes parameters by value, but also transfers
any change of a parameter value back to the original variables when ENDFORM is
reached. This option is only appropriate for recursive subroutine calls, for which the
variable shouldnt be changed immediately but only when the subroutine ends.

Subroutines: Using Parameters to Pass Data

USING

Pass By Reference
Pass By Value

TABLES

Pass By Reference

CHANGING

Pass By Value & Result

Parameters Example
When calling a subroutine, data is transferred. Data determined within the
subroutine is passed back to the calling program.
When a subroutine is declared, Formal Parameters are defined.
When a subroutine is called, Current Parameters are specified, which are then
assigned to the formal parameters according to the sequence in the parameter
list. The calling program and the called program communicate with one another.
It is more efficient (i.e. cost effective) to pass by reference than to pass by value.

Parameters Example

Current Parameters
PERFORM CALCULATE_TAX USING FL1 FL2.
FORM CALCULATE_TAX USING F1 F2.
CLEAR ITAB.
MOVE F1 TO ITAB-FL1.
APPEND ITAB.
ENDFORM.
Formal

Parameters

In this example, parameters are passed by


reference. This is the most common, and most
cost effectively, method of parameter passing.

Passing Parameters
Both fields or tables of the current program can be included as current
parameters. Both are passed by reference.
Field and field strings are passed with the keyword USING.
Putting VALUE immediately before the parameter name allows the developer to
specify the formal parameters and defines a pass by value.
TYPE identifies the type of each of the formal parameters being passed.
The method for passing parameters determines how the formal and current
parameters are stored and how/if they are updated.
Pass by Value - When the subroutine is called, the formal parameters are copies of the
current parameters, with their own storage location.
Pass by Value and Result - The formal parameters have a separate storage location.
At the end of the subroutine, the value of the formal parameter is passed to the storage
location of the current parameter assigned to it.
Pass by Reference -The address of the current parameter is passed. When called, the
formal parameters are not allocated a separate storage location.

Passing Parameters

PROGRAM <name>.
TABLES:
....
DATA: ....
.
.
.
PERFORM <name> USING
<a1> <a2>
<a3> <a4>.
.
.
.
FORM <name> USING
VALUE(<f1>)
VALUE(<f2>)
<f3>
<f4>.
<statements>

a1

a2

f1

f2

a3

a4

Pass by value

Pass by reference

ENDFORM.

Internal Tables as Passed Parameters


Internal tables can be passed with the key word TABLES. Note that the structure
of the table is not passed with the keyword alone.
The TABLES parameter should always appear first in the PERFORM . . . FORM
statement, before any using.
In this model program, the structure of the passed table is unknown to the
subroutine.
An internal table is always passed by reference.

Internal Tables as Passed Parameters


REPORT B170D094
DATA: BEGIN OF TAB,
F1 LIKE TABNA-COUNTRY,
F2 LIKE TABNA-NAME1,
END OF TAB.
DATA: X.
PERFORM SUB1 TABLES TAB
USING X.

FORM SUB1 TABLES T USING Z.


LOOP AT T.
WRITE: / T.
ENDLOOP.
MOVE . . . TO T.
APPEND T.
ENDFORM.

Global and Local Data


Local data can be declared in subroutines.
These are only valid in the subroutine. These fields are created and initialised
again every time the subroutine is called.
Dont create a field in a subroutine that has the same name as a global field, the
local field is the one that is valid in the subroutine.
From within a subroutine it is possible to access all of the global fields for which
there is no local data.
The global field is not affected by the actions in the subroutine in the case of
double definition.

Global and Local Data


REPORT B170D091
TABLES: . . .
DATA: . . .
Global Data
X1

X1 Y1

Call Subroutine
Subroutines
Passed Parameters
DATA:

X Y

local data

statements
Passes Parameters
Data:

local data X1

statements

Y1

Persistent Local Variable: STATICS


The STATICS statement is a variation of the DATA statement.
The STATICS statement allows local objects to retain their values.
The STATICS statement can only be used within a subroutine (FORM) or
function module.
REPORT B170D092.
DATA: RESULT TYPE I.
PERFORM RANDOM_NUMBER CHANGING RESULT.
FORM RANDOM_NUMBER CHANGING P_RESULT TYPE I.
STATICS: L_STATE TYPE I.
L_STATE = ( L_STATE * 113 + 34 ) MOD 256.
P_RESULT = L_STATE.
ENDFORM.

Subroutines

Exercise 19 Passing Variables to a subroutine, 90 min.


Exercise 20 Passing an internal table to a subroutine, 60 min.

Debugging
Tool used to identify and eliminate errors in ABAP programs
Allows the verification of program logic in a step-by-step manner by examining
the results of individual statements
Key Debugging Concepts
Debugger modes
Examining the value of variables
Changing the value of variables
Setting breakpoints
Setting watchpoints
Viewing contents of internal tables

Branching to Debugging Mode


ABAP
Debugger
ABAP Editor

Object List
Development object ... ... ...

...
Test/execute
...

Debugging
Program

B170D051

Any screen

Breakpoints

... ... ... System Help

Program ... . Breakpoint ... .

/h

...
Utilities
...

...
Debug ABAP
...

Debugging Display
The source code window displays the statements currently being executed or
may be used to scroll through the code to set breakpoints.
Breakpoints are identified with a stop sign
The field evaluation window displays the value of selected fields.
F5 single step; commonly used for watching values or thorough step by step
process
F6 almost the same with single step but skips sub-routines
F7 for forwarding to the next break-point or finishing a loop
F8 run execution

Debugging Display

Debugging Mode
When entering the debugger there is a choice of 6 different views:
Fields - Displays the fields content and technical characteristics.
Table- Displays the contents of an internal table.
Breakpoint - Interrupts a program at a given line of code. Breakpoints can be static or
dynamic.
Watchpoint - Interrupts a program only when there is a change in the contents of a
particular field or filed string. It is possible to define multiple watchpoints, attach
conditions to them, and link two or more watchpoints using a relational operator.
Calls - Displays an active event chain and the call sequence up to the current
breakpoint. The most recent active call appear at the top of the list and the previous
calls appear underneath.
Overview - Displays the structure of the programs being debugged. This view shows the
event names and event types within a program and indicates which section is currently
being used.
Settings - Displays the different options and error handling a user has when debugging.

Debugging Mode

Examining the Value of Variables

To display the value of a


particular variable, doubleclick on the variable, which
will copy it to the field
evaluation window.
The variable name may also
be typed directly in the field
names column of the field
evaluation window.

Changing the Value of Variables


While executing the program
in debug mode, the value of a
field may be modified.
Once a field has been
selected and the
corresponding values are
displayed in the field
evaluation window, the field
value may be manually
changed in the field contents
column. The change
pushbutton (pencil icon)
should then be selected to
activate the field value
change.

Important Debugging Functions


Single Step

Processes the next program line

Execute

Executes all processing steps belonging to one line

Continue

Processing continues until the next breakpoint (or end of


program) is encountered

Table

Displays the contents of internal tables

Breakpoint

Used to define breakpoints

Watchpoint

Interrupts the program when there is a change in a field

Editor

Invokes the ABAP editor

Hexadecimal display

Data contents can be displayed in hexadecimal format

Replace

Allows the change of data contents during debugging

Setting Breakpoints
ABAP Editor

Debugging Mode

Menu:

Utilities
-> Breakpoints

Keyword:

BREAK-POINT

Line selection (double-click)


Breakpoint Pushbutton
Menu:

Utilities -> Breakpoint -> Set/delete/Display


(or Deactivate/Activate, Delete All
Activate All, Deactivate All,
Breakpoint at)
Goto -> Breakpoints

Watchpoints
A watchpoint is a signal within a programs code that tells the ABAP runtime processor to
interrupt a program at a particular point in the code.
Watchpoints are set from the debugger. Set and remove watchpoints as needed.
Watchpoints are field-specific. Use a watchpoint to observe the changes to a particular
field. The debugger interrupts the program when the fields contents change.
Watchpoints can be set either locally and globally. Global watchpoints are valid in all
programs that is called. Local watchpoints are only valid within a specified program.
Watchpoints:
Up to five watchpoints can be defined.
Conditional watchpoints using <, <=, =, <>, >=, >.
Can combine watchpoints with AND or OR.
Local and global watchpoints ( i.e. stop only in my program).
Menu from Debugging mode: Breakpoint -> Create Breakpoint.

Watchpoints

Viewing the Contents of Internal Tables

Using the Debugger

Exercise 21 Using the ABAP Debugger, 30 minutes

Introduction to Function Modules


Function modules are external subroutines stored in a central library with a
formalized interface.
They make general and cross-application functions available to the programmer.
There are numerous pre-defined function modules in the R/3 system. These can
be called from ABAP programs.
It is possible for programmers to create new function modules.
Function modules have names that are unique system-wide, to avoid confusion
when calling one by name.

Introduction to Function Modules

High Reusability
Clear import and
export parameters

STRING_CONCENATE/
READ_CALENDAR/
CURRENCY_CONVERSION/
ACCOUNT_CHECK/ ...

Search
Create
Change
Document

Application

Exception

Test Environment

handling

Remote Function Call

Function Groups
Several logically related function modules are combined in a function group
(also known as a function pool). Logically related function modules are typically
function modules that perform similar functions and/or use the same data).
Function modules contained in the same function group can share common data
declarations.
To create or maintain a function group, select Goto -> Function Groups -> Create
Group from the initial screen of the ABAP Function Builder transaction.

Function Groups
ABAP Function Builder: Initial Screen

Tools
ABAP Workbench

Function module
Function Builder

.
.
Function groups
.
.

Create Function Group


Function group
Short text
Person responsible
Save

....

Function group docu.

Calling a Function Module


Parameters are used to exchange data between function modules and the calling
program.
Import parameters are used to transfer data to the function module from the calling
program. Use the keyword IMPORTING.
Export parameters are used in function modules to pass results back to the calling
program. Use the keyword EXPORTING.
Export parameters are assigned values in the function module. On completion of the
function module the data in the exporting fields is passed back to the calling program.
Internal tables are passed to the function module by specifying : TABLES <table
parameter> = <internal table name>.
Exception parameters define the possible errors that the program may encounter. They
stop execution and tell the caller program what has happened. In the calling program, a
numeric constant is assigned to each exception. Use the keyword EXCEPTIONS.
HINT: When programming a function module call, use the Pattern pushbutton to insert the
function module interface into the code.

Calling a Function Module


Function Module
Maintenance
FM_02
Interface
Import
Export
Tables
Exceptions
Program
Documentation
Administration

How to call a
Function Module
CALL FUNCTION
'FM_02'
EXPORTING ...
IMPORTING ...
TABLES ...
(EXCEPTIONS ...)

Interfaces
One of the key differences between function modules and subroutines is the clearly
defined formal parameter interface.
Import parameters correspond to the formal input parameters of subroutines. They pass
data from the calling program to the function module. A default value can be assigned to
each import parameter in the Proposal column. This value may be a system field value
(ex. SY-DATUM), a literal that is enclosed in inverted commas, or the predefined field
SPACE. Import parameters with proposed values are optional. If no such parameter is
specified when the function module is called, the proposed value is used.
Changing parameters are import parameters which will be passed back to the calling
program (their values may or may not have been changed).
Export parameters correspond to the formal output parameters of subroutines. They are
optional - the calling program need only specify those parameters for which it wants a
value returned.
Struct./field column allows to specify a reference structure/field for a parameter. By
specifying these, it improves the run-time of function modules.
The Type column allows the specification of a user-defined data type.
Import values are passed by value. Changing and Export parameters are passed by
reference.

Interfaces
Import/Export Parameters Z_FUNC_DEMO1
Import parameters
Parameters

Struct./field

Type

Proposal Optional Ref.

Type

Proposal Optional Ref.

Type

Ref.

Changing parameters
Parameters

Struct./field

Export parameters
Parameters

Struct./field

Exception Processing
Table Parameters/Exceptions STRING_SPLIT
Exceptions
NO_DATA
DATA_NOT_VALID
STRING_TOO_LONG
...

FUNCTION STRING_SPLIT.
...
IF ...
RAISE NO_DATA.
ENDIF

CALL FUNCTION STRING_SPLIT


EXPORTING DELIMITER
= -
STRING
= TEXT
IMPORTING HEAD
= HEAD
TAIL
= TAIL
EXCEPTIONS NO_DATA
= 01
STRING_TOO_LONG = 02
OTHERS
= 03.
CASE SY-SUBRC.
WHEN 1. .... .
WHEN 2. .... .
WHEN 3. .... .
ENDCASE.

Function Module Example

Import
Parameters

Export
Parameters

Global Data / Local Memory


To create fields and internal tables that are to be available as global data in all
function modules and subroutines belonging to a function group - Select Global
Data from the initial screen of the function module transaction.
Table work areas (TABLES) are always global, no matter where they are
declared.
Local fields in a function module that are declared in the program of the function
module, are initialized before each call of the function module.
Global fields are initialized before the first call of a function module in a function
group. The global data with the values from the previous call is then available for
further calls to function modules belonging to the same group.
Within the global data, a local memory can be implemented for a single function
group.

Global Data / Local Memory


Global Data

L<gr> TOP
FUNCTION-POOL <gr>.
DATA: X.
TABLES: ... .

Function module

Subroutines

L<gr> U01

L<gr> F01

FUNCTION ... .
DATA:... .
MOVE X TO ... .
ENDFUNCTION.

FORM SUB1 USING ... .


DATA:... .
MOVE ... TO X.
ENDFORM.

Function Modules

Exercise 22 Using a Function Module, 45 min.

Remote Function Call


Remote Function Call (RFC) is an easy way to communicate between
application programs via ABAP function calls. It can be very useful for
companies with numerous subsidiaries that each have their own systems.
With the remote call, the called function can run in a different system on a
different machine in the network.
The additional parameter, DESTINATION, must be called for the remote call.
The parameters for the remote function must be set.
The remote function contains the context for subsequent calls.

Remote Function Call


R/2
System

R/3
Presentation
server

Mainframe

RFC with
C-interface

RFC

RFC

RFC

AP
R/3
System

RFC
System

AP

DB

R/3
System
DB

Searching the Function Builder

Tools

Tools
Tools

ABAP Workbench

ABAP Workbench

ABAP Editor

Function Builder

ABAP Repository Information System


Standard selections
Function module
Short description
Function group
Development class

Creating a Function Module


ABAP Function Builder: Initial Screen
Tools

Function module

Z_FUNC_DEMO1

ABAP Workbench

Create
Function Builder

Administration
Import/Export
Import/Export Parameters
Parameters

Up to 30 characters long
Alphanumeric and underscore only

Table Parameters/Exceptions
Documentation
Source code

Creating a Function Module


Function Module Create: Administration Z_FUNC_DEMO1
Classification
Function group
Application
Short text

ZGR1

Test Function Group

Basis (System)

This is a short description of Z_FUNC_DEMO1


Copy from

Z_ANOTHER_FUNC_MOD

Process type
Normal
Remote Function Call supported
.
.
.

Specifying Interface Parameters

Example of Calling a Function Module in a Program


The parameters of a function are classified as importing, exporting, or changing
parameters. In the call function statement, the formal parameters are listed on
the left of an equal sign and the actual parameters on the right.
The exporting and importing parameters are always understood from the current
point of view - that is, either from the calling program or the called function.
Therefore, they exchange their roles between the function definition and the
function call.
The function above converts temperature degrees between Fahrenheit and
Celsius. This kind of function has one import parameter to distinguish whether
the input is Fahrenheit or Celsius and a second one for the value. The export
parameter will contain the converted degrees.

Example of Calling a Function Module in a Program


Function CONVERT_TEMPERATURE
* Local interface:
*
IMPORTING VALUE (TEMP_UNIT) TYPE C
*
VALUE (DEGREES) TYPE P
*
EXPORTING REFERENCE (CONV_DEGREES) TYPE P
IF TEMP_UNIT = F.
CONV_DEGREES = ( DEGREES - 32 ) * 5 / 9.
ELSE.
CONV_DEGREES = DEGREES * 9 / 5 + 32.
ENDIF.
ENDFUNCTION.
This function can be called as follows:
DATA DEG TYPE P.
CALL FUNCTION CONVERT_TEMPERATURE
EXPORTING TEMP_UNIT
= F
DEGREES
= 100
IMPORTING CONV_DEGREES = DEG.

Function Module: Attributes


The Admin Parameter displays the General Data and classification of the function module
such as the function group in which the function module belongs to, development class / the
type of application, date last changed, and a short text describing the function module.
The Admin Parameter displays the Processing type of the function module
Normal Processing - normal on line dialog processing
Remote Function Call Supported - the function communicates outside the R/3 System,
i.e., communicating to an R2 system
For use in update
Start immediately - update mode is started immediately, i.e., user hits enter
Immediately start, no restart - update mode is started immediately but when comes
across a failure there is no restart.
Start delay - update mode will only start at the specified day / time.
Collective run - update mode is running multiple jobs
The person responsible for a function group releases a function module via Function
module -> Release -> Release. Releasing a function module means that it has been
documented and that the interface has been defined. No further changes can be made to
the interface after release of the module. However, a function modules can be called before
releasing them.
To change or extend the interface of a function module that has already been released, the
person responsible of the function group has to cancel the release of the module first
(Function module -> Release -> Cancel release).

Function Module: Attributes

Function Modules

Exercise 23 Creating a Function Group and Function Module,

60 minutes

ALV Reporting

The ALV grid control ( ALV = ABAP List Viewer ) is a flexible tool
for displaying lists.

The tool provides common list operations as generic functions


and can be enhanced by user-defined options.

This allows you to use the ALV grid control in a wide range of
application programs.

ALV Graphic Presentation

Title

Generic Function
of the Toolbar

Output Table in
the Grid Control

ALV Special Features


Display non-hierarchical lists consistently with a modern design
Use typical list functions such as sorting and filtering without extra
programming effort
Adapt a predefined list functions and their enhancements
Program response to user actions ( such as double-clicking a line ) individually
Connect to the report / report interface

ALV Constraints
The ALV grid control does not allow you to display block or hierarchical
lists. Currently, simple lists can be displayed in single line format only.
However, users can define multiple-line format in the print preview and
print the list as such.

Working with the ALV Grid Control


As a minimum, you must provide the following two types of information for displaying the
data:
An internal table with the data to be displayed, called the output table
A description of the structure of this data that is declared to the ALV grid control through
the field catalog or through the corresponding structure of the ABAP dictionary
Generally, the output table contains data that you previously selected from database
tables. The reference to the output table that you pass to the ALV grid control should be
valid as the ALV grid control operates on it. Besides defining this reference as a global
table, you can also hold the reference in the ABAP objects instance using a public
attribute.
The Field Catalog is a table that contains information on the fields to be displayed. For
example, the ALV uses this table to identify the type of field. You can also use special
fields of this catalog to determine the number format and column properties of the list to be
output.

Working with the ALV Grid Control


Data Description

A
B
C

Type1
Type2
Type3
Data
Dictionary

Field
Catalog

<name>
A B C

DECLARATION OF
REFERENCE VARIABLES
DATA grid TYPE REF TO
cl_gui_alv_grid
DATA container TYPE REF TO
cl_gui_custom_container

Screen

INSTANTIATION AND SCREEN


INTEGRATION

a1 b1 c1
a2 b2 c2
a3 b3 c3

CREATE OBJECT container


container_name = MYCONT
Output Table

Data

Internal Table

CREATE OBJECT grid


parent = container

a1 b1 c1
a2 b2 c2
a3 b3 c3

Data Display on the Control


CALL Method
Grid->set-table-for_first_display

Select * from <name>

List Display

GRID
( Linked to Screen
through container

A B C

Container with
Integrated ALV
Control

Flush

ALV Application Specific Programming


The following features of the ALV grid control make it a multi-purpose tool
suitable for many applications:
Display Variants allow users to adapt list output to their requirements. Application
developers determine which saving options users have available for a list.
User-defined Functions created by application developers can be added to the
toolbar. In addition, developers can adapt the standard functions to their individual
application or even hide them if they are not needed.
Drag and Drop Functions are programmable. The ALV grid control allows developers
to use the drag and drop control for implementing application specific functions
between the ALV grid control and other custom controls.
Formatting, Output and Control Options are provided through three different
structures:

1. The Field Catalog

2. The Layout Structure

3. The Print Structure

Function Module REUSE_ALV_GRID_DISPLAY

Call Function REUSE_ALV_GRID_DISPLAY


Exporting
I_CALLBACK_PROGRAM
= V_REPID
IS_LAYOUT
= V_LAYOUT
IT_FIELDCAT
= V_FIELDCAT
I_SAVE
= V_SAVE
Tables
T_OUTTAB
= V_ITAB
Exceptions
Program_Error
=1
Others
= 2.

ALV Data Declaration


TYPE-POOLS: SLIS.
Types: Begin of T_Mara.
Include Structure MARA.
Types: End of T_Mara.
Data: I_Mara Type Table of T_Mara,
W_Mara Type T_Mara.
ALV Declaration
Data : V_FIELDCAT type SLIS_T_FIELDCAT_ALV
with Header Line,
V_LAYOUT type SLIS_LAYOUT_ALV,
V_REPID like SY-REPID.

Field Catalog Structure

Routine Build_Field_Catalog (To Populate the Field Catalog)


Form Build_Field_Catalog.
Perform BUILD_TABLE Using:
SOITEM VBAP POSNR
Sales Order Item,
SODATE VBAK AUDAT
Sales Order Date,
MAT
VBAP MATNR Material,
SOQTY VBAP KWMENG Sales Order Qty.
Endform.

The subroutine BUILD_TABLE contains 4 parameters needed to populate the


Field Catalog internal table.
1. FIELD NAME relevant to the internal table to be displayed
2. Name of the Table
3. Name of the Field
4. Field Description

Subroutine Build_Table
Form Build_Table Using

P_FIELDNAME,
P_TABNAME,
P_REFFIELD,
P_FIELDTEXT.

Clear <FieldCat_Itable>.
<FieldCat_Itable>-row_pos
= 1.
<FieldCat_Itable>-col_pos
= l_column.
<FieldCat_Itable>-fieldname
= P_FIELDNAME.
<FieldCat_Itable>-seltext_l = P_FIELDTEXT.
<FieldCat_Itable>-ref_tabname
= P_TABNAME.
<FieldCat_Itable>-ref_fieldname
= P_REFFIELD.
Append <FieldCat_Itable>.
Endform.

The Layout Structure

Subroutine Build_Layout (to populate the Layout Structure)

Form Build_Layout.
Clear <Layout>.
<Layout>-no_input
= X.
<Layout>-colwidth_optimize
= X.
<Layout>-window_titlebar = SY-TITLE.
Endform.

ALV Reporting

Exercise 24 Create a Report using ALV, 60 minutes

Sorting the Report (Ascending or Descending)


Sort the report
using this button

Find Selected Records in the ALV Report


Click this button to Find
Selected Records in ALV
Report

Display Selected Records in the ALV Report


Click this button to Filter
the ALV Report

ALV Aggregation Operation


Click this button for
Aggregation

Subtotals in ALV Report


Click this button for
the subtotals

Dynamic Report Layout Modification


Click this button to
change the report layout

ALV List Viewer Navigation

Exercise 25 ALV List Viewer Navigation, 30 minutes

ALV Event Declaration

TYPE-POOLS: SLIS.
Types: Begin of T_Mara.
Include Structure MARA.
Types: End of T_Mara.
Data: I_Mara Type Table of T_Mara,
W_Mara Type T_Mara.
ALV Declaration
Data : V_FIELDCAT type SLIS_T_FIELDCAT_ALV
with Header Line,
V_LAYOUT type SLIS_LAYOUT_ALV,
V_REPID like SY-REPID.
Data : V_EVENTS type SLIS_T_EVENT.

ALV Event Introduction

Call Function REUSE_ALV_GRID_DISPLAY


Exporting
I_CALLBACK_PROGRAM
= V_REPID
IS_LAYOUT
= V_LAYOUT
IT_FIELDCAT
= V_FIELDCAT
I_SAVE
= V_SAVE
IT_EVENTS
= V_EVENTS
Tables
T_OUTTAB
= V_ITAB
Exceptions
Program_Error
=1
Others
= 2.

Function Module REUSE_ALV_EVENTS_GET


Form Build_Events.
Data: wa_event type SLIS_ALV_EVENT.
Call Function REUSE_ALV_EVENTS_GET
Exporting
I_LIST_TYPE
=0
Importing
ET_EVENTS
= V_EVENTS
Exceptions
LIST_TYPE_WRONG
= 1
OTHERS
= 2.
If sy-subrc eq 0.
Read Table V_EVENTS with KEY name = slis_ev_user_command into wa_event.
if sy-subrc is initial.
wa_event-form = USER_COMMAND.
modify V_EVENTS from wa_event index sy-tabix.
endif.
Endif.
Endform.

Subroutine USER_COMMAND
Form USER_COMMAND
Using R_UCOMM like sy-ucomm
RS_SELFIELD type SLIS_SELFIELD
Perform the Necessary Command Here
Endform.

RS_SELFIELD-TABINDEX holds the line selected by the user.

ALV List Viewer Navigation

Exercise 26 ALV List Viewer Interactive Reporting, 60 minutes

Conversions and Interface Development

Chapter

Data Imports and Exports


External data can be read from a file or internal data can be stored to a file, instead of
reading and writing data to and from tables.
Sequential files can be used for importing data from a customer system to the SAP System
and for exporting data from the SAP System to a customer system.

Customer
Customer system
system
Customer
Customer
program
program

Sequential
Sequential
file
file

SAP
SAP System
System

SAP
SAP
program
program

Processing Files
Before data records can be read from a file or written
to a file, the file must be opened.
The file is closed again after processing (i.e. after the
read/write operations have been completed).
Within an ABAP program, a file is referenced to by its
absolute file name. The absolute file name is made
up of the precise path and the actual file name, for
example, '/tmp/bc180/d01' or c:\myfile. Note, file
names may or may not be case sensitive depending
on the underlying operating system
Depending on the particular operating system in use,
files may be stored in different directories. Also, file
and path names must conform with different syntax
requirements. This is why platform independent
filenames are often used. The physical name and
location of the file can then be changed through
configuration rather than through program or
parameter changes.

Open
Open file
file

Process
Process file
file

Close
Close file
file

Opening Files
The statement OPEN DATASET <file name> is used to open a file.
Depending on the success, SY-SUBRC is set to 0 or to 8.

When an addition is not provided, the file is opened for reading. Possible
additions:
FOR OUTPUT - opens the file for writing. (If the file already exists, its content is deleted.
If the file does not exist, it is created.)
FOR INPUT - opens an already existing file for reading. (If the file has already been
opened, it returns to the beginning of the file. FOR INPUT does not have to be entered
explicitly.)
FOR APPENDING - opens the file for writing at the end of the file. (If the file does not yet
exist, it is created. If the file has already been opened, only return to the end.)

OPEN
OPEN DATASET
DATASET <file
<file name>
name>
FOR
FOR

OUTPUT
OUTPUT
INPUT
INPUT
APPENDING
APPENDING

Opening Files
When opening a file, it is also possible to choose between binary mode and text mode.
IN BINARY MODE (default)
The content of the file is not structured in lines. The data areas entered for these
language elements are entered or displayed directly. IN BINARY MODE does not have to
be entered explicitly.
IN TEXT MODE
If a file is opened with this addition, it is assumed that the file is structured in lines. Every
time READ DATASET or TRANSFER is called, exactly one line is always entered or
displayed. If the data area is too large when reading for the line read, the rest is filled
with blanks. If it is too small, the rest of the line is lost. (READ DATASET and
TRANSFER will be detailed in the following sections).

OPEN
OPEN DATASET
DATASET <file
<file name>
name>
FOR
FOR
IN
IN

OUTPUT
OUTPUT
INPUT
INPUT
APPENDING
APPENDING
BINARY
BINARY MODE
MODE (default)
(default)
TEXT
TEXT MODE
MODE

Binary Mode and Text Mode


Binary mode
ABAP
ABAP
program
program

Text mode
ABC
AB
ABCD

ABAP
ABAP
program
program

TRANSFER

ABC
AB
ABCD
TRANSFER

ABCABABCD
READ DATASET
ABAP
ABAP
program
program

A B C
A B A
B C D

A B C

A B

READ DATASET
ABAP
ABAP
program
program A B C
A B
A B C

A B C D

Opening Files
Additions available for the OPEN statement:
AT POSITION <position> - With this addition, an explicit file item
can be entered in bytes from the beginning of the file. The next
reading or write operation occurs then at this point. It is not
possible to position the cursor in front of the beginning of the
file.This addition can be used together with the addition IN TEXT
MODE.
MESSAGE <field> - The field <field> is filled with the relevant
operating system message when an error occurs during file open.
TYPE <attr> - The TYPE parameter allows the specification of
further file attributes. The system passes the contents of the field
<attr> to the operating system without performing any checks.
FILTER <filter> - Under Unix and Windows NT, the field <filter>
can contain an operating system command. Under Unix, the
statement OPEN DATASET DSN FOR OUTPUT FILTER
compress will open the file DSN and then write the output data to
the file in compressed format using the Unix command
compress.

OPEN
OPEN DATASET
DATASET <file
<file name>
name>
AT
ATPOSITION
POSITION <position>
<position>
MESSAGE
MESSAGE

<field>
<field>

TYPE
TYPE

<attr>
<attr>

FILTER
FILTER

<filter>
<filter>

Automated Data Transfer into the SAP System


Automated data transfer, i.e.
data transfer without
interactive dialog from the
user, is very desirable in
certain circumstances, such
as:
Very large amounts of data are
involved.
Data is entered into another
system first and then interfaced
to the SAP afterwards.

Non-SAP
Non-SAP System
System
SAP
SAP R/2
R/2
SAP
SAP R/3
R/3

Batch Input
Historically, batch input (commonly referred to as BDC - Batch Data
Communications) has been the most popular and widely used method for the
data interchange between SAP and the other information systems.
Use of batch input provides the following features:
Large data volumes can be processed in batch.
Can be scheduled and submitted in the background.
Can be processed automatically without human intervention.
Uses standard SAP transactions, just as if the data were entered manually. This
simulation of a user dialog ensures that data entered via BDC is subject to the same
checks and updates as data entered on line by the user.
Data is entered into another system first and then interfaced to the SAP afterwards.

Batch Input
Non-SAP
Non-SAP System
System
SAP
SAP R/2
R/2
SAP
SAP R/3
R/3
Queue
Batch
Input
Sessions
Application
program

Format checks
Automatic value range check
(against check table or value range)
Conversion of input data into program
data (and vice versa)
Field default values

Automatic
Checks

SAP

Batch Input Processing


Batch input (or BDC for Batch
Data Communication) is an
automatic procedure for the nononline transfer of data into the SAP
System. To allow the same checks
and updates to be carried out as if
online, a user dialog is simulated
with this procedure.
Batch input sessions can be
viewed and processed via the
Batch Input function, which can be
accessed via System->Services->
Batch Input of directory via SM35.

Customer
Master Data

Sequential
File
Batch
Batch input
input program
program

Queue
File

takes data belonging


together in batch input
sessions

Function
Function "Batch
"Batch input"
input"

Vendor
Master Data

Document
Data

Batch Input Program


Sequential
File

ABAP
Dictionary
Structure
Structure
BDCDATA
BDCDATA

READ DATASET
Batch
Batch input
input program
program
BDC
table

DATA ... LIKE BDCDATA OCCURS <n>.

CALL FUNCTION

Queue
File

Batch Input Queue File

Sequential
File

Screens

SAP
Database

Batch
Batch input
input

Transaction 1
Screen 1

Transaction 2

Screen 2

Screen 1

Screen 2

Log
File

Customer
Master
Data

Vendor
Master Data

Document
Data

Format of a Batch Input Session


Session
Session Header
Header (APQI)
(APQI)
Creator
Creator
Client
Clientin
in which
which session
session should
should run
run
Session
name
Session name
Batch
Batchinput
inputauthorization
authorization user
user
Date
from
which
Date from which session
sessioncan
canrun
run(Lock
(Lock date)?
date)?
Delete
session
after
running
(Keep
function)?
Delete session after running (Keep function)?

Transaction
Transaction (APQD)
(APQD)

...

Session
Session End
End

Creating Batch Input Sessions


Creating a batch input session is a
three step process:
Opening the batch input session

Open
Open
batch
batch input
input session
session

Inserting the transaction data into the


session
Closing the batch input session

A batch input program can create


multiple batch input sessions in
succession.

Enter
Enter
transaction
transaction data
data

Close
Close
batch
batch input
input session
session

Function Modules for Batch Input Sessions


BDC_OPEN_GROUP
BDC_OPEN_GROUP
Client
Client
Session
Session name
name
Block
Block date
date
Delete
Delete session
session after
after
processing
processing
BDC
BDC user
user name
name

BDC_INSERT
BDC_INSERT
Transaction
Transaction code
code
BDC
BDC table
table

BDC_CLOSE_GROUP
BDC_CLOSE_GROUP

CLIENT
CLIENT
GROUP
GROUP
HOLD
HOLD
KEEP
KEEP
USER
USER

TCODE
TCODE
DYNPROTAB
DYNPROTAB

Function Module BDC_OPEN_GROUP


A batch input session is started with the
function module BDC_OPEN_GROUP.
The following parameters are required:
CLIENT (client),
GROUP (session name),
USER (user ID). This is the user id that will
be used to process the transactions specified in
the BDC session.

The following parameters are optional:


HOLDDATE (day on which the session can be
started at the earliest)
KEEP (indicator whether the session is deleted
or not after successful processing of the
session; KEEP = ' ' means: Delete session,
KEEP = 'X' means: Do not delete session).

EXCEPTIONS returns values that can be


checked via SY-SUBRC.

CALL
CALL FUNCTION
FUNCTION BDC_OPEN_GROUP
BDC_OPEN_GROUP
EXPORTING
EXPORTING
CLIENT
CLIENT
GROUP
GROUP
HOLDDATE
HOLDDATE
KEEP
KEEP
USER
USER

==
==
==
==
==

<client>
<client>
<session
<session name>
name>
<lock
<lock date>
date>
<deletion
<deletion indicator>
indicator>
<batch
user
<batch user name>
name>

EXCEPTIONS
EXCEPTIONS RUNNING
RUNNING
QUEUE_ERROR
QUEUE_ERROR
CLIENT_INVALID
CLIENT_INVALID
GROUP_INVALID
GROUP_INVALID

==
==
==

11
22
33

Function Module BDC_INSERT


Transaction data is
inserted into the session
with the function module
BDC_INSERT.
A special internal table
(BDC table) is required
to transfer the data.
The following
parameters are required:
TCODE (transaction
code). This is the SAP
transaction to be
executed using the data
in the internal BDC table.
DYNPROTAB (BDC
table). This is the name
of the internal table.

CALL
CALL FUNCTION
FUNCTION BDC_INSERT
BDC_INSERT
EXPORTING
EXPORTING
TABLES
TABLES

TCODE
TCODE

DYNPROTAB
DYNPROTAB

== <transaction
<transaction code>
code>
== <bdc_table>
<bdc_table>

EXCEPTIONS
EXCEPTIONS
INTERNAL_ERROR
INTERNAL_ERROR

== 11

NOT_OPEN
NOT_OPEN

== 22

QUEUE_ERROR
QUEUE_ERROR

== 33

TCODE_INVALID
TCODE_INVALID

== 44

Defining the BDC Table

DATA:
DATA: <bdc
<bdc table>
table> LIKE
LIKE BDCDATA
BDCDATA
OCCURS
OCCURS <occurs
<occurs parameter>.
parameter>.

BDCDATA
BDCDATA
Field
Field name
name

Type
Type

Length
Length

Description
Description

PROGRAM
PROGRAM
DYNPRO
DYNPRO
DYNBEGIN
DYNBEGIN
FNAM
FNAM
FVAL
FVAL

CHAR
CHAR
NUMC
NUMC
CHAR
CHAR
CHAR
CHAR
CHAR
CHAR

88
44
11
35
35
80
80

BDC
BDC Module
Module pool
pool
BDC
BDC Screen
Screen number
number
BDC
BDC Starting
Starting aa screen
screen
BDC
BDC Field
Field name
name
BDC
BDC Field
Field value
value

Filling the BDC Table


The BDC table is filled line
by line. As for every internal
table, this action is
performed with MOVE and
APPEND statements.
If the internal table has been
declared with a header line,
the fields of the header line
should be reset to their
initial value by CLEAR. The
REFRESH command will
delete all the contents of the
internal table.

FORM <fill bdc table>.


REFRESH <bdc table>.
CLEAR <bdc table>.
MOVE: <program name> TO <bdc table>-PROGRAM,
<number1>
TO <bdc table>-DYNPRO,
'X'
TO <bdc table>-DYNBEGIN.
APPEND <bdc table>.
CLEAR <bdc table>.
MOVE: <field11> TO <bdc table>-FNAM,
<value11>
TO <bdc table>-FVAL.
APPEND <bdc table>.
CLEAR <bdc table>.
MOVE: <field12> TO <bdc table>-FNAM,
<value12>
TO <bdc table>-FVAL.
APPEND <bdc table>.
...
CLEAR <bdc table>.
MOVE: <program name> TO <bdc table>-PROGRAM,
<number2>
TO <bdc table>-DYNPRO,
'X'
TO <bdc table>-DYNBEGIN.
APPEND <bdc table>.
...
ENDFORM.

Function Module BDC_CLOSE_GROUP


A batch input session is closed with the function module BDC_CLOSE_GROUP.
EXCEPTIONS returns values that can be checked with SY-SUBRC.

CALL
CALL FUNCTION
FUNCTION BDC_CLOSE_GROUP
BDC_CLOSE_GROUP
EXCEPTIONS
EXCEPTIONS

NOT_OPEN
NOT_OPEN
QUEUE_ERROR
QUEUE_ERROR

==
==

11
22

Example: Changing Customer Data


Accounting/Financial
Accounting/Financial accounting/Accounts
accounting/Accounts payable
payable
Master
Master data/Change
data/Change
(Transaction
(Transaction FD02)
FD02)

Customer

4711

Address

Name
Region

Save
Save

Miller
03

BDC Programming

Exercise 30 Creating a customer using FD01, 20 minutes

Questions?
SAP ABAP/4 Training

Thank you
SAP ABAP/4 Training

7 January 2017

Guidelines & Samples

No. 287

You might also like