You are on page 1of 488

BC411 Advanced ABAP Programming

BC411

R/3 System Release 46B 24.06.2002

0
BC411 Advanced ABAP Programming ................................................................................................ 0-1
Copyright.......................................................................................................................................... 0-2
R/3 Integration Model ................................................................................................................... 0-3
ABAP Workbench......................................................................................................................... 0-4
Prerequisites ................................................................................................................................ 0-5
Target Group ................................................................................................................................ 0-6
Introduction: Contents ...................................................................................................................... 1-1
Course Goal ................................................................................................................................. 1-2
Course Objectives ........................................................................................................................ 1-3
Contents I ..................................................................................................................................... 1-4
Contents II .................................................................................................................................... 1-5
Overview Diagram ........................................................................................................................ 1-6
Overall Business Scenario............................................................................................................ 1-7
Development Process and Tools: Contents ..................................................................................... 2-1
Unit Objectives ............................................................................................................................. 2-2
Development Process for an ABAP Program ............................................................................... 2-3
Types of Program Analysis........................................................................................................... 2-4
Syntax Check ............................................................................................................................... 2-5
Syntax Check ............................................................................................................................... 2-6
Syntax Errors................................................................................................................................ 2-7
Runtime Errors ............................................................................................................................. 2-8
Short Dump Administration........................................................................................................... 2-9
Dynamic Analysis ....................................................................................................................... 2-10
Debugging Mode ........................................................................................................................ 2-11
The Most Important Debugging Functions .................................................................................. 2-12
The Most Important Debugging Functions II ............................................................................... 2-13
Debugger: Overview................................................................................................................... 2-14
Expanding Substructures............................................................................................................ 2-15
Breakpoints in Programs ............................................................................................................ 2-16
Breakpoints in the Debugger ...................................................................................................... 2-17
Watchpoints................................................................................................................................ 2-18
Runtime Measurement ............................................................................................................... 2-19
Runtime Analysis I...................................................................................................................... 2-20
Runtime Analysis II..................................................................................................................... 2-21
Measurable Functions I .............................................................................................................. 2-22
Measurable Functions II ............................................................................................................. 2-23
Gross and Net Times.................................................................................................................. 2-24
The GET RUN TIME Statement.................................................................................................. 2-25
Test Frame I ............................................................................................................................... 2-26
Test Frame II .............................................................................................................................. 2-27
Test Frame III ............................................................................................................................. 2-28
Test Frame IV............................................................................................................................. 2-29
Database Access........................................................................................................................ 2-30
SQL Trace .................................................................................................................................. 2-31
SQL Trace - Basic List................................................................................................................ 2-32
SQL Trace Function: Explain SQL.............................................................................................. 2-33
Index Range Scan/Access by Rowid .......................................................................................... 2-34
Summary .................................................................................................................................... 2-35
Types: Contents ............................................................................................................................... 3-1
Unit Objectives ............................................................................................................................. 3-2
Data Types ................................................................................................................................... 3-3
Predefined ABAP Types ............................................................................................................... 3-4
Predefined Dictionary Types I....................................................................................................... 3-5
Predefined Dictionary Types (2) ................................................................................................... 3-6
Calculations Using Numeric Types ............................................................................................... 3-7
Summary of Declarative Statements ............................................................................................ 3-8
Type Conversion .......................................................................................................................... 3-9
Conversion Rules for Elementary Types .................................................................................... 3-10
Conversion Rule for Structure types ........................................................................................... 3-11
Information About an Object at Runtime ..................................................................................... 3-12
Summary .................................................................................................................................... 3-13
Field Symbols: Contents .................................................................................................................. 4-1
Unit Objectives ............................................................................................................................. 4-2
Pointers and Field Symbols .......................................................................................................... 4-3
Reference and Value Semantics .................................................................................................. 4-4
Using Field Symbols - Overview ................................................................................................... 4-5
Using Field Symbols (1)................................................................................................................ 4-6
Using Field Symbols (2)................................................................................................................ 4-7
Assigning Parts of Strings Dynamically ........................................................................................ 4-8
Processing Individual Characters in a String ................................................................................ 4-9
Dynamic Field Assignment ......................................................................................................... 4-10
Referring to Components of a Structure ..................................................................................... 4-11
Changing the Field Type............................................................................................................. 4-12
Memory Protection ..................................................................................................................... 4-13
Summary .................................................................................................................................... 4-14
Internal Tables: Contents ................................................................................................................. 5-1
Unit Objectives ............................................................................................................................. 5-2
Internal Tables.............................................................................................................................. 5-3
Internal Table Attributes................................................................................................................ 5-4
Table Types.................................................................................................................................. 5-5
Response Times .......................................................................................................................... 5-6
Access Times ............................................................................................................................... 5-7
Defining Internal Tables................................................................................................................ 5-8
Internal Tables in Memory (1) ....................................................................................................... 5-9
Internal Tables in Memory (2) ..................................................................................................... 5-10
Internal Tables in Memory (3) ..................................................................................................... 5-11
Internal Tables in Memory (4) ..................................................................................................... 5-12
Internal Tables in Memory (5) ..................................................................................................... 5-13
Internal Tables in Memory (6) ..................................................................................................... 5-14
Special Internal Table Operations............................................................................................... 5-15
Operations on all Data Objects ................................................................................................... 5-16
Index Access Using Read........................................................................................................... 5-17
Index Operations on Internal Tables........................................................................................... 5-18
Linear Index (1) .......................................................................................................................... 5-19
Linear Index (2) .......................................................................................................................... 5-20
Linear Index (3) .......................................................................................................................... 5-21
Accessing a Single Generic Entry with READ ............................................................................ 5-22
Generic Key Operations ............................................................................................................. 5-23
Operations on Standard Tables (Example)................................................................................. 5-24
Internal Tables With and Without Header Line ........................................................................... 5-25
Declaring an Internal Table With Header Line ............................................................................ 5-26
Sorted Table (Example).............................................................................................................. 5-27
Partial Sequential Processing: Sorted Tables............................................................................. 5-28
Hashed Tables (Example) .......................................................................................................... 5-29
Filling an Internal Table with Cumulative Values ........................................................................ 5-30
Summary of Internal Table Operations ....................................................................................... 5-31
Standard Table Definitions (History) ........................................................................................... 5-32
Summary .................................................................................................................................... 5-33
Object-Oriented Programming with ABAP Objects: Contents .......................................................... 6-1
Objectives..................................................................................................................................... 6-2
What are Objects?........................................................................................................................ 6-3
Objects ......................................................................................................................................... 6-4
Encapsulation ............................................................................................................................... 6-5
Advantages of Object-Oriented Programming .............................................................................. 6-6
From Function Groups to Objects I............................................................................................... 6-7
From Function Groups to Objects II.............................................................................................. 6-8
Classes and Objects..................................................................................................................... 6-9
What is ABAP Objects? .............................................................................................................. 6-10
Classes I..................................................................................................................................... 6-11
Classes II.................................................................................................................................... 6-12
Declaring Attributes .................................................................................................................... 6-13
Static Attributes .......................................................................................................................... 6-14
References: Reference Variables ............................................................................................... 6-15
References: Creating Objects..................................................................................................... 6-16
References: Assigning References............................................................................................. 6-17
References: Garbage Collection................................................................................................. 6-18
Classes and Instances: Example................................................................................................ 6-19
Declaring Methods...................................................................................................................... 6-20
Implementing Methods ............................................................................................................... 6-21
Calling Methods.......................................................................................................................... 6-22
Constructor................................................................................................................................. 6-23
Interfaces.................................................................................................................................... 6-24
Interfaces: Model ........................................................................................................................ 6-25
Defining Interfaces...................................................................................................................... 6-26
Implementing Interfaces ............................................................................................................. 6-27
Generic Programming Using Interface References..................................................................... 6-28
Interfaces - Example................................................................................................................... 6-29
Events ........................................................................................................................................ 6-30
Events ........................................................................................................................................ 6-31
Defining Events .......................................................................................................................... 6-32
Defining an Event Handler.......................................................................................................... 6-33
Registering and Triggering Events.............................................................................................. 6-34
Events: Handler Table ................................................................................................................ 6-35
Summary .................................................................................................................................... 6-36
Preview: Inheritance ................................................................................................................... 6-37
Contexts: Contents........................................................................................................................... 7-1
Unit Objectives ............................................................................................................................. 7-2
What is a Context? ....................................................................................................................... 7-3
Using Contexts ............................................................................................................................. 7-4
Structure of a Context................................................................................................................... 7-5
Testing Contexts........................................................................................................................... 7-6
Derivation Schema of a Context ................................................................................................... 7-7
Buffering Contexts ........................................................................................................................ 7-8
Context Buffer and Context Instances .......................................................................................... 7-9
Creating a Context Instance ....................................................................................................... 7-10
Supplying a Context Instance with Key Values I......................................................................... 7-11
Supplying a Context Instance with Key Values II ........................................................................ 7-12
Retrieving Data from a Context Instance I .................................................................................. 7-13
Retrieving Data from a Context Instance II ................................................................................. 7-14
Message Handling in Contexts: System ..................................................................................... 7-15
Message Handling in Contexts: Program.................................................................................... 7-16
Clearing the Context Buffer ........................................................................................................ 7-17
Creating and Maintaining Contexts............................................................................................. 7-18
Summary I .................................................................................................................................. 7-19
Summary II ................................................................................................................................. 7-20
ABAP Open SQL: Inhalt ................................................................................................................... 8-1
Unit Objectives ............................................................................................................................. 8-2
ABAP Open SQL: Overview ......................................................................................................... 8-3
Business Transaction Performance .............................................................................................. 8-4
ABAP Open SQL: Overview ......................................................................................................... 8-5
R/3 Architecture............................................................................................................................ 8-6
General DBMS Architecture ......................................................................................................... 8-7
The Optimizer ............................................................................................................................... 8-8
ABAP Open SQL: Overview ......................................................................................................... 8-9
ABAP SQL.................................................................................................................................. 8-10
From SQL Statement to Result Set ............................................................................................ 8-11
Efficient ABAP Database Programming...................................................................................... 8-12
Five Rules of Open SQL Programming ...................................................................................... 8-13
Basis for the Five Rules.............................................................................................................. 8-14
Rule 1 ......................................................................................................................................... 8-15
Exercise: Read all Flights for a Year........................................................................................... 8-16
1. Keep the Result Set Small...................................................................................................... 8-17
Benefits of Rule 1 ....................................................................................................................... 8-18
Rule 2 ......................................................................................................................................... 8-19
Exercise: Reading the First 10 Flights ........................................................................................ 8-20
2. Minimize Data Transfer I......................................................................................................... 8-21
2. Minimize Data Transfer........................................................................................................... 8-22
Client/Server Architecture and ABAP Runtime I ......................................................................... 8-23
Client/Server Architecture and ABAP Runtime II ........................................................................ 8-24
2. Minimize Data Transfer II........................................................................................................ 8-25
Exercise: Summation.................................................................................................................. 8-26
2. Minimize Data Transfer 4........................................................................................................ 8-27
2. Minimize Data Transfer 5........................................................................................................ 8-28
Benefits of Rule 2 ....................................................................................................................... 8-29
Rule 3 ......................................................................................................................................... 8-30
3. Minimize the Number of Transfers 1....................................................................................... 8-31
Exercise: Reading from More than One Table............................................................................ 8-32
3. Minimize the Number of Transfers 2....................................................................................... 8-33
3. Minimize the Number of Transfers 3....................................................................................... 8-34
3. Minimize the Number of Transfers 4....................................................................................... 8-35
3. Minimize the Number of Transfers 5....................................................................................... 8-36
3. Minimize the Number of Transfers 6....................................................................................... 8-37
3. Minimize the Number of Transfers 7....................................................................................... 8-38
Exercise: Reading Maximum and Minimum Values .................................................................... 8-39
3. Minimize the Number of Transfers 8....................................................................................... 8-40
Exercise: Reading Grouped Data with Conditions ...................................................................... 8-41
3. Minimize the Number of Transfers 9....................................................................................... 8-42
Benefits of Rule 3 ....................................................................................................................... 8-43
Rule 4 ......................................................................................................................................... 8-44
4. Minimize the Search Overhead 1............................................................................................ 8-45
4. Minimize the Search Overhead 2............................................................................................ 8-46
4. Minimize the Search Overhead 3............................................................................................ 8-47
4. Minimize the Search Overhead 4............................................................................................ 8-48
4. Minimize the Search Overhead 5............................................................................................ 8-49
4. Minimize the Search Overhead 6............................................................................................ 8-50
4. Minimize the Search Overhead 7............................................................................................ 8-51
4. Minimize the Search Overhead 8............................................................................................ 8-52
Rule 5 ......................................................................................................................................... 8-53
5. Reduce the Database Load 1 ................................................................................................. 8-54
5. Reduce the Database Load 2 ................................................................................................. 8-55
5. Reduce the Database Load 3 ................................................................................................. 8-56
5. Reduce the Database Load 4 ................................................................................................. 8-57
5. Reduce the Database Load 5 ................................................................................................. 8-58
5. Reduce the Database Load 6 ................................................................................................. 8-59
Synchronizing the buffer II .......................................................................................................... 8-60
Synchronizing the buffer III ......................................................................................................... 8-61
5. Reduce the Database Load 9 ................................................................................................. 8-62
When should you buffer tables? ................................................................................................. 8-63
Buffering tables........................................................................................................................... 8-64
SQL statements that bypass the buffer....................................................................................... 8-65
5. Reduce the Database Load 13 ............................................................................................... 8-66
5. Reduce the Database Load 14 ............................................................................................... 8-67
5. Reduce the Database Load 15 ............................................................................................... 8-68
5. Reduce the Database Load 16 ............................................................................................... 8-69
ABAP Tuning Checklist - I .......................................................................................................... 8-70
ABAP Tuning Checklist - II ......................................................................................................... 8-71
ABAP Tuning Checklist - III ........................................................................................................ 8-72
Summary I .................................................................................................................................. 8-73
Summary II ................................................................................................................................. 8-74
Summary III ................................................................................................................................ 8-75
Exceptions and Message Handling: Contents .................................................................................. 9-1
Unit Objectives ............................................................................................................................. 9-2
Exceptions.................................................................................................................................... 9-3
Catching Runtime Errors .............................................................................................................. 9-4
System Exceptions ....................................................................................................................... 9-5
Nested CATCH… ENDCATCH Structures ................................................................................... 9-6
Summary ...................................................................................................................................... 9-7
ABAP Modularization Units ............................................................................................................ 10-1
Unit Objectives ........................................................................................................................... 10-2
Modularization Units ................................................................................................................... 10-3
Memory Areas: Logical Model I .................................................................................................. 10-4
Memory Areas: Logical Model II ................................................................................................. 10-5
Visibility Area of a Program ........................................................................................................ 10-6
Internal Session.......................................................................................................................... 10-7
Table Work Areas / Common Parts ............................................................................................ 10-8
The Dangers of Working with Common Data Areas, Call Hierarchies I ...................................... 10-9
The Dangers of Working with Common Data Areas, Call Hierarchies II ................................... 10-10
Subroutines, Function Modules, and Methods.......................................................................... 10-11
Calling a Function Module, Method, or External Subroutine ..................................................... 10-12
Interfaces in Subroutines .......................................................................................................... 10-13
Methods for Passing Parameters.............................................................................................. 10-14
Interfaces in Function Modules / Methods ............................................................................... 10-15
Screens, Modules, and Events ................................................................................................. 10-16
Interfaces of Screens, Modules, and Events............................................................................. 10-17
Screen/List/Selection Screen.................................................................................................... 10-18
CALL SCREEN......................................................................................................................... 10-19
Implicit Exit / LEAVE SCREEN ................................................................................................. 10-20
List System............................................................................................................................... 10-21
Several List Systems ................................................................................................................ 10-22
Several List Systems - Example I ............................................................................................. 10-23
Several List Systems - Example II ............................................................................................ 10-24
LEAVE TO SCREEN ................................................................................................................ 10-25
CALL SELECTION-SCREEN ................................................................................................... 10-26
Transaction / Program .............................................................................................................. 10-27
CALL TRANSACTION ‘TA01’ /SUBMIT PROG01 AND RETURN ........................................... 10-28
Implicit Exit / LEAVE PROGRAM.............................................................................................. 10-29
LEAVE TO TRANSACTION ‘TA01’ .......................................................................................... 10-30
SUBMIT PROG01 .................................................................................................................... 10-31
Context ..................................................................................................................................... 10-32
Structuring Source Code .......................................................................................................... 10-33
Include Programs ..................................................................................................................... 10-34
Macros...................................................................................................................................... 10-35
Summary .................................................................................................................................. 10-36
Dynamic Program Generation: Contents........................................................................................ 11-1
Unit Objectives ........................................................................................................................... 11-2
Dynamic ABAP Programming..................................................................................................... 11-3
Dynamic Programming - Examples ............................................................................................ 11-4
Specifying Names at Runtime .................................................................................................... 11-5
Generating Programs from Within Progams ............................................................................... 11-6
Generating Temporary Programs ............................................................................................... 11-7
Generating Persistent Programs................................................................................................. 11-8
Summary .................................................................................................................................... 11-9
Appendix ........................................................................................................................................ 12-1
Further Information about Internal Tables and Extracts .............................................................. 12-2
Internal Tables and Extracts (1).................................................................................................. 12-3
Internal Tables and Extracts (2).................................................................................................. 12-4
Internal Tables and Extracts (3).................................................................................................. 12-5
Accessing Table Entries Directly (Release 4.5) Contents .............................................................. 13-1
Structure of Deep Tables............................................................................................................ 13-2
Accessing Table Entries Directly (Release 4.5A)........................................................................ 13-3
Further Information About ABAP Open SQL: Contents .................................................................. 14-1
Rule 3: Minimize the Number of Transfers 1............................................................................... 14-2
Rule 3: Minimize the Number of Transfers 2............................................................................... 14-3
Rule 4: Minimize the Search Overhead ...................................................................................... 14-4
Rule 4: Minimize the Search Overhead ...................................................................................... 14-5
Rule 5: Reduce the Database Load 1......................................................................................... 14-6
Rule 5: Reduce the Database Load............................................................................................ 14-7
Further Information About Modularization Units: Contents ............................................................. 15-1
Comparison Criteria I.................................................................................................................. 15-2
Comparison Criteria II................................................................................................................. 15-3
Comparison Criteria III................................................................................................................ 15-4
Internal Subroutine I ................................................................................................................... 15-5
Internal Subroutine II .................................................................................................................. 15-6
Internal Subroutine III ................................................................................................................. 15-7
External Subroutine I .................................................................................................................. 15-8
External Subroutine II ................................................................................................................. 15-9
External Subroutine III .............................................................................................................. 15-10
Function Module I ..................................................................................................................... 15-11
Function Module II .................................................................................................................... 15-12
Function Module III ................................................................................................................... 15-13
Screen, CALL SCREEN, CALL SELECTION-SCREEN I ......................................................... 15-14
Screen, CALL SCREEN, CALL SELECTION-SCREEN II ........................................................ 15-15
Screen, CALL SCREEN, CALL SELECTION-SCREEN III ....................................................... 15-16
Module I.................................................................................................................................... 15-17
Module II................................................................................................................................... 15-18
Module III.................................................................................................................................. 15-19
Event I ...................................................................................................................................... 15-20
Event II ..................................................................................................................................... 15-21
Event III .................................................................................................................................... 15-22
Dialog Module I......................................................................................................................... 15-23
Dialog Module II........................................................................................................................ 15-24
Dialog Module III....................................................................................................................... 15-25
Transaction I............................................................................................................................. 15-26
Transaction II............................................................................................................................ 15-27
Transaction III........................................................................................................................... 15-28
Program, SUBMIT I .................................................................................................................. 15-29
Program, SUBMIT II ................................................................................................................. 15-30
Program, SUBMIT III ................................................................................................................ 15-31
LEAVE TO LIST PROCESSING I............................................................................................. 15-32
LEAVE TO LIST PROCESSING II............................................................................................ 15-33
LEAVE TO LIST PROCESSING III........................................................................................... 15-34
String Processing: Contents........................................................................................................... 16-1
Unit Objectives ........................................................................................................................... 16-2
String Processing ....................................................................................................................... 16-3
Searching in a String .................................................................................................................. 16-4
Manipulating Strings ................................................................................................................... 16-5
Joining and Splitting Strings ....................................................................................................... 16-6
String Comparisons .................................................................................................................... 16-7
Summary .................................................................................................................................... 16-8
Bit Processing: Contents................................................................................................................ 17-1
Unit Objectives ........................................................................................................................... 17-2
Sets as Bit Patterns .................................................................................................................... 17-3
SET BIT and GET BIT ................................................................................................................ 17-4
Assigning Values to X Fields ...................................................................................................... 17-5
Bit Calculations........................................................................................................................... 17-6
Bit Comparisons ......................................................................................................................... 17-7
Example: Representing Flights with an X Field........................................................................... 17-8
Summary .................................................................................................................................... 17-9
Data Clusters: Contents ................................................................................................................. 18-1
Unit Objectives ........................................................................................................................... 18-2
Data Clusters: Overview ............................................................................................................. 18-3
Syntax: EXPORT to a Cluster Database .................................................................................... 18-4
Syntax: IMPORT and DELETE ................................................................................................... 18-5
Key of the Database Table INDX................................................................................................ 18-6
ABAP Cluster Databases............................................................................................................ 18-7
Example: Catalog for INDX......................................................................................................... 18-8
ABAP Memory - Overview: Communication Between Internal Sessions .................................... 18-9
Transporting Data Between Programs (ABAP Memory) ........................................................... 18-10
Shared Buffer - Overview ......................................................................................................... 18-11
Cluster Tables and Transparent Tables.................................................................................... 18-12
Summary .................................................................................................................................. 18-13
Exercises ....................................................................................................................................... 19-1
Data used in the exercises: ........................................................................................................ 19-2
- .................................................................................................................................................. 19-6
- .................................................................................................................................................. 19-7
- .................................................................................................................................................. 19-9
- ................................................................................................................................................ 19-13
- ................................................................................................................................................ 19-24
- ................................................................................................................................................ 19-26
- ................................................................................................................................................ 19-33
- ................................................................................................................................................ 19-34
Solutions ........................................................................................................................................ 20-1
- .................................................................................................................................................. 20-2
- .................................................................................................................................................. 20-6
- .................................................................................................................................................. 20-8
- ................................................................................................................................................ 20-12
- ................................................................................................................................................ 20-17
- ................................................................................................................................................ 20-40
- ................................................................................................................................................ 20-45
- ................................................................................................................................................ 20-57
- ................................................................................................................................................ 20-59
Glossary......................................................................................................................................... 21-1
ABAP Glossary........................................................................................................................... 21-2
BC411 Advanced ABAP Programming

BC 411
Advanced ABAP
Programming

© SAP AG 1999
© SAP AG

BC 411 Advanced ABAP Programming


Release 4.0 B
Material number: 5002 0252
August 1998
Copyright

Copyright 1998 SAP AG. All rights reserved.

Neither this training manual nor any part thereof may


be copied or reproduced in any form or by any means,
or translated into another language, without the prior
consent of SAP AG. The information contained in this
document is subject to change and supplement
without prior notice.

All rights reserved.

© SAP AG

• Trademarks
SAP and the SAP logo are registered trademarks of SAP AG.
MS-DOS and EXCEL are registered trademarks of Microsoft.
OS/2, CICS, MVS, ACF/VTAM, VSE, AIX, OS/400 and AS/400 are registered trademarks of
IBM.
X Window System is a registered trademark of MIT University.
SINIX, UTM and BS2000 are registered trademarks of Siemens.
UNIX is a registered trademark of AT&T.
HP-UX is a registered trademark of Hewlett Packard.
DECnet, DECstation, DECsystem, VAXstation and VMS are registered trademarks of DEC.
Ethernet is a registered trademark of the Xerox Corporation.
ORACLE SQL*net, SQL*+ PRO*C are registered trademarks of the ORACLE Corporation.
INFORMIX-OnLine and INFORMIX-ESQL/C are registered trademarks of the INFORMIX
Corporation.
R/3 Integration Model

SD FI
Sales & Financial
Distribution Accounting
MM CO
Materials Controlling
Mgmt
PP AA
Production Asset
Planning
R/3 Accounting

QM
Quality
Client/Server PS
Project
Mgmt PM
Plant
ABAP WF
System

Maintenance Workflow
HR IS
Human Industry
Resources Solutions

© SAP AG

The SAP R/3 System continues to set new standards for universal standard software. Based on
progressive development techniques, the SAP R/3 System allows comprehensive integration of
business administration and data processing.
The SAP R/3 System components are characterized by comprehensive business functions with
the most modern technology. The integration of the applications ensures that all the functions are
directly available in the system and thus in the enterprise.
ABAP Workbench
Level 2 Level 3
BC405 5 days BC411 5 days
Techniques of Advanced ABAP
List Processing Programming
BC410 5 days BC425 2 days
Transaction Processing Enhancements and
Modifications
BC415 3 days BC440 5 days
Communication Developing Internet
Interface Programming Application Components
in ABAP (IAC)
BC400 5 days BC420 2 days
ABAP Workbench
Interface Programming
Basics
for Data Transfer
BC430 2 days
ABAP Dictionary

BC460 3 days
SAPscript: Forms
Design and Text
Management in R/3

© SAP AG
Prerequisites

Required:
BC400 Introduction to the ABAP Workbench
BC410 Transaction programming
ABAP programming experience
Recommended:
BC405 Techniques of List Processing
BC430 ABAP Dictionary

© SAP AG
Target Group

Project team
Technical developers and application programmers
This course is aimed at experienced ABAP
programmers writing complex programs, who want to
improve their knowledge of ABAP.
Participants will gain hands-on experience of ABAP
programming through the exercises.
Duration: 5 days

© SAP AG

Notes to the user


The training materials are not teach-yourself programs. They complement the course
instructor's explanations. On the sheets, there is space for you to write down additional
information.
Introduction: Contents

Course goal
Course objectives
Contents
Overview diagram
Overall business scenario

© SAP AG
Course Goal

This course teaches you about :

Programming in ABAP in the R/3 System


ABAP language constructions, with
particular emphasis on using them
correctly and in appropriate situations

© SAP AG

(C) SAP AG BC411 1-2


Course Objectives

Description of the development process and


using the development tools
Using types and field symbols
Understanding and using the different kinds of
internal tables
Understanding and using the syntax of ABAP
Objects
Programming exception and message handling
Using ABAP and Open SQL
Using appropriate modularization units and
dynamic programs R

© SAP AG

(C) SAP AG BC411 1-3


Contents I

Introduction

Unit Introduction Unit Contexts

Unit Development process and Unit ABAP Open SQL


development tools

Unit Types Unit Exceptions and message handling

Unit Field symbols Unit Modularization units

Unit Internal tables Unit Generating dynamic programs

Unit Object-oriented programming


in ABAP

Unit ABAP Objects

© SAP AG

(C) SAP AG BC411 1-4


Contents II

Appendices

Appendix A Further information about internal tables and extracts


Appendix B Accessing table lines directly (from Release 4.5A)
Appendix C Further information about ABAP Open SQL
Appendix D Further information about modularization units
Appendix E String processing
Appendix F Bit processing
Appendix G Data clusters

Exercises
Solutions
Glossary R

© SAP AG

(C) SAP AG BC411 1-5


Overview Diagram

Complex problems:

What ABAP constructions


can I use to solve the
problem?

© SAP AG

(C) SAP AG BC411 1-6


Overall Business Scenario

This course contains no overall scenario


that is successively developed by the
participants

© SAP AG

(C) SAP AG BC411 1-7


Development Process and Tools: Contents

Development process for an ABAP program


Static checks
Syntax check
Extended program check

Runtime errors
Debugger
Performance tools
ABAP runtime analysis
GET RUN TIME
SQL TRACE
R

© SAP AG
Unit Objectives

At the end of this unit, you will be able to:


Explain the development process for an ABAP
program
Check the syntax of a program
Run an extended program check for a program
Analyze a short dump
Use the most important functions of the Debugger
Determine the flow and runtime of a program using
runtime analysis
Measure runtime using the GET RUN TIME statement
Analyze database access using the main functions of
the SQL Trace tool

© SAP AG

(C) SAP AG BC411 2-2


Development Process for an ABAP Program

ABAP
Development Program

TRDIR Source code


attributes

Syntax
Syntax check
check
Extended
Extended program
program check
check

Errors
Load
R
Generated form Warnings

© SAP AG

(C) SAP AG BC411 2-3


Types of Program Analysis
Syntax
Syntax check
check Error
Error
Static
Static analysis
analysis
Warning
Warning
Extended
Extended program
program check
check Error
Error
Warning
Warning
Message
Message
Dump
Dump analysis
analysis Runtime
Runtime error
error

Dynamic
Dynamic Debugging
Debugging Memory
Memory contents
contents
analysis
analysis
General
General memory
memory allocation
allocation
Program
Program interruption
interruption

ABAP
ABAP runtime
runtime Program
Program flow
flow
analysis
analysis
Runtime
Runtime measurement
measurement
Memory
Memory requirements
requirements
R

SQL
SQL Trace
Trace Database
Database access
access
© SAP AG

In the static check, the system checks both the syntax of a program and its semantics (for example,
whether the number and type of parameters passed to a subroutine is correct).
The dump analysis allows you to investigate runtime errors.
Dynamic program analysis occurs while the program is running.
Runtime analysis allows you to analyze the program flow, its runtime, and the memory it requires.
You can analyze SQL statements using both the runtime analysis and the SQL Trace tool.
In the Debugger, you can set breakpoints and display the contents and attributes of fields.

(C) SAP AG BC411 2-4


Syntax Check

*&
*& REPORT
REPORT sapsyntaxcheck.
sapsyntaxcheck. *&
*& INCLUDE
INCLUDE SYNTAXCHECKTOP.
SYNTAXCHECKTOP.
INCLUDE
INCLUDE syntaxchecktop.
syntaxchecktop. REPORT
REPORT syntaxcheck.
syntaxcheck.
INCLUDE
INCLUDE syntaxcheckf01.
syntaxcheckf01.

*INCLUDE
*INCLUDE SYNTAXCHECKF01
SYNTAXCHECKF01

PERFORM
PERFORM subprog.
subprog.
*Form
*Form Routine
Routine not
not defined
defined
Syntax error *in
*in program.
program.
Syntax error in: SYNTAXCHECKF01 Line 5
PERFORM SUBPROGRAM.
The form "SUBPROGRAM" does not exist,
but there is a FORM with the similar name
"SUBPROG"

Edit Correct error


R

© SAP AG

When you check the syntax of an include, the system combines the current contents of the Editor
with the contents of the TOP include to form a unit whose syntax and semantics can be checked
sensibly. If an error occurs, the system interrupts the check and generates an error message, often
with a proposed correction that you can adopt by choosing 'Correct error'. The system then restarts
the syntax check.
The system only checks all includes for completeness and consistency (for example, to ensure that
all subroutines that you call are actually defined) when you run the syntax check for the main
program.

(C) SAP AG BC411 2-5


Syntax Check

*&
*& INCLUDE
INCLUDE SAPBC411D_SYNTAXCHECKF01.
SAPBC411D_SYNTAXCHECKF01.

PERFORM
PERFORM subprogram.
subprogram.
FORM
FORM subprogram.
subprogram.
SELECT
SELECT ...
...
ENDSELECT.
ENDSELECT.
ENDFORM.
ENDFORM.
PERFORM
PERFORM u_pgm.
u_pgm.

Syntax warning:

Statement (PERFORM u_pgm) is not accessible.

© SAP AG

The syntax check may display warnings. The check does not end when a warning occurs, and the
program can, in principle, be generated. However, as a programmer, you should always correct
syntax warnings, since they can often lead to unforeseeable errors.

(C) SAP AG BC411 2-6


Syntax Errors

Extended
Extended PERFORM/FORM interfaces
program
program check
check
CALL FUNCTION interfaces
Screen consistency
STATUS and TITLEBAR
Strings
Field attributes
Conversions
Warnings from the syntax check

© SAP AG

The standard syntax check leaves out many checks to save runtime. Only the extended program
check provides a complete examination of your program that includes the interfaces to other
programs that it calls.
Errors in the extended program check (other than inaccessible coding) cause runtime errors, and
must therefore be corrected. You should also correct warnings. If warnings occur that you want to
ignore (for example, they occur because of dynamic calls in your program), you can use pseudo-
comments to suppress them ("+EC*). For further information, refer to the extended help for the
extended program check transaction.
As a programmer, you should always run the extended program check as part of your development
process. A program is only finished once you have corrected all of the errors and warnings (although
a few non-critical messages may remain).
The extended syntax check, like the standard check, is a static check. This means that runtime errors
may still occur in your program. For example, if your program contains the statement CALL
FUNCTION field, the static check cannot tell whether the value of field corresponds to a valid
function module name. However, if you write CALL FUNCTION 'JOHN_SMITH', the extended
program check will look to see if the function module 'JOHN_SMITH' exists.

(C) SAP AG BC411 2-7


Runtime Errors

Overview
Short
Short text
text
What
What happened?
happened?

Runtime
Runtime errors
errors Internal
Internal errors
errors What
What can
can you
you do?
do?
Error
Error analysis
analysis
Installation
Installation and
and
environment/resource
environment/resource How
How to
to correct
correct the
the error
error
errors
errors
System
System environment
environment
Errors
Errors in
in application
application Info:
Info: Where
Where error
error occurred
occurred
programs
programs
Chosen
Chosen variables
variables
Active
Active calls/
calls/ events
events

...
...
R

Debugger
© SAP AG

There is a range of errors that can occur during an ABAP program that the runtime system
recognizes. When one occurs, the program terminates, and the system generates and displays a short
dump.
The short dump is divided into various blocks that document the error. You can use the overview to
find out exactly what categories of information are available, such as the contents of data objects,
active calls, control structures, and so on.
There are various categories of error:
Internal errors
The kernel has recognized an error. In this case, inform SAP.
Installation and resource errors
An error occurred due to incorrect system installation or missing
resources (for example, database not available).
Errors in application programs. Typical causes include:
Contents of a type P field not in packed format
Arithmetic overflow
Type conflict between the formal and actual parameters of a function module.

(C) SAP AG BC411 2-8


Short Dump Administration

Material
Management
Overview Statistics

Dump Analysis Display


Print

Reorganization

Keep
Release

© SAP AG

ST22 is the transaction for short dump administration.


By default, short dumps are retained in the system for 14 days. However, you can retain a short
dump indefinitely using the Keep function.
You can use the Reorganize function to delete all short dumps older than a certain date.
If you encounter problems in ABAP programs that you cannot solve yourself, you can print out the
short dump and send it to SAP. The information it contains is important for the SAP Hotline and
remote consulting services.
You cannot switch to the Debugger from the short dump administration transaction.

(C) SAP AG BC411 2-9


Dynamic Analysis

Dynamic analysis
Debugging

ABAP runtime
analysis

SQL Trace

© SAP AG

Dynamic analysis occurs while a program is running.


The runtime analysis utility provides an overview of your ABAP program. The Call hierarchy
function shows you the sequence in which the individual program steps (subroutines and other
modularization units, input and output statements) are processed.
You can use the SQL Trace to analyze database accesses.
In the Debugger, you can use the Calls function to display the sequence in which subroutines are
called.
These three methods of dynamic analysis are explained in more detail on the following pages.

(C) SAP AG BC411 2-10


Debugging Mode
1.Browser
Repository Program statement
Program Edit Goto System Help
BREAK-POINT
BREAK-POINT <value>.
<value>. ?

Test/Execute
1. Program
ABAP Editor:
SAPBC411 SAP Training:
Initial Screenstatement
Program BC411
Edit Goto System Help
/H BREAK-POINT
BREAK-POINT <Value>.
<Value>.
Object type development class ...
Debugging ...
Programs
Utilities > Debugging ...
Context_I_C_GEOGR_DISTANCE
...
Context_I_C_GEOGR_DISTANCE
Program SAPBC411D_TEST Create

Execute
Sub-objects

Source code
Variants
Attributes
Documentation
R

© SAP AG

There are four different ways of starting the Debugger:


- From the Repository Browser, by choosing Test/Execute.

- From the ABAP Editor by choosing Debugging.

- From a transaction, by entering /h in the command field.

- From any screen by choosing System -> Utilities -> Debugging.

- By setting breakpoints in the source code and starting the program.

(C) SAP AG BC411 2-11


The Most Important Debugging Functions

Processes
Processes the
the next
next line
line of
of the
the
Single step program.
program.

Continues
Continues processing
processing until
until the
the
next
next breakpoint
breakpoint or
or the
the end
end of
of the
the
Continue
program
program occurs.
occurs.

Displays
Displays aa screen
screen on
on which
which
Breakpoint you can set breakpoints.
you can set breakpoints.

Use
Use this
this button
button to
to display
display
Hexadecimal the
the field
field contents
contents in
in
display hexadecimal
hexadecimal form.
form.

Replace function Allows


Allows you
you to
to change
change the
the
contents of a field.
contents of a field.
R

© SAP AG

In the Debugger, you can use the scroll buttons to scroll through the program code.
The Breakpoint function allows you to define points at which your program is interrupted.
The Hexadecimal display button allows you to toggle between hex and character display.
You can change the value of a field in the field display during a debugging session. To do this, enter
the new contents in the field contents column of the display and choose 'Change field contents'. The
system copies the new value into the contents of the field.

(C) SAP AG BC411 2-12


The Most Important Debugging Functions II

Up
Up to
to five
five watchpoints
watchpoints linked
linked
Watchpoint with
with relational operators.
relational operators.

Pushbutton for
expanding You
You can
can expand
expand structured
structured
substructures fields
fields by
by double-clicking.
double-clicking.

Displaying complex You


You can
can display
display complex
complex
internal tables internal
internal tables
tables and
and expand
expand them
them
by
by double-clicking.
double-clicking.

© SAP AG

You can create watchpoints in the Debugger. These allow you to interrupt your program when the
contents of a particular field change. You can link watchpoints using logical expressions containing
either constant values or field contents.
You can expand a data object that contains a structure as one of its components by double-clicking it.
The Debugger also allows you to display complex internal tables.

(C) SAP AG BC411 2-13


Debugger: Overview
SAP R/3
Debugging Goto Breakpoint Settings Development System Help
?
Watchpoint
Fields Table Breakpoint Watchpoint Calls
Main program Test Bezeichnungen
Fixed point arith.
Source code of Test -
77 68 77
start-of-selection

Select Carrid From Spfli


Crew_Wa-Function = 'PILOT'. Crew_Wa-Flight = '0400'.
Move-Corresponding Crew_Wa To Flight_Table-Crew.
Append Flight_Table-Crew.
Break-point.

Double-click Form f.

Field names 2-5 Field contents


carrid LH
Crew-Flight Table[2x272]
Fldate 19980810
R

Crew ********************************************
SY-SUBRC= 0 SY-TABIX= 2 SY-DBCNT= 30

© SAP AG

In debugging mode, the screen is divided into two areas. In the upper area, the system displays the
program code. The lower area contains different information about the source code, depending on
the settings that you have chosen. You can change the information displayed using the pushbuttons
in the application toolbar.
You can expand the amount of source code displayed by choosing Increase prog. section size.
You can move a line to the top of the displayed area by double-clicking it.
You can display the statement that is currently being processed by choosing Display current
statement. This is particularly useful when you are processing internal tables.
You can display the contents of up to eight fields in the field display.
The bottom line of the Debugger screen displays the three most important system fields and their
contents.

(C) SAP AG BC411 2-14


Expanding Substructures

Structured field FLIGHT_TABLE


Length 272

No Component name Type Length Contents


Component name

1 Carrid C 3 LH
2 Connid N 4 0400
3 Crew h 8
4 Crew-Name C 30 Miller
4 Crew-Function C 20 Pilot
5 Crew-Flight h
6 Crew-Flight-No1 N 4 0400
7 Crew-Flight-No2 N 4 0402
8 Fldate D 8 19980509

© SAP AG

To display a complex structure, choose Goto -> Structured field.


You can navigate deeper into the structure by double-clicking an individual component.
The system displays the length of the structured field, along with the name, type, length, and
contents of its components.

(C) SAP AG BC411 2-15


Breakpoints in Programs
1. ABAP statement 2. Editor function
BREAK-POINT
BREAK-POINT <value>.
<value>. Set
Set
Delete
Delete
Display
Display breakpoint
breakpoint

SAP R/3
Program Edit Goto System Help
BREAK-POINT
BREAK-POINT <value>.
<value>. ?

1 PROGRAM sapbc411d_debugger.
2. Function Breakpoints Bezeichnungen
2 INCLUDE BREAKPOINTS
bc411d_debuggertop.
BREAKPOINTS anzeigen
anzeigen
3 setzen
setzen
SELECT carrid connid FROM sflight INTO
4
löschen
löschen
CORRESPONDING FIELDS OF TABLE itab
5 WHERE carrid = 'LH' AND connid = '0400'.
6 BREAK-POINT 1.
7 LOOP AT itab.
8 WRITE: / itab-carrid, itab-connid.
9 ENDLOOP. Stop
R

10

© SAP AG

There are various ways of setting breakpoints in programs.


From the Editor:
In the ABAP Editor, you can set breakpoints before you even start the program, either by using the
BREAK-POINT statement, or by choosing Utilities → Set Breakpoint. This sets line-oriented
breakpoints. The lines for which they are set are marked with STOP symbols. You can also use the
second method to set breakpoints in display mode.
You can also set breakpoints that are based on field contents (watchpoints).
For further information, see Watchpoints.

(C) SAP AG BC411 2-16


Breakpoints in the Debugger

Breakpoints

No Program Line Statement/Event/... Counter

Stop 1 SAPBC411D_DEBUG 1 append


Stop 2 SAPBC411D_DEBUG 10 start-of-selection
Stop 3 SAPBC411D_DEBUG 70 select
4
5
6
7
8
9
10

© SAP AG

Breakpoints in the Debugger


- To set a breakpoint within the Debugger, position the cursor on a line of code and double-click.
A stop sign appears next to the lines for which a breakpoint has been set.
As well as setting line-oriented breakpoints, you can also set statement-oriented breakpoints in the
Debugger. The Breakpoint menu allows you to set breakpoints at ABAP keywords, events,
subroutines, function modules, and system exceptions.
You can display an overview of the breakpoints that you have set by choosing Breakpoints. To delete
a breakpoint, position the cursor on it and double-click.

(C) SAP AG BC411 2-17


Watchpoints

Watchpoints
Logical operator between watchpoints or and

No L Program Field name Op Field Comparsion field/value

1 x SAPBC411D_DEBUG str-c
2 x SAPBC411D_DEBUG str-i = 1
3 x SAPBC411D_DEBUG i > x sy-index
4 x SAPBC411D_DEBUG sy-tabix = 5
5 x SAPBC411D_DEBUG str-c <

Current contents of the last watchpoint reached:


SAPBC411D_DEBUG i 4

© SAP AG

Watchpoints allow you to interrupt your programs either when the contents of a field change or on
the basis of a comparison with a constant or the contents of another field.
You can set up to five watchpoints.
You can link watchpoints together using the 'AND' and 'OR' operators.
Note: Debugging in production system can cause data inconsistencies, since the system functions /N
and /I lead to a database commit. Similarly, the system triggers implicit commits in normal mode
(see Transaction SM50).

(C) SAP AG BC411 2-18


Runtime Measurement

Runtime Analysis

GET RUN TIME FIELD <f>.

© SAP AG

The runtime analysis utility allows you to analyze how your ABAP program runs. The most
important information that it provides is the real time required by the program. The programs that
you measure using runtime analysis are not changed by the process.
Note that the runtime required by a program depends on the current system load.
You can measure the runtime of a particular sequence of statements within a program using the
GET RUN TIME statement. In this case, you modify the program that you want to measure, because
the GET RUN TIME statement has to be inserted in the program code.
Runtime measurements are returned in microseconds (one microsecond = one millionth of a second).

(C) SAP AG BC411 2-19


Runtime Analysis I
Runtime
Runtime analysis
analysis

Start End

Measure
Measure Analysis
Analysis

Report:
Report: RSDEMO00
RSDEMO00

Performance
data in file

Dialog List

Analysis
R

© SAP AG

The runtime analysis utility allows you to measure the time required by an ABAP program and store
the performance data in a file.
The system profile parameter ABAP/ATRASIZEQUOTA specifies the amount of space allocated in
the file system for storing performance data.
For further information about runtime analysis, refer to the ABAP Workbench Tools online
documentation.

(C) SAP AG BC411 2-20


Runtime Analysis II
Runtime analysis

Analysis screen

Group hit list Overall


Overall Table hit
hit list list call hierarchy
Group hit list

Detail selection
Analysis screen
Call hierarchy

Subtree R

© SAP AG

You can display various analyses, including the entire program, or individual program sections such
as subroutines.

(C) SAP AG BC411 2-21


Measurable Functions I

Modularization Units
ABAP programs Program/Report

Modules (screens) MODULE

Subroutines PERFORM

Methods CALL METHOD

Events RAISE EVENT

Function modules CALL FUNCTION

Contexts SUPPLY/DEMAND

Reports SUBMIT R

© SAP AG

ABAP program analysis is based on:

modularization units, and the statements listed on the next page.

(C) SAP AG BC411 2-22


Measurable Functions II
Database/file access
SELECT/INSERT/UPDATE/
SAP SQL DELETE

Direct SQL interface EXEC SQL

Data cluster EXPORT/IMPORT

Sequential files TRANSFER/READ


DATASET

Internal tables

Extending APPEND/COLLECT

Processing LOOP

Sorting SORT

System times
R

Load/generate programs
© SAP AG

Input/Output statements
Statements for internal table operations and
system times

The Call hierarchy function displays a detailed list of measurable functions. The group hit list
summarizes these functions into groups. Within the groups, the calls are listed in descending order
of gross runtime, allowing you to identify immediately the most expensive call within a group.

(C) SAP AG BC411 2-23


Gross and Net Times
PROGRAM SAPBC411D_...
.
.
.

SELECT
.
.
.

PERFORM
.
.

SORT
.
.
.
.
.
.
R

Gross Net
© SAP AG

Gross time = Total time required to execute the relevant functions


Net time = Gross time less the time required for modularization units and other selected
statements. The net time is the time that is not otherwise accounted for.
You can display times either as a percentage, or as absolute times in microseconds.
For further information about the procedure, refer to the online documentation in the ABAP Editor
for the SET RUNTIME ANALYZER ON/OFF statement.

(C) SAP AG BC411 2-24


The GET RUN TIME Statement
GET RUN TIME FIELD <f>.

PROGRAM xxx.
DATA: t1 TYPE i,
t2 TYPE i,
run_time TYPE i.

GET RUN TIME FIELD t1.


Statement block
GET RUN TIME FIELD t2.
run_time = t2 - t1.

© SAP AG

The first time the GET RUN TIME statement is executed, the field <f> is initialized. Each
subsequent time the statement is executed, the system places the runtime in microseconds since the
first call into field <f>.
The measurement results depend on the overall system load, and the system may return differing
runtimes for the same block of statements. Time differences can also be caused, for example, by a
data record being read from the buffer on one occasion, but from the database another time.

(C) SAP AG BC411 2-25


Test Frame I
REPORT
REPORT sapbc411d_testframe.
sapbc411d_testframe.

TYPES:
TYPES:
BEGIN
BEGIN OF
OF result_line,
result_line,
text(60)
text(60) TYPE
TYPE c,
c,
time
time TYPE i,
TYPE i,
END
END OF
OF result_line.
result_line.
DATA:
DATA:
t1
t1 TYPE
TYPE i,
i,
t2
t2 TYPE i,
TYPE i,
base_time
base_time TYPE
TYPE i,
i,
res_time(8)
res_time(8) TYPE
TYPE pp DECIMALS
DECIMALS 1,
1,
ii TYPE
TYPE i,
i,
result
result TYPE
TYPE result_line
result_line OCCURS
OCCURS 10
10 WITH
WITH
HEADER LINE.
HEADER LINE.
PARAMETERS:
PARAMETERS:
in_cnt
in_cnt TYPE
TYPE ii DEFAULT
DEFAULT 100,
100,
R
out_cnt
out_cnt TYPE i DEFAULT 20.
TYPE i DEFAULT 20.
** Specifc
Specifc data
data for
for the
the measurement
measurement ...
...
© SAP AG

You can use this test framework program to measure the runtime of different coding variants.

(C) SAP AG BC411 2-26


Test Frame II
** Start
Start measurement
measurement
PERFORM
PERFORM fill_result
fill_result USING:
USING:
’Base
’Base time’,
time’, "#EC
"#EC NOTEXT
NOTEXT
’..Variant
’..Variant 1.......’,
1.......’, "#EC
"#EC NOTEXT
NOTEXT
’..Variant
’..Variant 2.......’.
2.......’. "#EC
"#EC NOTEXT
NOTEXT
LOOP
LOOP ATAT result.
result.
ii == sy-tabix.
sy-tabix.
result-time
result-time == 99999999.
99999999.
DO
DO out_cnt
out_cnt TIMES.
TIMES.
GET
GET RUN
RUN TIME
TIME FIELD
FIELD t1.
t1.
DO
DO in_cnt
in_cnt TIMES.
TIMES.
PERFORM
PERFORM ii OFOF f0
f0 f1
f1 f2.
f2.
ENDDO.
ENDDO.
GET
GET RUN
RUN TIME
TIME FIELD
FIELD t2.
t2.
t2
t2 == t2
t2 -- t1.
t1.
IF
IF t2
t2 << result-time.
result-time. result-time
result-time == t2.
t2.
ENDIF.
ENDIF.
ENDDO.
ENDDO.

© SAP AG

You use two loop counters to determine the number of test runs.
If the statement(s) that you want to measure have a very short runtime, choose a high value for the
inner loop (for example, the statement MOVE c1 to c2 has a shorter runtime than the
measurement accuracy of 1µs. In this case, you would run the statement several times and divide the
total runtime by the number of loop passes).
You use the outer loop to determine the number of test runs, from which you then take the minimum
runtime. This process should eliminate factors, such as changing work process, that can make
individual measurements inaccurate.

(C) SAP AG BC411 2-27


Test Frame III

IF
IF ii == 1.
1.
base_time
base_time == result-time.
result-time.
ELSE.
ELSE.
SUBTRACT
SUBTRACT base_time
base_time FROM
FROM result-time.
result-time.
ENDIF.
ENDIF.
MODIFY
MODIFY result.
result.
ENDLOOP.
ENDLOOP.
LOOP
LOOP ATAT result.
result.
t1
t1 == result-time
result-time // in_cnt.
in_cnt.
WRITE:
WRITE: // result-text,
result-text, res_time.
res_time.
ENDLOOP.
ENDLOOP.

© SAP AG

The field base_time is the time that the system needs to call the 'control' FORM routine f0. This
routine should always either be left empty or contain statements that are processed in every form
routine, but do not belong to the statements that you want to measure.

(C) SAP AG BC411 2-28


Test Frame IV
*& FORM FILL_RESULT
FORM fill_result USING text.
result-text = text.
APPEND result.
ENDFORM.

*& FORM F0
FORM f0.
...
ENDFORM.
*& FORM F1 Variant 1
FORM f1.
Statements for variant 1
ENDFORM.

*& FORM F2 Variant 2


FORM f2.
Statements for variant 2 R

ENDFORM.

© SAP AG

In the subroutines f1 and f2, program the variants whose runtime you want to compare.
Subroutine f0 can contain statements that are common to both variants (initializiation, closing
processing, and so on).

(C) SAP AG BC411 2-29


Database Access

ABAP
ABAP
Program

Runtime analysis

SQL Trace

Database R

© SAP AG

The runtime analysis function tells you the number of database operations and the gross time that
they require, that is, the time including that spent in queues or network overhead time.
Runtime analysis provides useful information about access to buffered tables, since they, by
definition, do not involve database access. However, for a precise analysis of the runtime required by
SQL statements and their conversion in the database, you need the SQL Trace utility. This provides
not only the runtime, but also other database-relevant information such as the index used to read the
database.

(C) SAP AG BC411 2-30


SQL Trace

Application server Database I/O

e
T rac
S QL

© SAP AG

The SQL Trace tool allows you to analyze the execution of SQL statements, locking operations, and
Remote Function Calls.
This section of the course concentrates on the runtime of SQL access.
Only one person can use the SQL Trace on an application server at any one time. You should
therefore switch it off as soon as you have finished with it.
You start the SQL Trace using Transaction ST05, or by choosing the System -> Utilities -> SQL
Trace.
The SQL Trace does not include access to buffered tables except in the case of the first time they are
read (when they are not yet stored in the buffer).
The SQL Trace measures the time that the database need to execute a statement. Runtime analysis,
on the other hand, measures the overall time required by the statement within the context of the
application program, that is, the execution time plus the time spent in queues and that required for
network transmission.

(C) SAP AG BC411 2-31


SQL Trace - Basic List
Trace Basic List
Debugging Goto Breakpoint Settings Development System Help
?

DDIC Info Explain SQL ABAP Display More Info

Bezeichnungen
Transaction = SAPBC411 Client = 000 User = Heilerm

Duration Object Oper Rec RC Statement

10,998 TRDIR REEXECS 1 0 Select Where "name" = 'SAPBC411_...


684 REEXECS 0 0 Free
14,920 SPFLI PREPARE Select Where "mandt" = ? AND "carrid"

461 SPFLI DECLARE Select Where "mandt" = ? AND "carrid"

347 SPFLI OPEN Select Where "mandt" = '400' AND "...

191,329 SPFLI FETCH 6 0

206 SPFLI FETCH 6 0

300 SPFLI FETCH 0 100


R

209 SPFLI CLOSE 0 0

© SAP AG

The basic list of the SQL Trace contains the following information:
Duration: The time in microseconds (10-6) required by the database to execute the operation.
The individual columns have the following meanings:
Object The database table to which the operation refers
Oper The operation executed by the database. This can be one of the following:
Declare Creates a new cursor for an SQL statement and assigns a cursor number to it
Prepare Converts the SQL statement and determines the execution plan
Open/Close Opens/closes the cursor with the precise values required for the access
Reopen Reuses an existing cursor in the cursor cache on the application server
Fetch Moves the cursor through the data and sends it to the application server
EXEC/REEXECS: If you want to insert, change, or delete data
Rec The number of records read
RC The return code of the corresponding statement
Statement The SQL statement currently being processed
'Expensive' statements (more than 100,000 µs) are highlighted in red.
For further information about a statement, choose the 'MORE INFO' function.

(C) SAP AG BC411 2-32


SQL Trace Function: Explain SQL

SQL Statement

SELECT
"CARRID" , "CONNID" , "PAYMENTSUM", "CURRENCY"
FROM
"SPFLI"
WHERE
"MANDT" = :A0000 AND "CARRID" = :A0001

Execution Plan
SELECT STATEMENT
5 TABLE ACCESS BY ROWID SPFLI
INDEX RANGE SCAN SPFLI______0

© SAP AG

The Explain SQL function provides a more detailed analysis of an SQL statement. It displays how
the statement is executed and, above all, the index that is used. SFLIGHT____0 means that the
primary index was used. A figure other than zero indicates that the statement used a secondary index
from the ABAP Dictionary.
The precise display of the Explain SQL function depends on the database system. The above
example shows how it appears under Oracle.
For further information about indexes, refer to the ABAP Open SQL unit.

(C) SAP AG BC411 2-33


Index Range Scan/Access by Rowid

SELECT ... FROM SPFLI WHERE CARRID IN ITAB_CARRID.

SPFLI_______0 SPFLI
MANDT CARRID CONNID ROWID ROWID MANDT CARRID CONNID...
--------------------------------------------------- ---------------------------------------------------
001 AA 0017 1237 1234 001 AA 0017
001 AA 0064 1235 1235 001 AA 0064
001 AZ 0555 1234 1236 001 AZ 0555
001 AZ 0788 1236 1237 001 AZ 0788

Index for primary key


Table contents R

© SAP AG

When you access the database using index range scan/access by rowid, the system starts searching
from the point in the table where the specified key occurs in the primary key, and reads sequentially
until the key changes. Table entries that match the key are ready from the table using their ROWID.

(C) SAP AG BC411 2-34


Summary

In this unit, you have learned the typical steps involved


in program development, in particular how to check
programs using
Static check
Runtime check
and the most important functions for
Dynamic program checks:
Runtime analysis
The GET RUN TIME statement
SQL Trace
Debugger

© SAP AG

(C) SAP AG BC411 2-35


Types: Contents

The ABAP type concept


ABAP Dictionary types and ABAP program types
Type compatibility and conversion
Type conversion and performance
Runtime type information

© SAP AG
Unit Objectives
At the end of this unit, you will be able to explain:
The system of types in ABAP
How ABAP Dictionary types are based on program
types
The type compatibility and type conversion rules in
ABAP
How type conversions can affect the performance of
programs
How you can find out about the type of a data object
at runtime

© SAP AG

(C) SAP AG BC411 3-2


Data Types
Data type

Predefined User-defined

Elementary Structured
(Data element)

Structured type Table type Class/Interface


(Structure)

y r
na
io

m
ct

ra
Di

og
AP

Pr
R
AB

AP
AB
© SAP AG

The ABAP type concept is based on the following ideas:


User-defined data types can be either elementary or structured. Elementary types cannot be
broken down into other, smaller components. Structured types, on the other hand, consist of any
number of elementary or other structured types.
There are two types of structured data types - structure types and table types:
You can combine components of any type to form a structure (record in other terminology).
You can combine lines of any type to form a table type (array in other terminology).
Data types that are structure types or table types may contain other structure types or table types as
elements.
ABAP Types can be defined either locally in an ABAP program or systemwide in the ABAP
Dictionary. In the ABAP Dictionary,
user-defined elementary types are called data elements
user-defined structure types are called structures.

(C) SAP AG BC411 3-3


Predefined ABAP Types

Data type Description Initial value Default Permitted


length length

P Packed number 0 8 1-16


Numeric

I Integer 0 4 4

F Floating point number 0.000 8 8

Numeric string 00...0 1 1 - max.


N
Alpha-numeric

C Text Space 1 1 - max.

D Date YYYYMMDD 00000000 8 8

T Time HHMMSS 000000 6 6

X Hexadecimal X‘00‘ 1 1 - max.


R

Reference - - -
REF TO
© SAP AG

There are nine predefined data types in ABAP.


The numeric types P, I, and F have the following attributes and value ranges:
Type Attribute Value range Suitable for
I Integer - 231 bis +231 Counters, numbers,
indexes, periods
P Number with decimal places 2 digits per byte Currency amounts, length, weight
F Floating point -2.2E-308 to +1.8E308 Calculations with very large amounts
In terms of runtime, calculations with type I numbers is the cheapest, followed by type F, with type
P calculations being the most expensive. Note, however, that the system may round or truncate type
F numbers. In particular, it is not a good idea to test whether two floating point numbers are equal.
Instead, you should check whether they differ by less than a predefined amount. You should only
use type F numbers for mathematical problems where rounding errors are tolerable. Use type P
numbers for business calculations.
Type P numbers are stored with two digits per byte. The last half-byte is used for the plus or minus
sign.

(C) SAP AG BC411 3-4


Predefined Dictionary Types I

Type Description Permitted length n ABAP type

DEC Calculation/amount field 1-31, in tables 1-17 P((n+1)/2)

INT1 1 byte integer 3 internal

INT2 2 byte integer 5 internal


INT4 4 byte integer 10 I
P((n+1)/2)
CURR Currency field 1-17
C(5)
CUKY Currency key 5
QUAN P((n+1)/2)
Quantity 1-17
UNIT C(n)
Unit key 2-3
PREC X(2)
Accuracy of QUAN field 2
FLTP F(8) R

Floating point number 16

© SAP AG

The ABAP Dictionary has significantly more built-in types than the ABAP programming language.
ABAP Dictionary data types are converted into corresponding ABAP types in ABAP programs.
ABAP Dictionary data types have the following semantics (continued on next page):
DEC Calculation or amount field with decimal point, sign, and thousand separators
INT1 1 byte integer, value between 0 and 255
INT2 2 byte integer, value between -32767 and 32767
INT3 4 byte integer, value between -2177483647 and 2177483647
CURR Currency field. Corresponds to a DEC amount field.
Fields with this type must point to a reference field with type CUKY.
CUKY Currency key referenced by a type CURR field.
QUAN Quantity field. Corresponds to a DEC amount field.
Fields with this type must point to a reference field with type UNIT.
UNIT Unit key referenced by a type QUAN field.
PREC Accuracy of a QUAN field.
FLTP Floating point number.
NUMC Numeric text. May only contain digits.

(C) SAP AG BC411 3-5


Predefined Dictionary Types (2)

Type Description Permitted length n ABAP type

NUMC Numeric text 1-255 N(n)


CHAR Character 1-255 C(n)

LCHR Long Character 256-max C(n)


DATS Date 8 D
ACCP Accounting period YYYYMM 6 N(6)

TIMS Time HHMMSS 6 T


RAW Uninterpreted byte sequence 1-255 X

LRAW Long byte sequence 256-max X(n)

CLNT Client 3 C(3)

LANG Language int. 1, ext. 2 C(1) R

© SAP AG

CHAR Character. Fields with type CHAR may only be up to 255 characters long in tables.
If you use longer character fields in tables, use the data type LCHR. There is no
length restriction in structures.
LCHR. Character string at least 256 characters long. Fields of this type must occur at the
end of transparent tables and be preceded by a length field with type INT2 that is
filled with the required length when the table is filled.
DATS Date.
ACCP Accounting period in the format YYYYMM.
TIMS Time
RAW Byte sequence. Fields with type RAW may only be up to 255 characters long in
tables. If you want to use longer RAW fields in tables, use the data type LRAW.
LRAW Byte sequence of any length longer than 256 bytes. Fields of this type must
occur
at the end of transparent tables and be preceded by a length field with type INT2
that is filled with the required length when the table is filled.
CLNT Client
LANG Language key. This is displayed as a two-character code, but stored in the
database as a single character. It is converted using the exit ISOLA.

(C) SAP AG BC411 3-6


Calculations Using Numeric Types

ABAP performs calculations using either F, P, or I arithmetic. The


arithmetic used is determined by the following rule:

F before P before I

REPORT sapbc411d_arithmetic.
DATA: int1 TYPE i, int2 TYPE i,
pack1 TYPE p, float TYPE f.

int1 = 1. int2 = 3. pack1 = 3.


float = ( int1 / int2 ) * pack1.
WRITE float. 1,0000000000000000E+00

© SAP AG

ABAP has three different kinds of arithmetic: F, P, and I.


Arithmetic expressions are calculated using one of there three types. All of the operands (including
the answer) are considered when determining the type of arithmetic to use.
The priority rule is F before P before I. This means that:
If at least one of the operands has type F, ABAP will use type F arithmetic.
If there are no type F operands, but at least one type P operand, ABAP will use type P arithmetic.
If there are no type F or P operands, ABAP will use type I arithmetic.
Note that:
Operands with inbuilt functions (such as SQRT(…)) are type F.
Numeric strings up to nine digits are type I, and numeric strings with ten or more digits are type
P.

(C) SAP AG BC411 3-7


Summary of Declarative Statements
Type
TYPES

Constant
CONSTANTS

Elementary field, structure,


internal table DATA

Input parameter
PARAMETERS

Selection criteria
SELECT-OPTIONS
RANGES

Table work area


R

TABLES

© SAP AG

You should already know the following declarative statements:

TYPES Defines a type


CONSTANTS Defines a constant
DATA Defines an elementary field, structure, or internal table
PARAMETERS Defines an input parameter
TABLES Defines a table work area
SELECT-OPTIONS Defines a selection criterion

You can display a full list of ABAP declarative statements in the ABAP Editor F1 help by choosing
ABAP Overview -> Overview of the ABAP Programming Language -> Classification of Key Words
by Type.

(C) SAP AG BC411 3-8


Type Conversion
Compatible types can be assigned to each other without conversion.

Two elementary types are compatible when they


have exactly the same type and length (and, for
type P fields, the same number of decimal places).

Two structured types are compatible when they have


exactly the same structure and their components are
compatible.

Two table types are compatible when their line types are compatible and their
key sequences, uniqueness attributes and table types are the same.

Two object references are compatible when they refer to the same class. An
object reference is compatible with an interface reference when the class
referenced by the object implements the interface.

Non-compatible types can be converted if a conversion rule exists.

© SAP AG

If you assign data objects to each other, the ABAP runtime system converts the types if:
the two types are incompatible, and
there is a defined conversion rule.
An object reference o1 with the type REF TO <class> is compatible with object reference o2 when
o2 references the class <class> or one of its subclasses. Object references with the type <class> are
compatible with interface references when the class <class> implements the interface.
The conversion rules are explained on the following pages.

(C) SAP AG BC411 3-9


Conversion Rules for Elementary Types
Conversion rules exist for MOVE, COMPUTE and comparisons, but not
not for
the assignment of actual parameters to formal parameters in FORMS,
FORMS,
FUNCTIONS, METHODS, and ABAP Objects events.
For MOVE, COMPUTE, and comparisons, there are conversion rules for
for all
type combinations except
T to D and vice versa
for ABAP Objects (classes and interfaces)

REPORT sapbc411d_performance_conversi.
DATA: pack TYPE p DECIMALS 2 VALUE '100,00',
char5(5) TYPE c VALUE '12,34',
char7(7) TYPE c VALUE '6789,00'.

MOVE char5 TO char5. "Types compatible(cost 2 microsec.)


MOVE char5 TO char7. "Type conversion (cost 3 microsec.)
MOVE char5 TO pack. "Type conversion (cost 11 microsec.) R

© SAP AG

Conversion rules only exist for MOVE, COMPUTE, and comparisons, not for assignments of actual
parameters to formal parameters in procedures.
There are no conversion rules for types D to T (or T to D), or for ABAP Objects (object reference to
object reference, object reference to interface reference). Assignments or comparisons of this type
cause syntax errors.
Type conversions at runtime can cause runtime errors.
Conversions from numeric to non-numeric types and vice versa are runtime-intensive.
For full information about conversion rules for elementary types, refer to the online documentation
in the ABAP Editor for the MOVE statement.

(C) SAP AG BC411 3-10


Conversion Rule for Structure types
PROGRAM SAPBC41D_CONVERSION_OF_RECORD.
DATA: BEGIN OF rec1,
text1(3) TYPE C VALUE 'AAA',
text2(2) TYPE C VALUE 'BB',
pack TYPE P DECIMALS 2 VALUE '2.26',
text3(10) TYPE C VALUE 'YY',
END OF rec1,
BEGIN OF rec2,
text1(5) TYPE C VALUE 'CCCCC',
pack TYPE P DECIMALS 2 VALUE '72.34',
text3 TYPE C VALUE 'Z',
END OF REC2.

MOVE REC1 TO REC2.

REC1 AAA BB 2.26 YY

C REC2 CCCCC 72.34 Z


R

REC2 AAABB 2.26 Y

© SAP AG

ABAP has rules for converting


From structures to structures
From elementary fields to structures
From structures to elementary fields.
In each of these cases, the ABAP processor converts the structures into type C fields.
Internal tables can only be converted into other internal tables. The system converts the
corresponding line type.

(C) SAP AG BC411 3-11


Information About an Object at Runtime
DESCRIBE FIELD <f> LENGTH <len>
TYPE <type> [COMPONENTS <n>]
OUTPUT-LENGTH <len>
DECIMALS <n>.
DESCRIBE TABLE <itab> LINES <lines> [OCCURS <n>].

REPORT xyz.
TABLES: sflight.
DATA: flightinfo_list LIKE bcxaa OCCURS 10,
line_count TYPE I.

SELECT * FROM sflight INTO TABLE flightinfo_list.


DESCRIBE TABLE flightinfo_list LINES line_count.

Internal table FLIGHTINFO_LIST


CARRID CONNID ...

AA 0017 LINE_COUNT
AA 0017
AA 0026 4
AA 0026
R

© SAP AG

The DESCRIBE FIELD statement allows you to find out the following runtime information (RTTI
= runtime type information) about any data object:
Its defined length (LENGTH)
Its type (TYPE) and (for structures) the number of components (COMPONENTS)
The output length (OUTPUT-LENGTH)
The number of decimal places (DECIMALS).
The DESCRIBE TABLE statement allows you to display information about an internal table.
The LINES addition returns the current number of table entries.
The OCCURS addition returns the value from the OCCURS or INITIAL SIZE addition in the
table definition.

(C) SAP AG BC411 3-12


Summary

You can create data types either locally in a program or


systemwide in the ABAP Dictionary.
ABAP has three numeric types (P,I,F), five non-numeric
types (N,C,D,T,X), and a reference type (REF TO).
Each ABAP Dictionary type is converted by the ABAP
runtime environment into a numeric or non-numeric ABAP
data type.
The ABAP runtime system has type compatibility rules for
MOVE, COMPUTE, comparisons of data objects, and the
assignment of actual parameters to formal paramters.
There are type conversion rules for MOVE, COMPUTE, and
comparisons of data objects.

© SAP AG

(C) SAP AG BC411 3-13


Field Symbols: Contents

Pointers and field symbols


Using field symbols
Defining and assigning field symbols

© SAP AG
Unit Objectives
At the end of this unit, you will be able to
Explain the difference between field
symbols and pointers in other
programming languages (reference and
value semantics)
Use field symbols in ABAP
Define field symbols
Assign a data object to a field symbol

© SAP AG

(C) SAP AG BC411 4-2


Pointers and Field Symbols

Pointer ABAP field symbol


Pointer p1 Data object p1^ Field symbol <fs1> Data object f1

4 4
ASSIGN f1 TO <fs1>.
Pointer p2 Data object p2^ Field symbol <fs2> Data object f2

5 5
ASSIGN f2 TO <fs2>.

© SAP AG

Field symbols in ABAP are similar to pointers in other programming languages. However, pointers
(as used in PASCAL or C) differ from ABAP field symbols in their reference syntax.
The statement ASSIGN f TO <fs> assigns the field f to field symbol <fs>. The field symbol
<fs> then "points" to the contents of field <f> at runtime. This means that all changes to the
contents of f are visible in <fs> and vice versa. You declare the field symbol <fs> using the
statement
FIELD-SYMBOLS: <fs>.

(C) SAP AG BC411 4-3


Reference and Value Semantics

p1 = p2. Reference semantics


Pointer p1 Data object p1^

4 ASSIGN <fs1> TO <fs2>.

Pointer p2 Data object p2^

Value semantics <fs1>


> = <fs2>.
Field symbol <fs1> Data object f1

p1^ = p2^. 4

Field symbol <fs2> Data object f2


R

© SAP AG

Reference syntax
Programming languages such as PASCAL and C use a dereferencing symbol to indicate the
difference between a reference and the object to which it refers; so PASCAL would use p^ for a
pointer instead of p, C would use *p instead of p. ABAP does not have any such dereferencing
symbol.
- In PASCAL or C, if you assign a pointer p1 to a pointer p2, you force p1 to point to the object
to which p2 refers (reference semantics).
- In ABAP, if you assign a field symbol <fs1> to a field symbol <fs2>, <fs1> takes the
value of the data object to which <fs2> refers (value semantics).
- Field symbols in ABAP are always dereferenced, that is, they always access the referenced
data object. If you want to change the reference yourself in ABAP, you can use the ASSIGN
statement to assign field symbol <fs1> to field symbol <fs2>.
Position in a data structure
Field symbols in ABAP are defined using the FIELD-SYMBOLS statement. However, the
statement does not define any data type of the ABAP type concept. This means that you cannot use
field symbols for chained lists or trees. Instead, chained lists can be programmed very elegantly in
ABAP using internal tables.

(C) SAP AG BC411 4-4


Using Field Symbols - Overview

<fs>
Dynamic offset and length for a string
A B C D E F G H I ...

<fs> Addressing fields whose name is


field_name
unknown until runtime
S F L I G H T - C A R R I D ...

Dynamic ASSIGN for any


SFLIGHT-CARRID L H
data object

<fs>
Processing components of a
structure
LH 0400 12/31/1997 ... R

© SAP AG

You can use field symbols to


Set the offset and length for a string variably at runtime
Adopt or change the type of a field dynamically at runtime
Set a pointer to a data object at runtime (dynamic ASSIGN)
Process the components of a structure
Assign an alias to a data object (for example, a shortened name for data objects structured through
several hierarchies - <fs>-f instead of rec1-rec2-rec3-f
(from Release 4.5A) Point to lines of an internal table (this makes it possible to process internal
tables without a separate work area. For further information, refer to Appendix A .

(C) SAP AG BC411 4-5


Using Field Symbols (1)
FIELD-SYMBOLS <fs> [TYPE typ | LIKE s].
ASSIGN field TO <fs>.

REPORT sapbc411d_field_symbols.
DATA counter TYPE i. 0

FIELD-SYMBOLS <fs> LIKE counter.

counter = 15. 15

ASSIGN counter TO <fs>. 15

WRITE : / counter, <fs>. 15 15

<fs> = 17. 17

WRITE : / counter, <fs>. 17 17

© SAP AG

You declare field symbols using the FIELD-SYMBOLS statement. They may be declared either
with or without a specific type.
At runtime, you assign a field to the field symbol using the ASSIGN statement. All of the operations
on the field symbol act on the field that is assigned to it.
When you assign a field to an untyped field symbol, the field symbol adopts the type of the field. If,
on the other hand, you want to assign a field to a typed field symbol, the type of the field and that of
the field symbol must be compatible.
A field symbol can point to any data object. From Release 4.5A, they can also point to lines of
internal tables.
The brackets (<>) are part of the syntax. This makes it easy to distinguish field symbols from normal
fields.

(C) SAP AG BC411 4-6


Using Field Symbols (2)
UNASSIGN <fs>.
IF <fs> IS ASSIGNED.

PROGRAM sapbc411d_field_symbols.

UNASSIGN <fs>.

IF <fs> IS ASSIGNED.
WRITE 'Field symbol points to a data object'(001).
ELSE.
WRITE 'Field symbol points nowhere'(002).
ENDIF.

© SAP AG

Use the expression <fs> IS ASSIGNED to find out whether the field symbol <fs> is assigned to
a field.
The statement UNASSIGN <fs> sets the field symbol <fs> so that it points to nothing. The logical
expression <fs> IS ASSIGNED is then false. The corresponding negative expression is
IF NOT <fs> IS ASSIGNED.
An unassigned, untyped field symbol <fs> behaves as though it were a constant with type C(1)
and initial value.

MOVE <fs> TO dest Transfers the initial value SPACE to the variable dest
MOVE 'abc' TO <fs> Not possible, since <fs> is a constant

(C) SAP AG BC411 4-7


Assigning Parts of Strings Dynamically
REPORT sapbc411d_dyn_string_assign.
DATA: text_line(30) VALUE ’ABCDEFGHIJKLMNOPQRSTUVWXYZ’,
short_text_line(5),
start TYPE i,
string_length TYPE i.
FIELD-SYMBOLS <fstring>.

start = 2. string_length = 5.
MOVE text_line+start(string_length) TO short_text_line.
ASSIGN text_line+start(string_length) TO <fstring>.
WRITE: / <fstring>. CDEFG
<fstring> = '123456789'.
WRITE: / <fstring>. 12345
WRITE: / text_line.
AB12345HI...
<fstring>

A B C D E F G H I ... Text_line

© SAP AG

There are very few statements in which you may specify offset and length using variables (MOVE,
WRITE… TO, actual parameters).
If you cannot use variables to specify offset and length, you can use a field symbol instead of the
field, since you can always use variable offset and length in the ASSIGN statement.
The first time you use the ASSIGN statement for an untyped field symbol, it adopts the type of the field
that you assign to it.

(C) SAP AG BC411 4-8


Processing Individual Characters in a String
REPORT sapbc411d_fs_string.
DATA: string(15) TYPE c VALUE 'HUGO BOSS',
n TYPE i.
FIELD-SYMBOLS <fs>.

n = STRLEN( string ).

ASSIGN string(1) TO <fs>.


DO n TIMES.
WRITE: / <fs>.
IF sy-index NE n.
ASSIGN <fs>+1 TO <fs>.
ENDIF.
ENDDO.
<fs>

...
R

string H U G O B O S S

© SAP AG

The above program uses a loop to assign each individual character of a string to the field symbol
<fs>. This is more efficient than the following algorithm, which uses variable offset to address the
string:

DO n TIMES.
ASSIGN string+sy-index(1) TO <fs>.
ENDDO.
It is important to query whether sy-index is unequal to n, since in the last loop pass, the field symbol
<fs> will point to the next memory address following the string. This could be a value that lies
outside the segment boundaries (see also memory protection concept).

(C) SAP AG BC411 4-9


Dynamic Field Assignment
REPORT sapbc411d_dyn_assign.
TABLES sflight.
DATA field_name(30).
FIELD-SYMBOLS <tab_field>.

field_name = 'SFLIGHT-CARRID'.
ASSIGN (field_name) TO <tab_field>.
IF sy-subrc EQ 0.
SELECT * FROM sflight.
WRITE: / <tab_field>.
LH
.
.

<tab_field>

field_name S F L I G H T - C A R R I D

SFLIGHT-CARRID L H

© SAP AG

The ASSIGN statement allows you to assign a field to a field symbol even if you do not know the
name of the field until runtime. In this case, you must specify the field containing the field name in
parentheses. In the above example, the field field_name contains the name of the field to be
assigned to the field symbol <tab_field>. Note that dynamic ASSIGN statements are very
runtime-intensive.
You can assign an ABAP Dictionary field to the field symbol using the addition TABLE FIELD.
The statement would then read (as in the above example)
ASSIGN TABLE FIELD (field_name) TO <tab_field>.
This shortens the runtime required by the statement, since the system knows that it does not have to
search in the list of program fields.
After the ASSIGN statement, the return code field SY-SUBRC tells you whether a field was
assigned to the field symbol:
SY-SUBRC = 0: The field in parentheses contained a valid field name.
SY-SUBRC > 0: The field in parentheses did not contain a valid field name. The field symbol
continues to point to the data object to which it pointed before the ASSIGN statement.

(C) SAP AG BC411 4-10


Referring to Components of a Structure
fieldname
ASSIGN COMPONENT n OF STRUCTURE rec TO <fs>.

PROGRAM
PROGRAM sapbc411_assign_component.
sapbc411_assign_component.
TABLES
TABLES sflight.
sflight.
FIELD-SYMBOLS:
FIELD-SYMBOLS: <fs>.
<fs>.

SELECT
SELECT ** FROM
FROM sflight.
sflight.
PERFORM
PERFORM write
write USING
USING sflight.
sflight.
ENDSELECT.
ENDSELECT.

FORM
FORM write
write USING
USING rec.
rec.
DO.
DO.
ASSIGN
ASSIGN COMPONENT
COMPONENT sy-index
sy-index OF
OF STRUCTURE
STRUCTURE rec
rec TO
TO <fs>.
<fs>.
IF sy-subrc NE 0.
IF sy-subrc NE 0. <fs>
EXIT.
EXIT.
ENDIF.
ENDIF.
WRITE
WRITE <fs>.
<fs>.
ENDDO.
ENDDO.
ULINE.
ULINE. R

ENDFORM.
ENDFORM.
sflight LH 0400 12/31/1997 ...
© SAP AG

You can never address a component of an untyped structure:


FORM routine USING rec.
* ASSIGN ('rec-f') TO <fs>. "Unable to access components of
untyped * structure
ENDFORM.
Instead, use ASSIGN COMPONENT f OF STRUCTURE rec TO <fs>.
This variant of the ASSIGN statement allows you to access the components of any structure. The
corresponding components of the structure rec are assigned to the field symbol <fs>.
You can assign the components by their name or their index.
If comp has type C or is a structure that does not contain an internal table, it is regarded as a
component name. Otherwise, it is interpreted as the component number. The statement returns a
value of SY-SUBRC unequal to 0 if the specified component comp of structure rec could not be
assigned to the field symbol.
In the above example, the subroutine write displays all of the components of the structure rec passed
to it.

(C) SAP AG BC411 4-11


Changing the Field Type

ASSIGN field TO <fs> [TYPE type] [DECIMALS n].

PROGRAM sapbc411d_fs_type_change.
PARAMETERS: packed(3) TYPE p DEFAULT '128',
DATA: lastdigits(2) TYPE c,
len TYPE i.
FIELD-SYMBOLS: <fs>.
ASSIGN packed to <fs> TYPE 'X'.
MOVE <fs>+2(1) TO lastdigits.
WRITE: / lastdigit+1(1).

© SAP AG

If a field symbol is untyped, you can use the TYPE addition to assign the type <type> to the field
symbol <fs>. The output length of the field symbol is then adjusted to the correct length for that
type.
You should only use the TYPE addition for typed fields if the type of the field field does not
correspond to that of the field symbol <fs>. The type <type> must be compatible with the type of
the field symbol. Since there is no type conversion with field symbols, the contents of field f must
also be compatible with the type <type>.

(C) SAP AG BC411 4-12


Address space
Memory Protection

All global data

All local data Table work


area 1

Table work area 2 Common


part 1

Common ...
part 2

© SAP AG

The danger with pointers is that they may point to invalid areas. This danger is not so acute in
ABAP, because the language does not use address arithmetic (for example, in other languages,
pointer p might point to address 1024. After the statement p = p + 10, it would point to address
1034). However, the danger does still exist, and memory protection violations lead to runtime
errors.
A pointer in ABAP may not point beyond a segment boundary. ABAP does not have one large
address space, but rather a set of segments. Each of the following has its own segment:
All global data
All local data
Each table work area (TABLES)
Each COMMON PART
You should only let field symbols move within an elementary field or structure where ABAP allows
you to assign both within the global data and beyond a field boundary.
Field symbols can also cause type violations in ABAP, that is, a field symbol points to the wrong
address event though it is within the field boundaries. An example of this is using offset and length
for a packed field.

(C) SAP AG BC411 4-13


Summary

Field symbols allow you to


Assign an alias to a data object
Set the offset and length for a string at
runtime
Set a pointer to a data object that you
determine at runtime (dynamic ASSIGN)
Adopt the type of a field at runtime or
change the type of a field symbol
Access components of a structure

© SAP AG

(C) SAP AG BC411 4-14


Internal Tables: Contents

Definitive attributes of internal tables


Hierarchy of table types
Defining internal tables
Internal table operations
Internal tables with and without header lines

© SAP AG
Unit Objectives

At the end of this unit, you will be able to


List the attributes that determine the type of an
internal table
Decide which type of internal table is the most
appropriate in a given situation
Define an internal table
Work with an internal table
Explain the difference between internal tables
with and without header lines

© SAP AG

(C) SAP AG BC411 5-2


Internal Tables
ABAP
Data type

Predefined User-defined
(P,I,F,C,N,D,T,X,REF TO)

Elementary Structured

Struct.Fld type Table type Class/Interface

Dynamic
table
extension !!!

Array Chained list


© SAP AG

Internal tables, like structured fields, are structured data types. An internal table consists of any
number of lines, all of which have the same type. Internal tables are comparable with the array
concepts of other programming languages. If you insert or delete lines in an internal table, the
system updates the link from each line to its new successor, just like in a chained list. The best way
to regard internal tables is as an area of memory occupied by similar data.
Unlike arrays in other programming languages, internal tables are extended dynamically at runtime
by the ABAP runtime environment.
There are two kinds of table structures - flat tables, whose structure contains no other tables or
references, and deep tables, whose structure contains other internal tables or references. Similarly,
we refer to the lines of an internal table as either flat or structured.

(C) SAP AG BC411 5-3


Internal Table Attributes

CARRID CONNID DISTANCE Line type


Key sequence
AA 0017 2,572
LH 0400 6,162
LH 0400 6,162 Uniqueness attribute
QF 0005 10,000 Index access
SQ 0866 1,625 5
Table type
UA 0007 2,572 UA 0007

Key access

© SAP AG

The data type of an internal table is fully specified by its:


Line type
The line type of an internal table can be any ABAP data type.
Key sequence
The key fields and their sequence determine the criteria by which the system identifies table lines.
Uniqueness attribute
You can define the key of an internal table as either UNIQUE or NON-UNIQUE. If the key is
unique, there can be no duplicate entries in the table. The uniqueness attribute depends largely on the
table type (see below).
Table type
The table type defines how ABAP access individual table lines. This can be either by table index or
by key.
Example of access using table index:
READ TABLE itab INDEX 5.
Example of access using key:
READ TABLE itab WITH TABLE KEY carrid = 'UA'.

(C) SAP AG BC411 5-4


Table Types
ANY TABLE

INDEX TABLE HASHED TABLE

STANDARD TABLE SORTED TABLE

Key access Table scan Binary Hash


search function

Access costs linear increase logarithmic increase constant


with n entries (O(n)) (O(log(n)) (O(1))

Access using n
R
Mainly index Mainly key Only key

Unique or not NON-UNIQUE UNIQUE | NON-UNIQUE UNIQUE


© SAP AG

The table type defines how ABAP accesses individual table lines. There are three types of internal
tables:
Standard tables. In a standard table, you can access data using either the table index or the key. If
you use the key, the response time is in linear relation to the number of table entries. The key of a
standard table is always non-unique.
Sorted tables. Sorted tables are always stored correctly sorted according to their key. You can
access them using either the table index or the key. If you use the key, the response time is in
logarithmic relation to the number of table entries, since the system uses a binary search to access
the table. The key of a sorted table can be either unique or non-unique.
Standard tables and sorted tables are generically known as index tables.
Hashed tables. You can only access a hashed table using its key - neither explicit nor implicit index
operations are allowed. The response time is constant, regardless of the number of table entries. The
hash algorithm is administered internally. The key of a hashed table must be unique.
At runtime, you can find out the type of an internal table <itab> using the statement
DESCRIBE TABLE <itab> KIND <k>.

(C) SAP AG BC411 5-5


Response Times ...

Example: Both tables have n entries


LOOP
LOOP AT
AT OuterTable
OuterTable INTO
INTO OuterWa.
OuterWa.
...
...
READ
READ TABLE
TABLE InnerTable
InnerTable INTO
INTO InnerWa
InnerWa WITH
WITH TABLE
TABLE KEY
KEY ...
...
...
...
ENDLOOP.
ENDLOOP.

Standard table: Increases quadratically, O(n2)

double n runtime increases fourfold


Sorted table: Increases logarithmically, O(n log2n)
double n runtime increases by factor 2 + 2/log2n
Hashed table: Increases constantly, O(n)
double n runtime doubles
R

© SAP AG

The above example processes two internal tables.


The outer table is processed sequentially, and for each entry in it, the system reads a single entry
from the inner table.
With a standard table, the inner table is searched sequentially (full table scan) for each pass of the
outer table. The response times increase quadratically with the number of entries.
With a sorted table, the response time for the inner table is logarithmic. This reduces the total
response time to a factor of 2.2 to 2.3 when the number of table entries is doubled.
With a hashed table, every table access has a constant response time. This reduces the runtime even
further.

(C) SAP AG BC411 5-6


Access Times
Loop costs for each internal table type

6
Time in microseconds

+0
1E
5
+0
1E
0
00
10
00
10
0
10 10 1

5 10 20 40 80 160 320 640 1280

Number of table entries: n


5 10 20 40 80 160 320 640 1280
Standard 52 121 335 1,081 3,887 14,999 59,700 238,214 951,704
Sorted 44 87 177 391 862 1,895 4,048 8,587 18,136
Hashed 41 78 151 305 613 1,249 2,497 5,080 10,537 R

© SAP AG

The above statistics show how the new table types can dramatically reduce access times to internal
tables.
Tests have shown that the runtime of programs similar to those on the previous page can be reduced
from around 8 hours to a few minutes by converting standard tables into sorted tables.

(C) SAP AG BC411 5-7


Defining Internal Tables
CARRID CONNID DISTANCE
TYPES: <itabtype> TYPE <itabkind>
of <linetype>
[WITH [UNIQUE | NON-UNIQUE] <keydef> ]
[INITIAL SIZE <n>]. AA 0017 2,572
LH 0400 6,162
DATA: <itab> TYPE <itabkind> of <linetype> LH 0400 6,162
WITH [UNIQUE | NON-UNIQUE] <keydef> QF 0005 10,000
[INITIAL SIZE <n>] SQ 0866 1,625
UA 0007 2,572
[WITH HEADER LINE].
<itabkind>
[STANDARD] TABLE | SORTED TABLE | HASHED TABLE
additionally, for types: INDEX TABLE | ANY TABLE

<keydef>
KEY <f1> ... <fn> |
KEY TABLE LINE |
DEFAULT KEY

© SAP AG

The statement
TYPES <itabtype> TYPE <tabkind> OF <linetype>
[WITH [UNIQUE | NON-UNIQUE] <keydef>] [INITIAL SIZE <n>]
creates a data type with type <itabtype>, table type <tabkind>, and line type <linetype>.
Normally, you also specify a user-defined key in the form <f1> … <fn>. All of the fields in the
key must have a flat structure. If the line type is not structured, you can use the addition KEY
TABLE LINE to designate the entire line as the key. The addition DEFAULT KEY allows you to
set the standard key as used in internal tables before Release 4.0.
You can use the UNIQUE or NON-UNIQUE addition to specify whether the table should be allowed
to contain entries with duplicate keys.
If you know that your internal table will be smaller than 8KB, you can use the INITIAL SIZE
<n> addition to reserve its initial memory space. The value <n> has no effect on the type check.
Unlike other user-defined ABAP data types, you do not have to specify the data type of an internal
table fully. Instead, you can use the generic types INDEX TABLE and ANY TABLE. These types
are useful for specifying the types of parameters in subroutines.

(C) SAP AG BC411 5-8


Internal Tables in Memory (1)
Table header
DATA:itab TYPE TABLE OF struc. Fixed size: 256 bytes

•Dynamic data structure


•Empty table occupies 256 bytes (header) R

© SAP AG

(C) SAP AG BC411 5-9


Internal Tables in Memory (2)
Table header
DATA:itab TYPE TABLE OF struc. Fixed size: 256 bytes

Table body (line width, e.g. 8 bytes)


APPEND wa TO itab. " 1. Eintrag 1 1st page:
2
m entries (e.g.16)

•Dynamic data structure


•An empty table occupies 256 bytes (header) R

•Maximum line length is 64K


© SAP AG

(C) SAP AG BC411 5-10


Internal Tables in Memory (3)
Table header
DATA:itab TYPE TABLE OF struc. Fixed size: 256 bytes

Table body (line width, e.g. 8 bytes)


APPEND wa TO itab. " 1st entry 1
2 1st page:
APPEND wa TO itab. " 2nd entry
m entries (e.g.16)

•Dynamic data structure


•Empty table occupies 256 bytes (header) R

•Maximum line length is 64K


© SAP AG

(C) SAP AG BC411 5-11


Internal Tables in Memory (4)
Table header
DATA:itab TYPE TABLE OF struc. Fixed size: 256 bytes

Table body (line width, e.g. 8 bytes)


APPEND wa TO itab. " 1st entry 1
2 1st page:
APPEND wa TO itab. " 2nd entry
m entries (e.g.16)

m+1 2nd page:


APPEND wa TO itab. " m+1th entry
2m entries (e.g.32)

•Dynamic data structure


•Empty table occupies 256 bytes (header) R

•Maximum line length 64K


© SAP AG

(C) SAP AG BC411 5-12


Internal Tables in Memory (5)
Table header
DATA:itab TYPE TABLE OF struc. Fixed size: 256 bytes

Table body (line width, e.g. 8 bytes)


APPEND wa TO itab. " 1st entry 1
2 1st page:
APPEND wa TO itab. " 2nd entry
m entries (e.g.16)

m+1 2nd page:


APPEND wa TO itab. " m+1th entry
2m entries (e.g.32)

3m+1 3rd page:


APPEND wa TO itab. " 3m+1th entry M enrties (e.g.1024)

•Dynamic data structure


•Empty table occupies 256 bytes (header) R

•Maximum line length is 64K


© SAP AG

(C) SAP AG BC411 5-13


Internal Tables in Memory (6)
Table header
DATA:itab TYPE TABLE OF struc. Fixed size: 256 bytes

Table body (line width e.g. 8 bytes)


APPEND wa TO itab. " 1st entry 1
2 1st page:
APPEND wa TO itab. " 2nd entry
m entries (e.g.16)

m+1 2nd page:


APPEND wa TO itab. " m+1th entry
2m entries (e.g. 32)

3m+1 3rd page:


APPEND wa TO itab. " 3m+1th entry M entries (e.g. 1024)
8-16 KB

4m+1 4th page:


•Dynamic data structure M entries
(e.g.1024)
•Empty table occupies 256 bytes (header)
8-16 KB
R

•Maximum line length is 64 KB


© SAP AG

When you define an internal table, the header information occupies 256 bytes.
When you add the first entry, the system creates a page of memory. The size of the page depends on
the width of the line type. The first page might typically contain 16 table entries.
When you add the (m+1)th entry, the system requests another page of memory, which can typically
store 2m entries.
Initially, the memory use increases moderately.
It is only with the third page that the memory usage starts to increase considerably. The extra
requirement for each subsequent page remains constant after this.

(C) SAP AG BC411 5-14


Special Internal Table Operations

Work area <wa>

APPEND ... <itab>.


COLLECT ... <itab>. Internal table <itab> LOOP AT <itab>. ENDLOOP.
INSERT ... <itab>. READ TABLE <itab> ... .
CARRID CONNID
MODIFY <itab> ... .
DELETE <itab> ... . AA 0017
LH 0400

SORT <itab> BY <field1> ... <fieldn>.


REFRESH <itab>.
FREE <itab>.

© SAP AG

Internal tables in ABAP differ from the array concepts of other programming languages in that you
do not directly access actual lines within the table. Instead, you use a separate work area. From
Release 4.5A, it will be possible to work directly with a table line using the statements
LOOP AT <itab> ASSIGNING <fs> or READ TABLE <itab> ASSIGNING <fs>,
where <fs> is a field symbol. For further information about this technique, refer to appendix A.
ABAP contains the following operations for internal tables:
Statement Effect
APPEND Appends the contents of the work area to the end of the internal table
COLLECT Cumulates the contents of the work area in the internal table
INSERT Inserts the work area in a particular line of the internal table
MODIFY Overwrites a particular line of the internal table with the contents of the work area
DELETE Deletes a particular line from the internal table
LOOP AT Places the lines of the internal table one by one in a work area
READ TABLE Places a single line of an internal table into a work area
SORT Sorts the internal table
REFRESH Deletes the internal table
FREE Deletes the internal table and releases all of the resources used by it

(C) SAP AG BC411 5-15


Operations on all Data Objects
MOVE <dataobject1> TO <dataobject2>.
IF <dataobject1> = <dataobject2>. ... . ENDIF.
CLEAR <dataobject>.
ASSIGN <dataobject> TO <fs>.
EXPORT <dataobject> TO MEMORY | DATABASE ... .
IMPORT <dataobject> TO MEMORY | DATABASE ... .

TYPES: BEGIN OF line_type,


f1 TYPE c,
f2 LIKE TABLE OF sflight-carrid,
END OF line_type.
DATA: itab1 TYPE TABLE OF line_type,
itab2 TYPE TABLE OF line_type.

MOVE itab1 TO itab2.


IF itab1 = itab2.
WRITE / 'Tables are the same'.
ENDIF.
CLEAR: itab1, itab2.
R

© SAP AG

As well as the statements that apply exclusively to internal tables, there are also the following that
apply to all data objects (including internal tables):
MOVE Assigns the contents of a data object to another data object
IF Compares the contents of one data object with those of another data object
CLEAR Deletes the contents of a data object
ASSIGN Assigns a data object to a field symbol
EXPORT Writes a data object to a cluster database or ABAP memory
IMPORT Reads a data object from a cluster database or ABAP memory
Passing parameters to and from subroutines, function modules, and methods.
Note that embedded (deep) structures in internal tables are included in MOVE, IF, CLEAR, and
IMPORT/EXPORT operations. This also applies to the FREE and REFRESH statements, but not for
the SORT statement (no deep SORT).

(C) SAP AG BC411 5-16


Index Access Using Read
TYPES: BEGIN OF line_type,
f1, f2,
END OF line_type.
DATA: stand_tab TYPE STANDARD TABLE OF line_type WITH KEY f1,
wa TYPE line_type.

READ TABLE stand_tab INDEX 2 INTO wa.

Work area wa

b 1

Internal table stand_tab


f1 f2
a 1
2 b 1

© SAP AG

The above example defines a standard table stand_tab. Each line consists of two fields f1 and f2,
each of which has type C and length 1. The key consists of field f1. The work area wa is also
required for internal table operations.
The READ statement reads the second line of the standard table stand_tab and places it in the
work area wa.
Note: You cannot access a hashed table using an index.

(C) SAP AG BC411 5-17


Index Operations on Internal Tables
Single record processing Mass processing
n

Read READ TABLE <itab> LOOP AT <itab>


INDEX <n> [FROM <n1>] [TO <n2>]
[INTO <wa>]. [INTO <wa>].
ENDLOOP.

APPEND [<wa> TO] <itab>. APPEND LINES OF <itab1>


Append
[FROM <n1>] [TO n2] TO <itab2>.

INSERT [<wa INTO] <itab> INSERT LINES OF <itab1>


Insert
[INDEX <n>]. [FROM <n1>] [TO <n2>]
INTO <itab2> [INDEX <n3>].

MODIFY <itab> [INDEX <n>]


Change [FROM <wa>].
Delete
DELETE <itab> DELETE <itab>
[INDEX <n>]. FROM <n1> TO <n2>.

© SAP AG

Internal table operations can be classified as follows:


By their access method as index operations or key operations.
By the scope of their access as single record processing or mass processing. Single record
processing accesses one line in each operation, mass processing accesses n lines.
By the operation type, as Read, Append, Insert, Change, or Delete.
ABAP contains the following index operations: Note, again, that index operations are not allowed
on hashed tables.
READ TABLE <itab> INDEX <n> INTO <wa>.
Reads the contents of the <n>th line of <itab> into the work area <wa>.
APPEND <wa> TO <itab>.
Appends the contents of <wa> to the end of <itab>.
INSERT <wa> INTO <itab> INDEX <n>.
Inserts the contents of <wa> into the table before line <n>.
MODIFY <itab> INDEX <n> FROM <wa>.
Overwrites the <n>th line of <itab> with the contents of <wa>.
DELETE <itab> INDEX <n>.
Deletes the <n>th line of <itab>.

(C) SAP AG BC411 5-18


Linear Index (1)
Table header
DELETE itab INDEX 2. Fixed size: 256 bytes

Table body (line width, e.g. 8 bytes)


Linear index 1
2 1st page:
2 1 1
2 3 m entries (e.g.16)
3 4
4 5
m+1 2nd page:
2m entries (e.g.32)

3m+1 3rd page:


M entries (e.g.1024)
8-16 KB

4th page:
M entries
(e.g.1024)
8-16 KB
R

© SAP AG

(C) SAP AG BC411 5-19


Linear Index (2)
Table header
DELETE itab INDEX 2. Fixed size: 256 bytes
DELETE itab INDEX 51.
Table body (line width, e.g. 8 bytes)
Linear index 1
2 1st page:
2 1 1
51 2 3 m entries (e.g.16)
3 4
4 5
m+1 2nd page:
2m entries (e.g.32)
50
52
3m+1 3rd page:
M entries (e.g.1024)
8-16 KB

4th page:
M entries
(e.g.1024)
8-16 KB
R

© SAP AG

(C) SAP AG BC411 5-20


Linear Index (3)
Table header
DELETE itab INDEX 2. Fixed size: 256 bytes
DELETE itab INDEX 51.
INSERT wa INTO itab Table body (line width, e.g. 8 bytes)
Linear index 1
2 1st page:
INDEX 3. 51 1 1
2 3 m entries (e.g.16)
3 2
4 4
5 m+1 2nd page:
2m entries (e.g.32)
50
52
3m+1 3rd page:
M entries (e.g.1024)
8-16 KB

4th page:
M entries
(e.g.1024)
8-16 KB
R

© SAP AG

The DELETE, SORT, and INSERT statements force the system to construct a linear index.
Deleted entries are kept in a free list.
When you delete entries, gaps occur in the body of the table. The index, on the other hand, has no
gaps, because the system closes them.
The cost of closing the index gaps becomes evident in tables of 5000 entries or more.

(C) SAP AG BC411 5-21


Accessing a Single Generic Entry with READ
TYPES: BEGIN OF line_type,
f1, f2,
END OF line_type.
DATA: stand_tab TYPE STANDARD TABLE OF line_type WITH KEY f1,
wa type line_type.

wa-f1 = 'b'. wa-f2 = '5'.


READ TABLE stand_tab FROM wa INTO wa. "implicity from wa
READ TABLE stand_tab WITH TABLE KEY f1 = 'b' INTO wa. "explicitly
Work area wa
b 5
b 1

Internal table stan_tab

f1 f2

A 1
b 1
R

© SAP AG

If you use a key to access and internal table, you can either pass the key values implicitly in a work
area, or explicitly using the additions
WITH KEY <f1> = <v1> ... AND <fn> = <vn> or
WITH TABLE KEY <f1> = <v1> ... <fn> = <vn>.
In the second case, <f1> … <fn> must be key fields of the table.
The READ variants "FROM <wa>" and "WITH TABLE KEY…", new in Release 4.0, are generic,
that is, valid for all table types. The access is optimized according to the table type. The cost of the
READ statement is linear for standard tables, logarithmic for sorted tables, and constant for hashed
tables.
If TABLE occurs before KEY in the new READ variants, the system optimizes the access, but you
must supply values for all of the key fields of the table.
To specify fields that differ from the table key, use the WITH KEY addition (note: no TABLE in
the addition). This is not internally optimized.
If you use WITH KEY to access a hashed table, the cost is no longer constant, but linear.
The exception to the general rule for WITH KEY is that the access is internally optimized for sorted
tables where the specified key is a left-justified extract of the beginning of the table key.

(C) SAP AG BC411 5-22


Generic Key Operations
Single record processing Mass processing
Implicit (from <wa>) explicit
READ TABLE <itab> READ TABLE <itab> LOOP AT <itab>
Read [INTO <itab_wa>] [INTO <wa>] [INTO <wa>]
FROM <wa>. WITH [TABLE] KEY WHERE <condition>.
<k> = <v>.
Insert
INSERT [<wa> INTO] INSERT LINES
TABLE <itab>. OF <itab1>
INTO TABLE <itab2>.
Cumulate
COLLECT [<wa> INTO]
<itab>.
Change
MODIFY TABLE <itab> MODIFY <itab>
[FROM <wa>]. [FROM <wa>]
Delete WHERE <condition>.
DELETE TABLE <itab> DELETE TABLE <itab> DELETE <itab>
[FROM <wa>]. WITH TABLE KEY WHERE <condition>.
<k> = <v>. R

© SAP AG

The parts of the syntax used to identify lines are italicized in the above table. These are either work
areas from which the key values are read (implicit key access), or implicit key specifications using
the WITH [TABLE] KEY addition.
If you try to insert a single duplicate entry into an internal table with unique key, the insertion fails,
and SY-SUBRC is set to 4. This allows you to filter out duplicates from a set of entries very easily.
If you try to insert duplicates during mass processing, a runtime error occurs.
This overview is further illustrated by examples on the following pages.

(C) SAP AG BC411 5-23


Operations on Standard Tables (Example)
TYPES: <itabtype> TYPE [STANDARD] TABLE of <linetype>
[WITH [NON-UNIQUE] <keydef>]
[INITIAL SIZE <n>].

REPORT sapbc411_standard_tab.
TYPES: BEGIN OF line_type,
f1, f2,
END OF line_type.
DATA: stand_tab TYPE STANDARD TABLE OF line_type WITH KEY f1,
wa TYPE line_type.

wa-f1 = 'a'. wa-f2 = '1'. APPEND wa TO stand_tab.


tabix = sy-tabix + 1. wa = 'c1'. INSERT wa INTO stand_tab INDEX tabix.
wa-f1 = 'b'. wa-f2 = '1'. INSERT wa INTO TABLE stand_tab.
wa-f1 = 'b'. wa-f2 = '2'. INSERT wa INTO TABLE stand_tab.
wa-f1 = 'b'. wa-f2 = '2'. MODIFY TABLE stand_tab FROM wa.
wa-f1 = 'a'. DELETE TABLE stand_tab FROM wa.
READ TABLE stand_tab INTO wa INDEX 1. WRITE wa-f1, wa-f2.
LOOP AT stand_tab INTO wa. WRITE wa-f1, wa-f2. ENDLOOP.
R

SORT stand_tab by f2.

© SAP AG

The above example processes the following operations using the data objects stand_tab and wa:
Appends the contents of wa ('a1') to the end of stand_tab. The index of the insertion point is
placed in SY-TABIX and is 1 in the example.
Inserts the contents of wa ('c1') in stand_tab at the position SY-TABIX + 1. This is position
2. The APPEND statement would, of course, have had the same effect.
Appends the contents of wa ('b1') to the end of stand_tab. A generic INSERT in a standard
table has the same effect as the APPEND statement.
Appends the contents of wa ('b2') to the end of stand_tab. This statement leads to a duplicate
key ('b'), since standard tables always have a non-unique key.
Finds the first entry corresponding to the key of wa ('b') and changes it to b2.
Deletes the first entry it finds corresponding to the key of wa ('a').
Reads the first entry from the internal table.
Displays all of the entries.
Sorts stand_tab according to field f2.

(C) SAP AG BC411 5-24


Internal Tables With and Without Header Line
Work area <wa> Header line <itab>

Internal table <itab> Internal table <itab>


CARRID CONNID CARRID CONNID
AA 0017 AA 0017
LH 0400 LH 0400

APPEND <wa> TO <itab>. APPEND <itab>.


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

READ TABLE <itab> INDEX <n> READ TABLE <itab> INDEX <n>.
INTO <wa>.
LOOP AT <itab> INTO <wa>. LOOP AT <itab>.
WRITE <wa>-<f>. WRITE <itab>-<f>.
ENDLOOP. ENDLOOP.
R

Clear syntax Short syntax


© SAP AG

You can define internal tables either with or without header lines. An internal table with header line
is a composite of a work area (the header line) and the body of the table, both of which are addressed
using the same name. The way in which the system interprets the name depends on the context. For
example, the MOVE statement applies to the header line, but the SEARCH statement applies to the
body of the table.
To avoid confusion, you are recommended to use internal tables without header lines. However,
internal tables with header line do offer a shorter syntax in several statements (APPEND,
INSERT, MODIFY, COLLECT, DELETE, READ, LOOP).
You can always address the body of an internal table itab using the syntax itab[], regardless of
whether itab has a header line or not.
Example:
DATA: itab1 TYPE TABLE OF i WITH HEADER LINE.
DATA: itab2 TYPE TABLE OF i WITH HEADER LINE.

itab1 = itab2 "Copies only the header lines.


itab1[] = itab2[] "Copies the contents of the entire table.

(C) SAP AG BC411 5-25


Declaring an Internal Table With Header Line
DATA: <itab> TYPE <itabkind> OF <linetype>
WITH [UNIQUE | NON-UNIQUE] <keydef>
[INITIAL SIZE <n>]
[WITH HEADER LINE].
REPORT sapbc411_standard_tab.
TYPES: BEGIN OF line_type,
f1, f2,
END OF line_type.
DATA: stand_tab TYPE STANDARD TABLE OF line_type
WITH KEY f1 WITH HEADER LINE,
wa TYPE line_type.
stand_tab = 'a1'. APPEND wa TO stand_tab.
tabix = sy-tabix + 1.
stand_tab = 'c1'. INSERT wa INTO stand_tab INDEX tabix.
stand_tab = 'b1'. INSERT wa INTO TABLE stand_tab.
stand_tab = 'b2'. INSERT wa INTO TABLE stand_tab.
stand_tab = 'b2'. MODIFY TABLE stand_tab FROM wa.
stand_tab = 'a1'. DELETE TABLE stand_tab FROM wa.
READ TABLE stand_tab INDEX 1 INTO wa. WRITE wa-f1, wa-f2.
R

SORT stand_tab.

© SAP AG

To define an internal table with a header line, use the addition WITH HEADER LINE.
In the above examples, the crossed-out code indicates the syntax required for an internal table
without a header line (where you would need the work area wa).

(C) SAP AG BC411 5-26


Sorted Table (Example)
DATA: <itabtype> TYPE SORTED TABLE of <linetype>
[WITH [UNIQUE | NON-UNIQUE] <keydef>]
[INITIAL SIZE <n>] [WITH HEADER LINE].

REPORT sapbc411_sorted_tab.
TYPES: BEGIN OF line_type,
f1, f2,
END OF line_type.
DATA: sorted_tab TYPE SORTED TABLE OF line_type
WITH UNIQUE KEY f1,
wa TYPE line_type.

wa-f1 = 'a'. wa-f2 = '1'. INSERT wa INTO TABLE sorted_tab.


wa-f1 = 'b'. wa-f2 = '1'. INSERT wa INTO TABLE sorted_tab.
wa-f1 = 'b'. wa-f2 = '2'. INSERT wa INTO TABLE sorted_tab.
wa-f1 = 'b'. wa-f2 = '2'. MODIFY TABLE sorted_tab FROM wa.
wa-f1 = 'b'. DELETE TABLE sorted_tab FROM wa.
READ TABLE sorted_tab INTO wa INDEX 1. WRITE wa-f1, wa-f2.
LOOP AT sorted_tab INTO wa. WRITE wa-f1, wa-f2. ENDLOOP.
R

© SAP AG

The above example processes the following operations using the data objects sorted_tab and wa:
Inserts the contents of wa ('a1') into sorted_tab.
Inserts the contents of wa ('b1') into sorted_tab.
Inserts the contents of wa ('b2') into sorted_tab. This insertion would lead to a
duplicate key ('b'). Since sorted_tab is defined with a unique key, SY-SUBRC <> 0.
Finds the first entry corresponding to the key of wa ('b') and changes it to 'b2'.
Deletes the first entry corresponding to the key of wa ('b').
Reads the first line of the table and places it in wa.
Displays all of the entries.
You can use INSERT … INDEX and APPEND for sorted tables, since the system only checks
whether the sort sequence is violated or not. If your table entries are already correctly sorted before
you insert them in the table, you can use these statements to bypass the normal binary search for the
correct insertion point.
You cannot explicitly sort a sorted table using the SORT statement.

(C) SAP AG BC411 5-27


Partial Sequential Processing: Sorted Tables
REPORT sapbc411_partseq_loop.
TYPES: BEGIN OF line_type,
f1, f2, f3, f4,
END OF line_type.
DATA: sorted_tab TYPE SORTED TABLE OF line_type
WITH NON-UNIQUE KEY f1 f2 f3,
wa TYPE line_type.
*... Fill sorted_tab with non-unique values ...

LOOP AT sorted_tab INTO wa


WHERE f1 = 'X' AND f2 = 'Y'. "optimized
....
ENDLOOP.

LOOP AT sorted_tab INTO wa


WHERE f1 = 'X' AND f3 = 'Z'. "not optimized
....
ENDLOOP.

© SAP AG

In partial sequential processing for sorted tables, you process optimized loops (that is, only the lines
that fulfil the WHERE condition are processed). The WHERE condition must have the following
form: WHERE k1 = v1 AND k2 = v2 AND … AND kn = vn, and the components k1 to kn
must be an extract of the beginning of the table key. In the second example above, the WHERE
condition only contains the key fields f1 and f3. Since f2 is missing, this is not a genuine extract of
the beginning of the key.
The same applies to the READ statement for sorted tables.

(C) SAP AG BC411 5-28


Hashed Tables (Example)
TYPES: <itabtype> TYPE HASHED TABLE of <linetype>
[WITH UNIQUE <keydef>]
[INITIAL SIZE <n>].

REPORT sapbc411_hashed_tab.
TYPES: BEGIN OF line_type,
f1, f2,
END OF line_type.
DATA: hashed_tab TYPE HASHED TABLE OF line_type
WITH UNIQUE KEY f1,
wa TYPE line_type.

wa-f1 = 'a'. wa-f2 = '1'. INSERT wa INTO TABLE hashed_tab.


wa-f1 = 'b'. wa-f2 = '1'. INSERT wa INTO TABLE hashed_tab.
wa-f1 = 'b'. wa-f2 = '2'. INSERT wa INTO TABLE hashed_tab.
wa-f1 = 'b'. wa-f2 = '2'. MODIFY TABLE hashed_tab FROM wa.
wa-f1 = 'b'. DELETE TABLE hashed_tab FROM wa.
LOOP AT hashed_tab INTO wa.
WRITE wa-f1, wa-f2. R

ENDLOOP.
SORT hashed_tab.
© SAP AG

The above example processes the following operations using the data objects hashed_tab and wa:
Inserts the contents of wa ('a1') into hashed_tab.
Inserts the contents of wa ('b1') into hashed_tab.
Inserts the contents of wa ('b2') into hashed tab. This would lead to duplicate key
('b'), and so SY-SUBRC <> 0, since hashed tables always have a unique key.
Finds the first entry corresponding to the key of wa ('b') and changes it to 'b2'.
Deletes the first entry corresponding to the key of wa ('b').
Displays all entries.
Sorts hashed_tab by the key of the internal table, that is, field f1 (hashed tables can be
sorted).
Note that you cannot use any index operations (APPEND, INSERT …. INDEX) on hashed tables.

(C) SAP AG BC411 5-29


Filling an Internal Table with Cumulative Values

COLLECT [<wa> INTO] <itab>. REPORT sapbc411d_collect_itab.

CARRID PRICE (TYPE P) TYPES: BEGIN OF flightinfo_type,


LH 100000 wa carrid LIKE sflight-carrid,
price LIKE sflight-price,
AA 2090938 1 END OF flightinfo_type.
DL 933338 2 DATA: flightinfo_list TYPE HASHED TABLE OF
LH 1766669 3 1866669 flightinfo_type WITH UNIQUE KEY carrid
4 connid,
wa TYPE flightinfo_type.
5
6 SELECT carrid price FROM sflight INTO wa.
COLLECT wa INTO flightinfo_list.
7 ENDSELECT.
8

© SAP AG

The COLLECT statement adds the work area or header line to an internal entry with the same type
or, if there is none, adds a new entry to the table.
It searches for the entry according to the table type and defined key. If it finds an entry in the table, it
adds all numeric fields that are not part of the key to the existing values. If there is not already an
entry in the table, it appends the contents of the work area or header line to the end of the table.
You can only use the COLLECT statement with internal tables whose non-key fields are all numeric
(type I, P, or F). The statement is optimized for standard tables so that the response time is constant.
However, this only applies if you only use the COLLECT statement to change the table contents, and
not DELETE, INSERT or SORT. If you do use the latter statements, the cost of the COLLECT
statement is linear.
With hashed tables, the cost of the COLLECT statement is constant, even if you do use DELETE,
INSERT or SORT.
From Release 4.0A, the table key may contain numeric fields.

(C) SAP AG BC411 5-30


Summary of Internal Table Operations
Standard table Sorted table Hashed table

O(n) O(log n) O(1)


INSERT Same as append Inserts in correct sort order Same as append

COLLECT O(1) bis O(n)

MODIFY
DELETE
READ But LOOP always
LOOP uses a full table scan
n O(1) O(1) O(1)

INSERT Possible sort


APPEND order violation
No index
MODIFY operations on
hashed tables
DELETE
READ
LOOP R

SORT See above


© SAP AG

You can access any type of internal table using the key. However, there is a performance difference
(O(n), O(log(n), O(1)). INSERT for a standard table or hashed table using the key has the same
effect as the APPEND statement.
INSERT using an index and APPEND are both dangerous with sorted tables, since you may violate
the sort sequence. They are syntactically invalid for hashed tables (no index operations allowed).
You cannot use any index operations with hashed tables (APPEND, INSERT … INDEX, LOOP
…FROM… TO).
You can use SORT for standard tables and hashed tables. It has no positive effect in a sorted table,
and can lead to a syntax or runtime error if the attempted sort violates the key sequence.
You can use control level processing with all table types. Hashed and standard tables must be sorted
beforehand.

(C) SAP AG BC411 5-31


Standard Table Definitions (History)
DATA: BEGIN OF <itab> OCCURS <n>,
Release 2.2
<f1>, ..., <fn>,
END OF <itab>.

TYPES: BEGIN OF <line_type>,


<f1>, ..., <fn>,
END OF <line_type>.
Release 3.0
DATA: <itab> TYPE <line_type>
OCCURS <n>
WITH HEADER LINE.

TYPES: BEGIN OF <line_type>,


<f1>, ..., <fn>,
END OF <line_type>.
DATA: <itab> TYPE TABLE OF <line_type>
WITH HEADER LINE.
Release 4.0
TYPES: BEGIN OF <line_type>,
<f1>, ..., <fn>,
END OF <line_type>.
DATA: <itab> TYPE STANDARD TABLE OF <line_type> R

WITH DEFAULT KEY INITIAL SIZE <n>


WITH HEADER LINE.
© SAP AG

The R/3 System also contains other ways of defining internal tables. However, these have been
retained to ensure compatibility with Releases 2.2 and 3.0, and should not be used in Release 4.0.
In Release 2.2, only standard tables with header line were allowed. The line type was specified
between BEGIN of <itab> OCCURS <n> and END OF <itab>. OCCURS <n> had two
meanings: Firstly, it specified the initial size of the table, secondly, it was the addition that identified
the data object as an internal table. The implicit key of this kind of internal table consisted of all
elementary non-numeric fields. The only attribute that determined the table type was the line type.
Caution: This syntax still occurs very frequently in ABAP programs. Remember that it defines a
standard table with header line and an implicitly-defined key.
Release 3.0 saw the introduction of the ABAP type concept. For internal tables, this meant that:
The line type could be defined separately and referenced in the definition of the internal table
itself.
You could define an internal table as a type.
From Release 3.0 onwards, it was also no longer necessary to work with a header line.
From Release 4.0, the type of an internal table consists of a freely-definable key, the uniqueness
attribute, and the table type, as well as the line type.

(C) SAP AG BC411 5-32


Summary

The attributes of an internal table that constitute its


type are the line type, key field sequence,
uniqueness attribute, and table type.
Standard tables are particularly suitable for index
acces. Sorted tables provide good performance if
you use a key, and also allow you to use an index.
Hashed tables provide excellent performance if you
specify the entire key of an entry, but index access
is not allowed.
A header line is a work area belonging to an
internal table. You address it using the same name
as the body of the table.

© SAP AG

Appendix A contains further information about internal tables, extracts, and how to access table
entries directly without using a header line or work area.

(C) SAP AG BC411 5-33


Object-Oriented Programming with ABAP
Objects: Contents
What are objects?
Advantages of object-oriented
programming
From function groups to objects
Classes and objects
What is ABAP Objects?
Classes
Attributes
Reference variables and object instances
Defining and implementing methods
Defining and implementing interfaces
R

Triggering and handling events


© SAP AG
Objectives

At the end of this unit, you will be able to:


Position ABAP Objects within the overall
structure of the ABAP language
Understand and use the basic techniques
of object-oriented programming using
ABAP Objects

© SAP AG

(C) SAP AG BC411 6-2


What are Objects?
Functions and Data Objects Real World: Objects

Data Data Data


Method
Data Method
Data
Data
Object Method
attributes

Encapsulation Abstraction

Function
Method
Data Method
Function Function Function
Method

Function Function Function Function

© SAP AG

Information systems have traditionally been defined through their functions. Functions and data were
always kept apart, and linked using input/output relationships.
At the centre of object-oriented methods are objects. Objects represent abstract or concrete aspects of
the real world. Their nature and properties are described by their structure and their attributes (data),
and their behavior is described in a set of methods (functions).
Objects provide a single shell encompassing both their nature and their behavior. Using objects, you
can establish a one-to-one relationship between a real-life problem and its software solution.
Typical objects in a business environment are 'customer', 'order', and 'invoice'. The R/3 System has
implemented objects of this type since Release 3.1 in the Business Object Repository (BOR). It is
intended to integrate the object model of the BOR into ABAP Objects.

(C) SAP AG BC411 6-3


Objects

Interface

Object Public
attributes
attributes
Flight
Airline
Address Flight number
Public
Private Customer
access
access Passenger Methods
list
BOOK

Events

© SAP AG

An object has two layers:


Public components: These are any components (attributes, methods, and events) that can be
seen and directly addressed by users. The public components of an object form its point of
contact with external users.
Private components: There are any components (attributes, methods, and events) that are only
visible within the object itself.
The aim is for objects to be able to ensure their own consistency. Most of an object's data is therefore
internal, that is, declared as private data. Private attributes of an object can only be changed by
methods of the same object. As a rule, the only public components are methods, which work with the
data in the object and ensure that it is consistent.
Objects also have a unique ID to distinguish them from other objects that have the same attributes
and methods.

(C) SAP AG BC411 6-4


Encapsulation

Object: Flight

Attribute:
Program:... Method:
passenger book
Read table passenger

No access

Program:...
add 1 to passenger
R

© SAP AG

Encapsulation is one of the main principles of object-orientation. It serves to ensure that data can
only be accessed by methods that have been specifically designed for the task, and not by other
programs.
In conventional programming, the user of a processing block such as a subroutine or function
module was responsible for choosing the correct data types to ensure that the caller and the called
processing block were compatible.

(C) SAP AG BC411 6-5


Advantages of Object-Oriented Programming

Encapsulation and interfaces


Easy to maintain, high quality
Generic programming and reusability
Integration of external object models
Distributed applications
Support for GUI and Business Workflow

© SAP AG

Object orientation is a programming model that unites data and functions within objects. Objects
hide their internal structures and functions from external users. This means that other components
cannot make assumptions about the inner workings of the object, with the advantage that they cannot
make themselves dependent on a particular internal object implementation.
Object-oriented programming provides ways of improving the structure and implemenation of large
software projects. The main aim is to realize a solution based on objects with clearly-defined
interfaces.
By carefully modeling suitable classes, you can increase the proportion of your programs that are
reusable. Generic constructions allow you to use different classes in a uniform way.
You can use external object models (CORBA, COM, DCOM) in object orientation. This allows you
to develop distributed scenarios.
ABAP Objects is compatible with the object models of graphical user interfaces and SAP Business
Workflow.

(C) SAP AG BC411 6-6


From Function Groups to Objects I

Function group 1 Function group 2

Function Data Function Data


... ...

module module
… …

ABAP program with data

Internal session of an ABAP program


R

External session

© SAP AG

Before Release 4.0, the ABAP components that most closely resembled objects were function
modules and function groups. For example, suppose we have a function group for order procesing.
The attributes of an order correspond to the global data of the function group, and the individual
function modules perform various functions (methods) on the data. In this ways, the internal
workings of the order are encapsulated in the function group, and the actual order data is never
processed directly, but always throguh function modules. The function modules can ensure that the
data always remains consistent.
When a function module is called, an instance of its function group is loaded into the memory area of
the internal session. If a single ABAP program calls function modules from more than one function
group, it will load more than one instance.
The principal difference between 'real' object-orientation and function modules is that a program can
work with instances of several function groups simultaneously, but not with several instances of a
single function group. For example, a program may need to work with several independent counter
variables, or process several orders at once. For this to work, the function group containing the
respective function modules would have to be specially programmed to keep the various instances
apart.

(C) SAP AG BC411 6-7


From Function Groups to Objects II

nth instance, class 1 nth instance, class n


1st instance, class 1 1st instance, class n
Schnitt-
Schnitt- Daten Funktions-
Funktions- Daten
... ...

stelle
Interface Data baustein Data
Function
… ... …
...

module
… …

ABAP program with data

Internal session of an ABAP program


R

External session

© SAP AG

In practice, this is very awkward. Consequently, the data is usually stored in the calling program, and
the function modules are called to work with it. The problem with this is that all of the programs that
use the function modules must use the same data structures as the function group itself. If you
change the internal data structure of a function group, you affect a large number of users, and it is
often difficult to predict the implications of the changes. The only way to avoid this is to rely heavily
on instances and a technique that guarantees that the internal structures of runtime instances will
remain hidden, allowing you to change them later without causing any problems.
Another problem is that all users have copies of the data. When you make changes, it is difficult to
ensure consistency (who has a copy of what, and where is it stored?)
This requirement is met by object-orientation. ABAP Objects allows you to define data and functions
in classes instead of function groups. Using classes, an ABAP program can work with any number of
runtime instances based on the same template.
Instead of loading a single runtime instance of a function group into memory implicitly when a
function module is called, the ABAP program can now generate the runtime instances of classes
explicitly using the new ABAP statement CREATE OBJECT. The individual runtime instances
represent unique objects. You address these using object references. Object references are a new
ABAP data type (REF TO).

(C) SAP AG BC411 6-8


Classes and Objects
Generalization
Plane Instantiation

Cargo plane Passenger plane

Private plane Business plane

Name AA
AA Hollywood
Hollywood Name D4711 Name LH
LH Munich
Munich
D4711
Pilots 22 Pilots 11 Pilots 22
Capacity 30,000
30,000 kg
kg Passengers Crew 33
33 Passengers 80
80

BB
BB Broadway
Broadway BA
BA Big
Big Ben
Ben
22 D0815
D0815 22
30.000
30.000 kg
kg 11 55R

22 200
200
© SAP AG

A class is an abstract description of a thing - anything - in the real world. You can model classes in a
class hierarchy, in which the specialization of the classes increases as you progress from top to
bottom.
An object (also known as an instance of a class) is a concrete example of the class. Objects that
belong to a particular class all have the same attributes, and can all be accessed using the same
methods. You can only have one copy of a class, but the class may have several objects (instances).
Classes and objects have the same relationship as TYPES to DATA or the structure of a table to the
table contents.
Objects cannot change their class.
In this unit, classes are represented by rectangles with right-angled corners, and objects by rectangles
with rounded corners.

(C) SAP AG BC411 6-9


What is ABAP Objects?

ABAP Objects is a fully compatible extension of the


exisiting ABAP language.
You can use 'conventional' ABAP statements within
ABAP Objects.
Equally, you can use ABAP Objects within
conventional ABAP programs.

© SAP AG

Object-orientation in ABAP is a strictly upwards-compatible extension of the existing ABAP


language. It provides ABAP programmers with the advantages of object-orientation, such as
encapsulation, interfaces, and inheritance, making complex applications easier to control and
simplify.
You can use all conventional ABAP statements and modularization units in ABAP Objects, and,
conversely, ABAP Objects can also be used in existing ABAP programs.
For further information about ABAP Objects, refer to the online documentation:
Help -> R/3 library -> ABAP Workbench -> ABAP Programming -> ABAP Objects or the online
documentation in the ABAP Editor for the term ABAP Objects.

(C) SAP AG BC411 6-10


Classes I
CLASS
CLASS <class>
<class> DEFINITION.
DEFINITION.

PUBLIC
PUBLIC SECTION.
SECTION.
...
... Definition
Definition of
of public
public components
components
PROTECTED
PROTECTED SECTION.
SECTION.
...
... Definition
Definition of
of protected
protected components
components
PRIVATE
PRIVATE SECTION.
SECTION.
...
... Definintion
Definintion of
of private
private components
components
ENDCLASS.
ENDCLASS.
CLASS
CLASS <class>
<class> IMPLEMENTATION.
IMPLEMENTATION.
...
... Method
Method implementation
implementation

ENDCLASS.
ENDCLASS.

© SAP AG

Objects of the same type are all defined by a single class definition. The declaration part of the class
describes its inner structure (attributes), and the methods that you can use to work with the object.
The source code of methods is defined in the implementation part of the class.
A few general statements about classes:
- Classes contain components.
- Each component of a class is assigned to a visibility section.
- Classes implement methods.
A class is made up of components, all of which are declared in the declaration part of the class
definition. Components define the attributes of the objects of the class. Each component is declared
in one of three visibility sections; this defines the interface of the class. All components of a class
are visible within the class itself. The three visibility sections are:
PUBLIC - all public components can be addressed by all users and in all methods. They form the
external interface of the class.
PROTECTED - Protected components of a class can be addressed in the methods of its subclass,
and in the class itself (not yet implemented).
PRIVATE - Private components of a class can only be addressed in the methods of that class.

(C) SAP AG BC411 6-11


Classes II

CLASS c1 DEFINITION.
PUBLIC SECTION. Class c1
DATA: a1 …
METHODS: m1 …
EVENTS: e1 … Public Private
PROTECTED SECTION. components components
DATA: a2 …
METHODS: m2 … a1, a3,
EVENTS: e2 … m1, m3,
PRIVATE SECTION. e3
DATA: a3 … e1
METHODS: m3 … Method
EVENTS: e3 … … implementation
ENDCLASS.
CLASS c1 IMPLEMENTATION. Protected components
a2, m2, e2, …
METHOD m1. … ENDMETHOD.
METHOD m2. … ENDMETHOD.
Subclasses of c1
METHOD m3. … ENDMETHOD.
All users
ENDCLASS. R

© SAP AG

The left-hand side of the illustration shows the declaration and implementation parts of a local class
C1. The right-hand side shows the components of the class in their different visibility sections, and
the implementation of the methods.
The public components form the point of contact between the class and its external users. Protected
components are a point of contact between the class and its subclasses. Private components are fully
encapsulated in the class and are not visible externally. The methods in the implementation part have
unrestricted access to all of the components in the class.

(C) SAP AG BC411 6-12


Declaring Attributes

DATA
DATA <attr>
<attr> TYPE
TYPE <type>
<type>
[[ VALUE
VALUE <val>
<val> ]]
[[ READ-ONLY
READ-ONLY ].
].

REPORT
REPORT sapbc411d_flight.
sapbc411d_flight.

CLASS
CLASS c_customer
c_customer DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
*--
*-- ID
ID can
can only
only be
be changed
changed within
within methods
methods of
of this
this class
class
DATA:
DATA: id
id TYPE
TYPE ii READ-ONLY,
READ-ONLY,
name(30)
name(30) TYPE
TYPE CC VALUE
VALUE 'DummyCustomer'.
'DummyCustomer'.
ENDCLASS.
ENDCLASS.

© SAP AG

Attributes are internal data fields in classes that determine the state of an object. They may have any
ABAP data type. They may be defined as instance attributes, in which case they contain data specific
to a single instance, or as static attributes, which only exist once in each class, and are shared by all
of the instances of the class.
You declare attributes in the declaration part of a class. Public attributes are visible outside the class,
and thus form part of the interface between an object and its users. To encapsulate the state of an
object, you use private attribtues. You can also prevent attributes from being changed by using the
READ-ONLY addition. When you declare attributes, note that you can only use the LIKE addition to
refer to other attributes of the class. You can only refer to data types in the ABAP Dictionary using
the TYPE addition.

(C) SAP AG BC411 6-13


Static Attributes

CLASS-DATA
CLASS-DATA <attr>
<attr> TYPE
TYPE <type>
<type>
[[ VALUE
VALUE <val>
<val> ]]
[[ READ-ONLY
READ-ONLY ].
].

REPORT
REPORT sapbc411d_flight.
sapbc411d_flight.

CLASS
CLASS ccustomer
ccustomer DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
*--
*-- Instance_counter
Instance_counter can
can be
be changed
changed by
by methods
methods of
of this
this
*--
*-- class
class and
and from
from outside
outside the
the class
class
CLASS-DATA:
CLASS-DATA: instance_counter
instance_counter TYPE
TYPE i.
i.
ENDCLASS.
ENDCLASS.

© SAP AG

You can only use this statement in the declaration part of a class declaration. The CLASS- prefix to
the DATA statement means that the attribute a is declared as a static attribute. Otherwise, the
CLASS-DATA statement has the same syntax as DATA statement for instance attributes.
Class attributes belong to the components of a class. Unlike instance attributes, which exist
separately for each instance (object) of a class, and can only be used after you have created at least
one instance, static attributes exist once only and are shared by all instances in the class. The system
does not reset the contents of a class attributes while the class is in use, making them similar to local
data objects in subroutines that you declare using the STATICS statements. Class attributes usually
contain information that is common to all objects, for example, a counter of the number of objects
currently in use.
The appearance of static attributes within a class is the same as that of instance attributes, and you
can address them in the same way. If you access a static attribute from outside the class, you can use
either an object reference or the class name. For example, if a is a static attribute of the class class,
you can access it using class=> in programs in which the class class is declared. Once the class has
been instantiated into an object obj, you can use the normal object reference obj->f to access the
class attribute.

(C) SAP AG BC411 6-14


References: Reference Variables

DATA:
DATA: oflight_1
oflight_1 TYPE
TYPE REF
REF TO
TO c_flight,
c_flight,
oflight_2
oflight_2 TYPE
TYPE REF
REF TO
TO c_flight.
c_flight.

Main memory

Reference semantics

Reference variable
oflight_1
_1

Reference variable
oflight_2
_2

© SAP AG

Objects are instances of classes. Each object has a unique identity and its own attributes. All objects
of a class exist within a single internal session (memory area of an ABAP program). You can create
any number of instances of a class.
ABAP programs access objects using object references. Object references are pointers to objects,
which, in ABAP, occur exclusively as the contents of reference variables (oflight_1 and
oflight_1 above), which use reference semantics (see also the unit on field symbols). This
means that you never address the values of attributes or methods directly, but always using their
reference variables. ABAP contains a new data type TYPE REF TO <class> for this purpose.
One of the advantages of the reference semantics is that the system does not have to copy object
components and methods when you assign one object/reference variable to another. Instead, it
merely copies the address of the new object.
Object references allow you to work with dynamic data structures such as detail lists, trees, graphs,
and so on without having to 'hammer out' their data structure to fit it into a table.
Object attributes can themselves contain reference variables.

(C) SAP AG BC411 6-15


References: Creating Objects

DATA:
DATA: oflight_1
oflight_1 TYPE
TYPE REF
REF TO
TO c_flight,
c_flight,
oflight_2
oflight_2 TYPE REF
TYPE REF TO
TO c_flight.
c_flight.
CREATE
CREATE OBJECT
OBJECT oflight_1.
oflight_1.
CREATE
CREATE OBJECT
OBJECT oflight_2.
oflight_2.

Main memory

Reference semantics

Reference variable
C_FLIGHT<1>
oflight_1

Reference variable C_FLIGHT<2>


oflight_2
R

© SAP AG

Once you have created a reference variable with reference to the class c_flight, you can create
an instance of the class (an object) using the statement CREATE OBJECT <cref>. The reference
variable <cref> now contains a reference to the object.
You can create any number of objects belonging to the same class, each of which is fully
independent of the others. Each object has its own identity and its own attributes. Each CREATE
OBJECT statement creates a new object whose identity is defined by its unique object reference.
In the above diagram, instances are displayed as rounded rectangles. The above notation for
instances corresponds to the contents of the reference variables as displayed in the ABAP Debugger.

(C) SAP AG BC411 6-16


References: Assigning References

DATA:
DATA: oflight_1
oflight_1 TYPE
TYPE REF
REF TO
TO c_flight,
c_flight,
oflight_2
oflight_2 TYPE
TYPE REF
REF TO
TO c_flight.
c_flight.
CREATE
CREATE OBJECT
OBJECT oflight_1.
oflight_1.
CREATE
CREATE OBJECT
OBJECT oflight_2.
oflight_2.
oflight_2
oflight_2 == oflight_1
oflight_1

Main memory

Reference semantics

Reference variable C_FLIGHT<1>


oflight_1

Reference variable C_FLIGHT<2>


oflight_2
R

© SAP AG

You can assign refrences to other reference variables using the MOVE statement. This means that
more than one reference variable can point to the same object. When you assign reference variables,
the types of the source and target variables must either be compatible or convertible.
In the statement oflight_2 = oflight_1, both of the class references oflight_1 and
oflight_2 must have the same type, that is, they must both refer to the same class, or the class of
oflight_1 must be the predefined empty class OBJECT.
The class OBJECT has no components. Its significance to reference variables is the same as that of
data type ANY to normal variables. Reference variables with the type OBJECT can serve as
containers for passing references. However, you cannot use them to access objects.

(C) SAP AG BC411 6-17


References: Garbage Collection

DATA:
DATA: oflight_1
oflight_1 TYPE
TYPE REF
REF TO
TO c_flight,
c_flight,
oflight_2
oflight_2 TYPE
TYPE REF
REF TO
TO c_flight.
c_flight.
CREATE
CREATE OBJECT
OBJECT oflight_1.
oflight_1.
CREATE
CREATE OBJECT
OBJECT oflight_2.
oflight_2.
oflight_2
oflight_2 == oflight_1
oflight_1

Main memory

Reference semantics

Reference variable
C_FLIGHT<1>
oflight_1

Reference variable C_FLIGHT<2>


oflight_2 Garbage collection
R

© SAP AG

As soon as no more references point to an object, the runtime system automatically releases the
memory occupied by it. This is known as garbage collection.

(C) SAP AG BC411 6-18


Classes and Instances: Example

REPORT
REPORT sapbc411d_flight.
sapbc411d_flight.
TYPES:
TYPES: tpassenger(20).
tpassenger(20).

CLASS
CLASS c_flight
c_flight DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
METHODS:
METHODS: book
book ...
...
PRIVATE
PRIVATE SECTION.
SECTION.
DATA:
DATA: passenger_list
passenger_list TYPE
TYPE STANDARD
STANDARD TABLE
TABLE OF
OF tpassenger.
tpassenger.
ENDCLASS.
ENDCLASS.
CLASS
CLASS c_flight
c_flight IMPLEMENTATION.
IMPLEMENTATION.
METHOD
METHOD book.
book.
MOVE
MOVE ...
...
APPEND
APPEND ...
...
ENDMETHOD.
ENDMETHOD.
ENDCLASS.
ENDCLASS.
START-OF-SELECTION.
START-OF-SELECTION.
DATA:
DATA: oflight
oflight TYPE
TYPE REF
REF TO
TO c_flight.
c_flight.
CREATE
CREATE OBJECT
OBJECT oflight.
oflight.

© SAP AG

You define object references in the DATA or TYPES statement using the form
<ref.variable> TYPE REF TO <class name>.
The CREATE OBJECT statement creates objects dynamically. The program requests main memory
space from the system to enable it to store the attributes and methods of the new object. The
reference to the object is stored in the reference variable.

(C) SAP AG BC411 6-19


Declaring Methods
METHODS
METHODS <meth>
<meth>
IMPORTING
IMPORTING ..
.. VALUE(<i>)|
VALUE(<i>)| <i>
<i> TYPE
TYPE type
type [OPTIONAL]
[OPTIONAL]
..
..
EXPORTING
EXPORTING ..
.. VALUE(<e>)|
VALUE(<e>)| <e>
<e> TYPE
TYPE type
type [OPTIONAL]
[OPTIONAL] ..
..
CHANGING
CHANGING ..
.. VALUE(<c>)|
VALUE(<c>)| <c>
<c> TYPE
TYPE type
type [OPTIONAL]
[OPTIONAL]
..
.. RETURNING
RETURNING VALUE(<r>)
VALUE(<r>)
EXCEPTIONS
EXCEPTIONS ..
.. <exc>
<exc> ..
..

REPORT
REPORT sapbc411d_…
sapbc411d_… ..
TYPES:
TYPES: tpassenger(20).
tpassenger(20).
TABLES:
TABLES: sflight.
sflight.
DATA:
DATA: begin
begin of
of wa,
wa, ...
...
CLASS
CLASS c_flight
c_flight DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
METHODS:
METHODS: book
book IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger
tpassenger
carrid
carrid LIKE
LIKE sflight-carrid,
sflight-carrid,
connid
connid LIKE
LIKE sflight-connid,
sflight-connid,
fldate
fldate LIKE
LIKE sflight-fldate.
sflight-fldate.

© SAP AG

You declare methods in the declaration part of a class or interface. The above example with its
additions declares an instance method. For further information, refer to the keyword documentation
in the ABAP Editor for the METHODS statement.
You must specify the type of all interface parameters using the TYPE or LIKE addition.
When you declare a method, you also declare its parameters interface using the IMPORTING,
EXPORTING, CHANGING and RETURNING additions. These define the input, output,
input/output and return code parameters. You also define the attributes of the interface parameters,
for example, whether it is passed by reference or value (VALUE), whether it has a fixed type (TYPE),
and whether an input parameter is optional (OPTIONAL, DEFAULT). Unlike function modules, the
default passing method for methods is by reference. To pass a parameter by value, you must
explicitly use VALUE. The return value (RETURNING parameter) must always be passed as a value.
This parameter is suitable for methods that return a single value. If you use a returning parameter,
you cannot use exporting or changing parameters.
Like function modules, methods allow you to define exception parameters (EXCEPTIONS),
allowing the user to react to errors that occur during the method.

(C) SAP AG BC411 6-20


Implementing Methods
METHOD
METHOD <meth>.
<meth>.
...
... Implementation
Implementation ...
...
ENDMETHOD.
ENDMETHOD.

REPORT
REPORT sapbc411d_…
sapbc411d_… ..
TYPES:
TYPES: tpassenger(20).
tpassenger(20).
TABLES:
TABLES: sflight.
sflight.
DATA:
DATA: begin
begin of
of wa,
wa, ...
...
CLASS
CLASS c_flight
c_flight DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
METHODS:
METHODS: book
book IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger
tpassenger
carrid
carrid LIKE
LIKE sflight-carrid,
sflight-carrid,
connid
connid LIKE
LIKE sflight-connid,
sflight-connid,
fldate
fldate LIKE
LIKE sflight-fldate.
sflight-fldate.
PRIVATE
PRIVATE SECTION.
SECTION.
DATA:
DATA: passenger_list
passenger_list TYPE
TYPE STANDARD
STANDARD TABLE
TABLE OF
OF wa.
wa.
ENDCLASS.
ENDCLASS.
CLASS
CLASS c_flight
c_flight IMPLEMENTATION.
IMPLEMENTATION.
METHOD
METHOD book.
book.
MOVE
MOVE carrid
carrid TO
TO wa-carrid,
wa-carrid, ...
...
APPEND
APPEND wa
wa TO
TO passenger_list.
passenger_list.
ENDMETHOD.
ENDMETHOD. R

ENDCLASS.
ENDCLASS.

© SAP AG

You must implement all of the methods that you declare in a class in its implementation part. Each
method implementation must be enclosed in the METHOD <meth> … ENDMETHOD statements in
the same way that a function module definition is enclosed in the FUNCTION … ENDFUNCTION
statements.
When you implement a method, you do not need to list its interface parameters again, since you have
already specified them in the method declaration. The interface parameters of methods are treated
like local variables within the method implementation. You can also declare other local data using
the DATA statement.
Like function modules, methods allow you to use the RAISE <exception> and MESSAGE RAISING
statements to trigger exceptions.
When you implement static methods, remember that they can only use the static attributes of the
class. Instance methods can use both static attributes and instance attributes (see also the online
documentation for the CLASS statement).

(C) SAP AG BC411 6-21


Calling Methods
CALL
CALL METHOD
METHOD <method>
<method> EXPORTING
EXPORTING <formal_e>
<formal_e> == <actual_e>
<actual_e>
IMPORTING
IMPORTING <formal_i>
<formal_i> == <actual_i>
<actual_i>
CHANGING
CHANGING <formal_c>
<formal_c> == <actual_c>
<actual_c>
RECEIVING
RECEIVING rr == hh
EXCEPTIONS
EXCEPTIONS <exc_i>
<exc_i> == rc_i.
rc_i.
REPORT
REPORT sapbc411d_flight.
sapbc411d_flight.
CLASS
CLASS c_flight
c_flight DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
METHODS:
METHODS: book
book IMPORTING
IMPORTING ...
...
PRIVATE
PRIVATE SECTION.
SECTION. ...
...
ENDCLASS.
ENDCLASS.
CLASS
CLASS c_flight
c_flight IMPLEMENTATION.
IMPLEMENTATION.
METHOD
METHOD book.
book.
...
...
ENDMETHOD.
ENDMETHOD.
ENDCLASS.
ENDCLASS.

DATA:
DATA: oflight
oflight TYPE
TYPE REF
REF TO
TO c_flight.
c_flight.
CREATE
CREATE OBJECT
OBJECT oflight.
oflight.
CALL
CALL METHOD
METHOD oflight->book
oflight->book EXPORTING
EXPORTING passenger
passenger == 'Peter
'Peter Miller'
Miller'
carrid
carrid == 'LH'
'LH' R

connid
connid == '0400'
'0400'
fldate
fldate == '19980202'.
'19980202'.
© SAP AG

You call methods using the above statement. The exact way in which you address the method
<method> depends on where in the program the call occurs. Within the implementation part of a
class, you can call methods in the same class directly using the name <method>.
CALL METHOD <method> … If you are calling the method from outside the class, the visibility
section of the method determines whether the call is possible. You can call visible instance methods
from outside the class using CALL METHOD <ref>-><method> where <ref> is a reference
variable whose value points to an instance of the class. You can call visible static methods from
outside the class using CALL METHOD <class>=><method> where <class> is the name of
the class.
When you call a method, you must specify all non-optional input parameters in the EXPORTING
and CHANGING additions of the CALL METHOD statement. You can (but do not have to) receive
the IMPORTING and RECEIVING parameters. It is also up to the caller whether to handle any
exceptions triggered in the method using the EXCEPTIONS addition. However, you are
recommended to do s.
You pass and receive values using the same syntax as with function modules, namely:
<formal parameter> = <actual parameter> following the corresponding addition.

(C) SAP AG BC411 6-22


Constructor

CLASS
CLASS cc DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
METHODS
METHODS CONSTRUCTOR
CONSTRUCTOR
[[ IMPORTING
IMPORTING VALUE(arg1)
VALUE(arg1) TYPE
TYPE type
type …… ].
].
ENDCLASS.
ENDCLASS.

PROGRAM
PROGRAM …… ..
DATA
DATA o1
o1 TYPE
TYPE REF
REF TO
TO ……

CREATE
CREATE OBJECT
OBJECT o1
o1 EXPORTING
EXPORTING arg1
arg1 == v1
v1 arg1
arg1 == v2.
v2.

Classes can define a constructor, which is automatically called at the


CREATE OBJECT statement.
The name is always CONSTRUCTOR (reserved name).
The constructor can only have IMPORTING parameters.
R

© SAP AG

Constructors are special methods that give objects and classes a particular initial state. The state of
an object or class is determined by its instance attributes or static attributes. You can preassign
values to attributes using the VALUE addition in the DATA statement. If, on the other hand, you
want to define the initial state of an object dynamically, you need to use a constructor.
The CONSTRUCTOR method is called after an object has been fully created in the
CREATE OBJECT <obj> statement (see also the online documentation for the CREATE
statement).

(C) SAP AG BC411 6-23


Interfaces
Interfaces define the interaction between objects
Polymorphism is independent of classes and
inheritance
Classes can implement more than one interface
Interface references provide uniform access

Booking_
Booking_Mgr

IBook

R
Flight Hotel Rental Car

© SAP AG

By their visibility, the components of a class define the external points of contact for a class. For
example, the public components define a point of contact that can be addressed by any other user.
Interfaces are standalone components that you can implement in classes to extend the class-specific
contact points. They provide a uniform way of addressing different classes. Interfaces are the basis
for polymorphism, since their methods can behave differently in the different classes in which they
are implemented. Interface references allow users to address different classes using the same
structure.
The above example shows a booking manager application that you can use to book flights, hotel
rooms, and rental cars. An interface (Ibook) allows you to extend the classes flight, hotel, and
rental car, and implement the booking procedure in each of the different classes by addressing the
same interface.

(C) SAP AG BC411 6-24


Interfaces: Model

INTERFACE i1.
DATA: a1. ...
METHOD: m1. ... Class c1
ENDINTERFACE.
Public Private
components components
CLASS c1 DEFINITION. a2,
a1,...
PUBLIC SECTION. m2,
DATA a1 … i1~a1. e2
INTERFACES i1 … i1~m1. Method
PROTECTED SECTION. implementation
PRIVATE SECTION.
Protected components
ENDCLASS. a3, m3, e3, …

CLASS c1 IMPLEMENTATION.
Subclasses of c1
METHOD i1~m1. … ENDMETHOD.
ENDCLASS. All users R

© SAP AG

The left-hand side of the diagram shows the definition of a local interface i1 and the declaration and
implementation parts of a local class c1 that implements interface i1 in its public section. The
implementation part of the class definition contains the implementation of the interface method
i1~m1.
The right-hand side shows the structure of the class with the components in their respective visibility
sections, and the implementation of the methods. The interface components extend the public
components of the class. All users can address both the class-specific public components and the
interface components.

(C) SAP AG BC411 6-25


Defining Interfaces

INTERFACE
INTERFACE <interface>.
<interface>.
...
... (Definition
(Definition of
of interface
interface components)
components) ...
...
ENDINTERFACE.
ENDINTERFACE.

INTERFACE
INTERFACE i_reservation.
i_reservation.
METHODS:
METHODS: book
book IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger,
tpassenger,
cancel
cancel IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger
tpassenger
ENDINTERFACE.
ENDINTERFACE.

© SAP AG

Like classes, you can define interfaces either globally in the R/3 Repository, or locally in an ABAP
program. The definition of a local interface <interface> is always enclosed in the statements
INTERFACE <interface> … ENDINTERFACE. Interfaces are abstract descriptions of
attributes sharead by different classes. They contain the same components as classes (attributes,
method definitions, events, constants), but do not have an implementation part. Instead, interface
methods are implemented by the class that implements the interface.
The components of interfaces do not have to be explicitly assigned to a visibility section, since the
interface itself is assigned to a visibiltiy section of the class that implements it, and all of its
components automatically assume the same visibility.
Interfaces allow you to implement abstract functions. In the above example, the methods 'book' and
'cancel' could appear in both the classes 'flight' and 'hotel'. However, the actual implementation is
different in each class. While you need to know the departure city, arrival city, and flight time to
book or cancel a flight, you need the duration of a guest's stay to book or cancel a hotel room.
Interfaces allow you to define common components of different classes in one place. Classes that
implement interfaces must implement all of their methods.
The question now remains as to how interfaces are linked to objects. This is explained on the next
page.

(C) SAP AG BC411 6-26


Implementing Interfaces

METHOD
METHOD <interface~imethod>.
<interface~imethod>.
...
... (Method
(Method implementation)
implementation) ...
...
ENDINTERFACE.
ENDINTERFACE.

INTERFACE
INTERFACE i_reservation.
i_reservation.
METHODS:
METHODS: book
book IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger,
tpassenger,
cancel
cancel IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger
tpassenger
ENDINTERFACE.
ENDINTERFACE.

CLASS
CLASS c_flight
c_flight DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
INTERFACES:
INTERFACES: i_reservation.
i_reservation.
...
...
ENDCLASS.
ENDCLASS.
CLASS
CLASS c_flight
c_flight IMPLEMENTATION.
IMPLEMENTATION.
METHOD
METHOD i_reservation~book.
i_reservation~book.
…… (Booking
(Booking code
code specific
specific to
to this
this class)
class)
ENDMETHOD.
ENDMETHOD.
ENDCLASS.
ENDCLASS.
R

© SAP AG

Unlike classes, interfaces do not have instances. Instead, they are implemented by classes.
When a class implements an interface, it must implement all of its methods. So the implementation
part of a class must have a statement block METHOD <interfacemethod~imeth> …
ENDMETHOD for each interface method <interfacemethod>.

(C) SAP AG BC411 6-27


Generic Programming Using Interface
References

INTERFACE
INTERFACE i_reservation.
i_reservation.
METHODS:
METHODS: book
book ...
...
cancel...
cancel...
ENDINTERFACE.
ENDINTERFACE.
...
... Klassendefinition
Klassendefinition und
und -implementation
-implementation ...
...

*----------------------------------
*----------------------------------
START-OF-SELECTION.
START-OF-SELECTION.
DATA:
DATA: ires
ires TYPE
TYPE REF
REF TO
TO i_reservation.
i_reservation.
DATA:
DATA: oflight
oflight TYPE
TYPE REF
REF TO
TO c_flight,
c_flight,
ohotel
ohotel TYPE
TYPE REF
REF TO
TO c_hotel.
c_hotel.

CREATE
CREATE OBJECT:
OBJECT: oflight,
oflight, ohotel.
ohotel.
ires
ires == oflight.
oflight.
CALL
CALL METHOD
METHOD ires->book
ires->book EXPORTING
EXPORTING passenger
passenger == 'Müller'
'Müller'
ires
ires == ohotel.
ohotel.
CALL
CALL METHOD
METHOD ires->book
ires->book EXPORTING
EXPORTING passenger
passenger == 'Müller'.
'Müller'.

© SAP AG

You can access the functions described in interfaces using interface references. Instead of creating a
reference variable with reference to a class, you can create them with reference to interfaces. This
kind of reference variable can contain references to objects of classes that implement the
corresponding interface.
Using an interface reference <iref>, a user can address all of the visible interface components
<icomp> of the obejct to which the reference is pointing using the form <iref>-<icomp>. In
other words, the user can access those components that have been added to the class by its
implementing the interface.
In the example, the expression ires = oflight means that ires now points to the same object as the
class reference in oflight. However, it can only access the methods of the object oflight that are
declared in the interface. The interface thus provides a restricted view of the methods of the object
oflight.
You can access the interface component book using CALL METHOD ires->book. Similarly, you
can access an attribute defined in an interface using <iref_variable>-><attr>.
Note: You can book both a flight and a hotel room by calling the method 'book'. The actual method
that is called depends on the target of the interface reference. You can thus program generically by
'redirecting' the reference variable.

(C) SAP AG BC411 6-28


Interfaces - Example
INTERFACE
INTERFACE i_reservation.
i_reservation.
METHODS:
METHODS: book
book IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger,
tpassenger,
cancel
cancel IMPORTING
IMPORTING passenger
passenger TYPE
TYPE tpassenger.
tpassenger.
ENDINTERFACE.
ENDINTERFACE.
CLASS
CLASS c_flight
c_flight DEFINITION.
DEFINITION. CLASS
CLASS c_hotel
c_hotel DEFINITION.
DEFINITION.
...
... ...
...
INTERFACES:
INTERFACES: i_reservation.
i_reservation. INTERFACES:
INTERFACES: i_reservation.
i_reservation.
ENDCLASS.
ENDCLASS. ENDCLASS.
ENDCLASS.
CLASS
CLASS class_flight
class_flight IMPLEMENTATION.
IMPLEMENTATION. CLASS
CLASS class_hotel
class_hotel IMPLEMENTATION.
IMPLEMENTATION.
...
... ...
...
METHOD
METHOD i_reservation~book.
i_reservation~book. METHOD
METHOD i_reservation~book.
i_reservation~book.
...
... ...
...
ENDMETHOD.
ENDMETHOD. ENDMETHOD.
ENDMETHOD.
METHOD
METHOD i_reservation~cancel.
i_reservation~cancel. METHOD
METHOD i_reservation~cancel.
i_reservation~cancel.
...
... ...
...
ENDMETHOD.
ENDMETHOD. ENDMETHOD.
ENDMETHOD.
ENDCLASS.
ENDCLASS. ENDCLASS.
ENDCLASS.
START-OF-SELECTION.
START-OF-SELECTION.
DATA:
DATA: ires
ires TYPE
TYPE REF
REF TO
TO i_reservation.
i_reservation.
DATA:
DATA: oflight
oflight TYPE
TYPE REF
REF TO
TO c_flight,
c_flight, ohotel
ohotel TYPE
TYPE REF
REF TO
TO c_hotel.
c_hotel.
CREATE
CREATE OBJECT:
OBJECT: oflight,
oflight, ohotel.
ohotel.
ires
ires == oflight.
oflight.
CALL
CALL METHOD
METHOD ires->book
ires->book EXPORTING
EXPORTING passenger
passenger == 'Miller'.
'Miller'. R

ires
ires == ohotel.
ohotel.
CALL
CALL METHOD
METHOD ires->book
ires->book EXPORTING
EXPORTING passenger
passenger == 'Miller'.
'Miller'.
© SAP AG

Classes implement interfaces by implementing all of the methods defined in the interface.
Classes can implement more than one interface.

(C) SAP AG BC411 6-29


Events
Controller
Controller
Business
Business plane
plane
Mr Smith
Landed=1

LH Munich

IF altitude = 0. Pilot
Pilot
RAISE EVENT touch_Down.
ENDIF. Pilot Miller
Relax!
Passenger
Passenger

Mrs Jones
Applause!
R

© SAP AG

Objects can announce that their state has changed by triggering events. Events usually contain export
parameters, but no import parameters, since the object only wants to announce its change of state - it
is not concerned about any further processing.
In the above example, the class business plane can trigger the event 'touch_down', which has been
registered by other classes, and is then handled by them. For example, the air traffic controller
checks off the plane as landed, the pilot can relax, and passenger Jones applauds.
Unlike 'normal' methods, where the caller controls the procedure and knows the method that has
been called, an object that triggers an event does not know who will handle it.

(C) SAP AG BC411 6-30


Events
Trigger Handler
CLASS c1 DEFINITION. CLASS c2 DEFINITION.
PUBLIC SECTION. PUBLIC SECTION.
EVENTS e1 EXPORTING VALUE (p1) METHODS: m2 FOR EVENT e1 OF c1
TYPE i. IMPORTING p1.
METHODS: m1.

PRIVATE SECTION. PRIVATE SECTION.


DATA: a1 TYPE i. DATA: a2 TYPE i.

ENDCLASS. ENDCLASS.

CLASS C1 IMPLEMENTATION. CLASS C1 IMPLEMENTATION.


METHOD m1. METHOD m2.
a1 = ... a2 = p1.
RAISE EVENT e1 EXPORTING p1 = a1 ...
ENDMETHOD. ENDMETHOD.
ENDCLASS. ENDCLASS.
R

© SAP AG

In order to trigger an event, a class must declare it in its declaration part and trigger it in its methods.
You declare events in a class or interface using the statement EVENTS <evt> EXPORTING …
VALUE (<ei>) TYPE type [OPTIONAL]. To declare a static event, use the statement
CLASS-EVENTS <evt> ...
The EXPORTING parameters are always passed by value.
If a class contains an instance event, any methods of the class can trigger it. Static events can be
triggered by any static method. To trigger an event in a method, use the statement RAISE EVENT
<evt> EXPORTING … <ei> = <fi>...
In the EXPORTING addition, you must specify the actual parameter <fi> for any formal parameter
<ei> that is not defined as optional.
Events are handled by special methods. To handle an event, a method must be declared as an event
handler method for it, and must have registered for the event at runtime.

(C) SAP AG BC411 6-31


Defining Events

EVENTS
EVENTS name
name [[ EXPORTING
EXPORTING VALUE(arg1)
VALUE(arg1) TYPE
TYPE type
type …… ]]

CLASS
CLASS c_button
c_button DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
EVENTS:
EVENTS: e_clicked
e_clicked EXPORTING
EXPORTING VALUE(doubleclick)
VALUE(doubleclick) TYPE
TYPE I.
I.
ENDCLASS.
ENDCLASS.

CLASS
CLASS c_button
c_button IMPLEMENTATION.
IMPLEMENTATION.
METHOD
METHOD mouse_click.
mouse_click.
RAISE
RAISE EVENT
EVENT e_clicked
e_clicked EXPORTING
EXPORTING doubleclick
doubleclick == 0.
0.
ENDMETHOD.
ENDMETHOD.
ENDCLASS.
ENDCLASS.

© SAP AG

Events may be components of classes and interfaces. Like all other components, the event has the
visibility of the visibility section in which it is defined.
You can only use the EVENTS statement in the declaration part of a class or definition.
The EXPORTING addition defines the event interface. The exporting parameters define the view
that the trigger has of the event.
Events can be triggered by the methods of the same class using the RAISE EVENT statement.
When the event is triggered, the interface parameters are passed to the interface of the event handler
method using the EXPORTING addition of the RAISE EVENT statement. The interface of an event
handler methods contains a list of IMPORTING parameters with the same names as their
corresponding EXPORTING parameters. This is generated automatically from the interface of the
event.

(C) SAP AG BC411 6-32


Defining an Event Handler

METHODS
METHODS name
name FOR
FOR EVENT
EVENT ee OF
OF c|i
c|i
[[ IMPORTING
IMPORTING form_par …… ]]
form_par

CLASS
CLASS c_window
c_window DEFINITION.
DEFINITION.
PUBLIC
PUBLIC SECTION.
SECTION.
METHODS:
METHODS: okclicked
okclicked FOR
FOR EVENT
EVENT e_clicked
e_clicked OF
OF c_button
c_button
IMPORTING
IMPORTING doubleclick,
doubleclick,
cancelclicked
cancelclicked FOR
FOR EVENT
EVENT e_clicked
e_clicked OF
OF c_button
c_button
IMPORTING
IMPORTING doubleclick,
doubleclick,
ENDCLASS.
ENDCLASS.

© SAP AG

Any class can contain event handler methods for events of other classes or interfaces. You declare
event handler methods for instance methods using the statement
METHODS <name> FOR EVENT <e> of <c|if> IMPORTING … <form_par>
where <e> is an event declared in class <c> or interface <if>.
The interface of an event handler method may only contain formal parameters defined in the
declaration of the event <e>. The attributes of the parameters are also adopted from the event.
However, the event handler method does not have to accept all of the parameters passed in the
RAISE EVENT statement.
If a class declares an event handler method, it and its instances are, in principle, capable of handling
the event <e> that is triggered in an event.

(C) SAP AG BC411 6-33


Registering and Triggering Events

Registering a handler and triggering the event

DATA:
DATA: okbutton
okbutton TYPE
TYPE REF
REF TO
TO c_button,
c_button, "" Object
Object that
that triggers
triggers an
an event
event
cancelbutton
cancelbutton TYPE
TYPE REF
REF TO
TO c_button,
c_button, "" Object
Object that
that reacts
reacts to
to an
an event
event
h1,
h1, h2
h2 TYPE
TYPE REF
REF TO
TO c_window.
c_window. "" Object
Object that
that reacts
reacts to
to an
an event
event
CREATE
CREATE OBJECT:
OBJECT: okbutton,
okbutton, cancelbutton,
cancelbutton, h1,
h1, h2.
h2.

SET
SET HANDLER:h1->okclicked
HANDLER:h1->okclicked FOR
FOR okbutton,
okbutton, "" Register
Register for
for event
event
h2->cancelclicked
h2->cancelclicked FOR
FOR cancelbutton.
cancelbutton.
CALL
CALL METHOD
METHOD okbutton->mouseclick.
okbutton->mouseclick. "" Trigger
Trigger event
event
CALL
CALL METHOD
METHOD cancelbutton->mouseclick.
cancelbutton->mouseclick. "" Trigger
Trigger event
event

© SAP AG

In order for an event handler method to react to an event, you must define at runtime the trigger to
which it should react. You do this using the statement SET HANDLER … <hi> … [FOR] …
This statement links a list of handler methods with the trigger methods. The triggered event has four
possible forms:
An instance event defined in a class
An instance event defined in an interface
A static event defined in a class
A static event defined in an interface.
The syntax and effect of the SET HANDLER statement differs in each case.
If the event is an instance event, you must use the FOR addition to specify the triggering instance for
which you want to register. You can either register a single instance using a reference variable <ref>:
SET HANDLER … <hi> for <ref>. Or you can register the handler for all instances as follows:
SET HANDLER … <hi>… FOR ALL INSTANCES.
This registration also applies to instances that do not yet exist at the time when you register the
event. You cannot use the FOR addition for static events: SET HANDLER … <hi> … The
registration automatically applies to the whole class, or to all classes implementing the interface with
the static event. The registration also applies to classes that implement the interface but have not yet
been loaded at the time of registration.

(C) SAP AG BC411 6-34


Events: Handler Table

Handler: h1
Handler table
Reference variable
e1 (Event) okclicked
okbutton
Registered handling
object method
h1 okclicked

Sender:okbutton
h1

© SAP AG

Triggering and handling methods means that certain methods trigger events, while others are
registered as handlers and are executed when the event occurs.
Objects can trigger events while executing a method. The event can then be processed by 'interested'
objects that have already registered themselves for the event. This registration is noted in an internal
handler table. In the above example, objects h1 and h2 have registered for event h1, and will react to
it using method m2.
Events allow very flexible programming. Unlike structured programming, where a program
explicitly calls an external processing block, a program that triggers an event does not have to know
who will react to it.
You declare events and event handler methods in classes. When an event occurs, the system looks
for registered objects and calls the corresponding source code of the event handler methods.

(C) SAP AG BC411 6-35


Summary

In this unit, you have learned about


object-oriented programming with ABAP
Objects. Object orientation allows you to
create programs that are easier to
maintain and have a better structure.
ABAP Objects supports all of the
significant characteristics of object
orientation, such as encapsulation,
interfaces, and events.

© SAP AG

(C) SAP AG BC411 6-36


Preview: Inheritance

Plane
Plane Plane
Plane
name altitude
fuelMaximum fuelActual numberOfPilots
setName ascend refuel

Passenger
Passenger plane
plane
name altitude
Passenger
Passenger plane
plane
fuelMaximum fuelActual
numberOfPilots passengerMaximum
passengerActual
setName ascend refuel
loadPassenger loadBaggage

Cargo
Cargo plane
name altitude
Cargo
Cargo plane
plane fuelMaximum fuelActual
numberOfPilots loadMaximum loadActual
setName ascend refuel R

loadCargo
© SAP AG

Inheritance Classes are, as a rule, not fully independent of each other. On the contrary, you can add
extra attributes and methods to most classes to make them more specialized. The new class is a
subclass of the old class (its superclass). The program code of a superclass is reused in all of its
subclasses, and any changes in the code are instantly and automatically effective in the subclasses as
well. You can add new methods to subclasses and also overwrite methods that they have inherited
from the superclass.
Inheritance and polymorphism are two characteristics of object-oriented programming that
distinguish it from conventional programming.
ABAP Objects does not yet support inheritance. It is planned to allow classes to inherit from one
superclass only (single inheritance).

(C) SAP AG BC411 6-37


Contexts: Contents

Contexts
How to use contexts
Where to use contexts
Buffering contexts
Maintaining contexts

© SAP AG
Unit Objectives

In this unit, you will learn


What a context is
Why you would want to use contexts
How contexts are buffered
How to use a context in an ABAP program
How to create and maintain contexts

© SAP AG

(C) SAP AG BC411 7-2


What is a Context?

Little basic data Derived data:

Ex.:Table
Ex.:Table SGEOCITY
SGEOCITY Field Value Derived by
Latitude 5.00090E01 Reading directly
City Country
Longitude 8.68000E01 Reading directly
Frankfurt D
Distance 6199.5164 Calculation
New York USA
Airport Frankfurt Int. Reading another
Paris F Airport table
Madrid E
LH0400,
Flights AZ0788,
UA3504, ... ...
... ... ...

© SAP AG

Among all of the data in the R/3 System, there is a relatively small amount of basic data from which
you can derive further information.
You often use particular relationships between data to retrieve other data, not only in one program,
but in several, each time using the same relationship. This means that the same database operations
or calculations are performed repeatedly, even though the required result had already been retrieved
or calculated previously.
Contexts provide a way of avoiding this unnecessary system load.
Contexts are ABAP Workbench objects, consisting of key fields (input fields), fields that are derived
from the values of the key fields, and the relationships between them. They do not store any actual
data. Instead, they provide a static definition of functional dependencies.
In ABAP programs, you work with instances of contexts, which contain the actual data.

(C) SAP AG BC411 7-3


Using Contexts
REPORT
REPORT ....
....
REPORT yyy.
** Calculate
Calculate geographical
geographical distance
distance
...
SELECT
SELECT longitude
longitude latitude
latitude FROM
FROM sgeocity
sgeocity
* Calculate geographical distance
WHERE
WHERE city
city == 'FRANKFURT'
'FRANKFURT'
AND
AND country
country == 'DE'.
'DE'.
REPORT zzz.
pi
pi == acos(
acos( -1-1 ).
).
x1
x1 == latitude1
latitude1 ** pi pi // 180.
180.
...
y1
y1 == longitude1
longitude1 ** pi pi // 180.
180.
* Calculate geographical distance
x2
x2 == latitude2
latitude2 ** pi pi // 180.
180.
y2
y2 == longitude1
longitude1 ** pi pi // 180.
180.
REPORT xyx.
yd
yd == y2
y2 -- y1.
y1.
distance
distance == 20000
20000 // pipi **
* Calculate geographical distance
ACOS(
ACOS( SIN(
SIN( x1x1 )) ** SIN(
SIN( x2
x2 )) ++ COS(
COS( x1
x1 ))
** COS(
COS( x2x2 )) ** COS(
COS( ydyd )) ).
).

Context buffer (main memory)


Read
Field Value Field Value buffer
Set city Frankfurt city New York
buffer country D country USA
latitude 5.0009E01 latitude
longitude 8.6800E01 longitude R

distance (FRA-NY) 6199.5164

© SAP AG

By using contexts, you can:


Reduce the complexity of your application programs because a lot of the processing logic is
transferred to the context program.
Make better use of recurring logic.
Increase performance by buffering the contexts.
Contexts are intended to store single complex functional relationships that occur frequently within
an application. They are not intended for buffering large amounts of data that has to be processed
sequentially.
The difference between the context buffer and the normal database and SAP table buffers is that it is
only refreshed at set intervals, and does not constantly synchronize itself with changes.
As a rule, you will work with contexts delivered by SAP in your system, using the Context Builder
to familiarize yourself with them and to test them.

(C) SAP AG BC411 7-4


Structure of a Context

Table
Table // View
View

Fields Modules Function


Function module
module
Context
Context

© SAP AG

Contexts consist of fields and modules. The fields are divided into key fields and derived fields, and
the modules describe the relationships between the fields. Modules are blocks, linked to one another
by a defined interface.
A module can be a:
- Database table or view
- Function module
- Context.
When you use a table as a module, all of its fields are adopted in the context. The key fields of the
table serve as the input parameters of the module.
When you use a function module, all of its interface parameters are adopted in the context. The
names of the context fields are generated automatically, but these default names can be overwritten.
The import parameters of the function module serve as the input parameters of the context module,
and the export parameters of the function module serve as its output parameters.
When you use a context as a module, all of its fields are adopted in the context. The system generates
names for the context fields.

(C) SAP AG BC411 7-5


Testing Contexts

Context: DEMO_CITIES

Fields Values Modules


CITY1 ACAPULCO Geogr. position of a city
COUNTRY1 MX Geogr. position of a city
CITY2 Geogr. distance
COUNTRY2
LONGITUDE1
LATITUDE1
LONGITUDE2
LATITUDE2 Context: Testumgebung
DISTANCE Icon Meaning in fields Meaning in modules
Value unknown Module inactive
Value calculable Module can be activated
Value known Module is active

© SAP AG

In the Context Builder, enter the name of the context that you want to test and choose Test.
To test the context, enter values for its key fields (input fields). If you want to use a space as an input
field, single-click the stoplight icon next to the relevant field to change its status. Next, select the
output fields that you want to see, and choose Calculate values.
To display the relationship between fields and modules, double-click a field or a module.
You can also display the current contents of the buffer.

(C) SAP AG BC411 7-6


Derivation Schema of a Context

Network graphic
LONG1/
Country 1 COUNTRY1 Georgraphical pos. LAT1
COUNTRY1 SGEOCITY1

City 1 CITY1
CITY1

LONG2/
City 2 CITY2 Geographical pos. LAT2 Geographical pos.
CITY2 SGEOCITY2 DISTANCE

Country 2 COUNTRY2
COUNTRY2 R

© SAP AG

The network graphic shows you the derivation schema of your context.
On the left are the key fields (input fields) of the context, including their technical names. On the
right are the modules that process the values from the fields. Further to the right, there may be
further modules whose input values are supplied by the output values of preceding modules (in this
case, DISTANCE).
You can display a module by double-clicking it. To display information about a field, double-click
the connecting line that represents it.

(C) SAP AG BC411 7-7


Buffering Contexts
Buffering types
P Permanent
Constant data T Temporary
N No buffering

Distance 2303.7715
Longitude Latitude
7.070000E01 7.40000E01
Reset every
New York USA hour on the
hour

Distance 2303.7715

Longitude Latitude
5.00160E01 -8.566000E00

Frankfurt D
R

© SAP AG

In the Modules table, you can set one of the following three buffering types for each module:
Permanent (P)
The default setting. The system retains the data on the application server even after the end of the
transaction. Whenever the context successfully derives a set of results, they (along with the
intermediate results) are placed in the buffer. You can display the buffer in the Context Builder. It is
automatically reset every hour on the hour, but may also be reset manually, either on the local
application server, or on all application servers.
Temporary (T)
If you choose this method, the results are only buffered for the duration of the transaction.
No buffering (N)
None of the results are buffered. If you choose this method for all modules, using the context carries
no performance advantage. However, you still have the advantage of its reusable logic.
The buffer (128 entries for each module) is refreshed according to the last recently used method.
You can change the buffer size in the profile parameter rsdb/obj/buffersize, and the refresh interval
using the parameter rdisp/bufreftime.

(C) SAP AG BC411 7-8


Context Buffer and Context Instances

Presentation

...
Context buffer Roll area 1 Roll area n

Application
Context
Context
instance 1:
instance 2:
demo_travel_
demo_travel_
instance
instance
ABAP
DATA:
demo_travel_
instance Database

© SAP AG

Like other program data, the data of the context instance is stored in the roll area of your program.
The context buffer is stored in the shared memory of the application server.

(C) SAP AG BC411 7-9


Creating a Context Instance

CONTEXTS: <context>.
DATA: <instance> TYPE context_<context>.

REPORT xxx.
CONTEXTS: geogr_information.

DATA: geogr_information_inst1 TYPE context_geogr_information.

© SAP AG

In an ABAP program, you work with runtime instances of contexts. While the context definition in
the Context Builder is a description, the runtime instances contain actual data.
You declare a context to an ABAP program using the CONTEXTS statement. The context
<context> must exist in the Context Builder. The CONTEXTS statement implicitly creates a
special data type context_<context>. You can use this type in a DATA statement to create
context instances.
The system also creates a data type CONTEXT_T_<context>-f for each field in the context. You
can use this data type to create corresponding fields. For an example, see the DEMAND statement.
You can work with several instances of the same context within a program.

(C) SAP AG BC411 7-10


Supplying a Context Instance with Key Values I

Presentation

Context buffer Roll area 1


Application
Context instance table

Entry Value Output fields


Cityfrom Frankfurt
ABAP Cityto New York

SUPPLY

Database

© SAP AG

When you provide a context instance with new key values in a SUPPLY statement, the old output
values in the context instance are automatically invalidated. New output values are then either
calculated or read from the context buffer at the next DEMAND statement.
Important note: The SUPPLY statement involves no database activity.

(C) SAP AG BC411 7-11


Supplying a Context Instance with Key Values II

SUPPLY <key1> = <f1> ... <keyn> = <fn> TO CONTEXT <instance>.

REPORT ....
CONTEXTS: geogr_information.

DATA: geogr_information_inst1 TYPE context_geogr_information.

SUPPLY city = 'FRANKFURT'


country = 'DE'
city_1 = 'NEW YORK'
country_1 = 'USA'
TO CONTEXT geogr_information_inst1.

© SAP AG

The SUPPLY statement supplies the key fields <key1> … <keyn> of an instance with the values
<f1> … <fn>. Once you have done this, you can derive the dependent fields in the context (see
next page).
Whenever you send new key fields to a context instance, the old dependent values in the instance are
automatically invalidated.

(C) SAP AG BC411 7-12


Retrieving Data from a Context Instance I

Presentation

Context buffer Roll area


Context instance table
Frankfurt
New York
2 Application
Entry Value Output fields
6193
Cityfrom Frankfurt DISTANCE
Frankfurt
Cityto New York 6193
Athens
1794
ABAP
1
DEMAND Database
3
R

© SAP AG

The following occurs in a DEMAND statement:

1.) The runtime environment checks whether the context instance already contains valid derived
values. This will be the case if you have already executed a DEMAND statement for that instance
and not changed the key values in a SUPPLY statement since then. If the instance contains valid
values, they are transferred to the corresponding program fields.

2.) If the context instance does not contain valid derived values, the system generates them. To do
this, it searches first of all in the context buffer for entries with the same key fields as the context
instance. If this is the case, the system transfers the values from the buffer to the context instance
and from there into the corresponding program fields.

3.) If the buffer does not contain the required values, the system derives the values itself according to
the context definition. During this process, it searches in the context buffer for intermediate results,
attempting to minimize the number of database accesses. When it has calculated the values, they are
stored in the context buffer, passed to the instance, and assigned to the corresponding program
fields.

4.) If the system cannot calculate all of the derived values, it stops processing, initializes the
program fields, and, if you have stored a message for that module, displays it. You can control
message handling in the program using the MESSAGES option.

(C) SAP AG BC411 7-13


Retrieving Data from a Context Instance II
DEMAND: <val1> = <f1> ... <valn> = <fn> FROM CONTEXT <instance>
[MESSAGES INTO <itab>].

REPORT sapbc411d_context_geogr_info.
CONTEXTS: geogr_infox.
TYPES: context_typ TYPE context_t_geogr_infox.
DATA: city_from TYPE contex_typ-city,
city_to TYPE context_typ-city,
distance TYPE context_typ-distance.
DATA: geogr_information_inst TYPE context_geogr_information.

SUPPLY city = 'FRANKFURT'


country = 'DE'
city_1 = 'NEW YORK'
country_1 = 'US'
TO CONTEXT geogr_information_inst.
DEMAND city = city_from
city_1 = city_to
distance = distance
FROM CONTEXT geogr_information_inst.
Write: / city_from, city_to, distance.
R

© SAP AG

The DEMAND statement fills the program fields <fn> with the derived values <valn> of context
instance <instance> using the process described on the previous page.
Tip: Both the SUPPLY and DEMAND statements are very economical, so reusing them is no
problem. In particular, you should always:

- Use a SUPPLY statement as soon as you assign values to the relevant key fields. This reduces
the
danger of the DEMAND statement deriving obsolete data. You do not have to check yourself
whether the key fields have changed, since the system does this automatically in each SUPPLY
statement.

- Use a DEMAND statement directly before using the derived fields. In this way, you can be sure
that you are using the right fields. This is a performance advantage in itself.

- Use local data objects as the target fields for the DEMAND statement. This also reduces the
danger
of inadvertently using obsolete values.

(C) SAP AG BC411 7-14


Message Handling in Contexts: System

REPORT sapbc411d_context_geogr_distan.
DATA: distance TYPE p.
...
CONTEXTS geogr_information.
DATA: geogr_information_inst TYPE context_geogr_information.

SUPPLY city = 'XX'


country = 'DE'
city_1 = 'NEW YORK'
country_1 = 'USA'
TO CONTEXT geogr_information_inst. Message displayed by context
DEMAND distance = distance
FROM CONTEXT geogr_information_inst.
WRITE: distance.

E No entries found for key XX DE

© SAP AG

If a context cannot derive the required data when you execute a DEMAND statement, you can force
it to send a user message.
The message handling depends on the modules in which the data retrieval failed. It is based on the
following:
For table modules, the message attributes specified in the Context Builder.
For function modules, exception handling in the function module using MESSAGE …
RAISING or RAISE.
Contexts as modules can always be traced back to tables or function modules.
If you want the system to be responsible for message handling, use the basic form of the DEMAND
statement without the MESSAGES addition.
For table modules, the system reacts as though there were a MESSAGE statement after the
DEMAND statement, containing the attributes (ID, number) specified for the module in the
Context Builder.
For function modules, the MESSAGE … RAISING statement in the function module is
executed. If the function module only contains a RAISE statement, a runtime error occurs.

(C) SAP AG BC411 7-15


Message Handling in Contexts: Program

REPORT sapbc411d_context_geogr_info.

DATA: itab LIKE symsg OCCURS 0 WITH HEADER LINE.


CONTEXTS c_geogr_information.
DATA: geogr_information_inst TYPE context_c_geogr_information.
DATA: distance TYPE context_t_geogr_information.

SUPPLY city = 'XX'


Messages displayed by system
country = 'DE'
city1 = 'NEW YORK'
country1 = 'USA'
TO CONTEXT geogr_information_inst. E BCTRAIN 007 XX DE
DEMAND distance = distance
FROM CONTEXT geogr_information_inst
MESSAGES INTO itab.
WRITE: / distance.
LOOP AT itab.
WRITE: / itab-msgty, itab-msgid, itab-msgno,
itab-msgv1, itab-msgv2.
ENDLOOP
R

© SAP AG

If you want to control message handling in your program, use the MESSAGES addition with the
DEMAND statement. The system then clears the table specified in the MESSAGES addition (itab in
the example) and fills it with any messages that occur while the context is being processed. These
message are not displayed to the user, and the system does not react to their type (for example, by
terminating the program in the case of an 'A' message). The messages in the internal table can then
be processed later in the program.
This is, for example, important when you want to make input fields on a screen ready for further
input following the error, since you must include these fields in your message handling (FIELD
statement in screen flow logic, or AT SELECTION-SCREEN event for selection screens).
If there are messages in the message table following the DEMAND statement, SY-SUBRC is
unequal to 0.

(C) SAP AG BC411 7-16


Clearing the Context Buffer

REPORT ....
DATA: context_name LIKE rs33f-frmid.
context_name = 'DOCU_TEST1'.
...
CALL FUNCTION 'UPDATE_...' IN UPDATE TASK
EXPORTING ...
IMPORTING ...
...
CALL FUNCTION 'CONTEXT_BUFFER_DELETE' IN UPDATE TASK
EXPORTING
context_id= context_name
EXCEPTIONS
OTHERS = 0.
...
COMMIT WORK.

© SAP AG

You can clear a context buffer on the current application server using the function module
CONTEXT_BUFFER_DELETE_LOCAL, and on all application servers using the function module
CONTEXT_BUFFER_DELETE. You can use these function modules when you make database
changes to ensure that the buffer contents are always up to date.
In the above example, the function module is called as the last step in the update task before the
COMMIT WORK.
You can delete the buffer contents either on the current application server or on all application
servers from within the Context Builder.
As a rule, contexts should only contain tables whose contents are still usable after one hour.
You can deactivate the context buffer for testing Customizing settings.

(C) SAP AG BC411 7-17


Creating and Maintaining Contexts

Context:
Context: DEMO_CITIES
DEMO_CITIES
Felder
Fields Modules
Name Reference field/type Name Type Table/mod. Text
DISTANCE CDEMOC Geograp
CITY1 SGEOCITY- CITY
SGEOCITY1 SGEOCITY Geograp
COUNTRY1 SGEOCITY- COUNTRY
SGEOCITY2 SGEOCITY Geograp
CITY2 SGEOCITY- CITY
COUNTRY2 SGEOCITY- COUNTRY
LONGITUDE1 SGEOCITY- LONGITUDE
LATITUDE1 SGEOCITY- LATITUDE
LONGITUDE2 SGEOCITY- LONGITUDE
LATITUDE2 SGEOCITY- LATITUDE Module SGEOCITY1
DISTANCE SPFLI-DISTANCE
Parameters I/O Field name Text
CITY CITY1 City1
COUNTRY COUNTRY1 Ctry1
LONGITUDE LATITUDE1 Long1
LATITUDE LONGITUDE1 Lat1

© SAP AG

You create and maintain contexts using the Context Builder (choose Development → Context
Builder from the initial screen of the ABAP Workbench).
Once you have entered the name of your context, you must maintain its attributes, namely a title, the
application, and the development class. When you choose Save, the context editor appears. This
contains three tables in which you can enter the fields and modules in your context, and maintain the
interfaces of the individual modules.
The three tables are all interdependent, and are partially filled by the system.
When you enter a module (table, view, function module, or another context), the system
automatically enters its input and output fields in the Fields table. It also proposes default names for
the fields, but you can change these if you wish. Equally, you do not have to use all of the fields.
All fields must have a reference to the ABAP Dictionary.
If you enter a table module, you can specify a message for the system to use in error handling.
To display the interface of a module, double-click its name in the Modules list.

(C) SAP AG BC411 7-18


Summary I

In this unit you have learned that contexts are


ABAP Workbench objects that store the
relationships between data, but not the data itself.
You have learned that you can use contexts to:
Remove processing logic from application programs, in order
to
Reduce complexity
Make souce code reusable
Improve the performance of application programs thanks to
context buffering
You have learned how to create and maintain
contexts, and about the different buffering types
(permanent, temporary, none).

© SAP AG

(C) SAP AG BC411 7-19


Summary II

You have learned the statements used to declare


contexts in programs (CONTEXTS), to provide a
context instance with values (SUPPLY), and to
retrieve data from a context instance (DEMAND)
You know how messages are handled in contexts
You know how to create or maintain a context

© SAP AG

(C) SAP AG BC411 7-20


ABAP Open SQL: Inhalt

Performance of business transactions


R/3 and DBMS architecture
SQL
Efficient database programming in ABAP
ABAP Open SQL features
ABAP Open SQL programming rules

© SAP AG
Unit Objectives

At the end of this unit, you will be able to


List the principal components of the R/3
System and DBMS architectures
Decide when it is appropriate to use Native
SQL
Understand and apply the most important
functions of ABAP Open SQL and the rules
for efficient database programming

© SAP AG

(C) SAP AG BC411 8-2


ABAP Open SQL: Overview

Business transaction
performance

R/3 and DBMS architecture

SQL

Efficient ABAP
database programming

© SAP AG

(C) SAP AG BC411 8-3


Business Transaction Performance

General rule:
The performance of business transactions is
determined by their database access times.

database
application
GUI

© SAP AG

The performance of business transactions is largely determined by their database access times. For
this reason, it may well be worth analyzing the SQL statements that you use. To find out if there is
an advantage to be gained from this, look at the runtime analysis (Transaction SE30) for your
program. This displays the runtime of ABAP statements, system requirements, and database access.
To understand the factors that influence the runtime of your database statements, you need to
understand the underlying architecture of the R/3 System.
The following pages illustrate the architecture of the R/3 System and that of a database management
system (DBMS).

(C) SAP AG BC411 8-4


ABAP Open SQL: Overview

Business transaction
performance

R/3 and DBMS architecture

SQL

Efficient ABAP
database programming

© SAP AG

(C) SAP AG BC411 8-5


R/3 Architecture
Central database
(saves all data and
application programs)
Data transfer between database
DBMS DB
and application server processes cache

Database server

Communication WP Local
with user data ...
Application server

Presentation server (workstation) R

© SAP AG

The R/3 System is based on a three-tier architecture containing the following layers:
Presentation layer - Use and SAPgui
Application layer - Application servers with work processes and local data
Database layer - Database management system (DBMS) with database, database processes,
and a database cache.
There is a database work process linked to each R/3 work process.

(C) SAP AG BC411 8-6


General DBMS Architecture
R/3 work process R/3 work process R/3 work process

Network
communication

DB work process DB work process DB work process

DB CPU
use
DB memory
use Database
Database cache service
processes

Physical I/O

Operating system

Database files R

© SAP AG

General DBMS architecture:


A database work process provides a service that database clients can call (the client in our case is
an R/3 work process).
There are different database services for different purposes (starting communications, changing
database tables, locking mechanism, archiving,…)
There is a large shared memory area containing the DBMS cache and other resources, such as the
statement cache and redo information.
The database files are stored on a hard disk and managed by the file system.
Within this architecture, there are four factors that affect performance:
Physical I/O, that is, reading from and writing to database files. This is the largest bottleneck in the
system. The mark of a well-configured system is the speed of its I/O access.
Memory use in the database cache.
CPU use on the database host. This is no problem with symmetrical multiprocessors (SMPs).
Network communication. Although this is not critical for small amounts of data, it can lead to
problems when larger data volumes are involved.
The next pages deal with these four points in further detail.

(C) SAP AG BC411 8-7


The Optimizer

Execution plan

Rule based

Cost based

© SAP AG

All database systems have an optimizer, whose task it is to generate the execution plan for an SQL
statement (for example, index or table scan). There are two kinds of optimizers:
A rule-based optimizer analyzes the structure of an SQL statement (mainly the SELECT and
WHERE clauses without values), and the index of the table(s) involved. It then uses a set of analysis
rules to decide the most appropriate procedure for executing the statement.
A cost-based optimizer also analyzes some of the values in the WHERE clause and the table
statistics. The statistics contain low and high values for the fields, or, in some cases, a histogram of
the distribution of the data in the table.
Cost-based optimizers use more information about the table, and usually produce faster access. One
of the disadvantages is that the statistics must be periodically updated.
ORACLE databases up to and including Release 7.1 use a rule-based optimizer. From Release 7.2
(R/3 Release 4.0A), they use a cost-based optimizer.
All other database systems use a cost-based optimizer.

(C) SAP AG BC411 8-8


ABAP Open SQL: Overview

Business transaction
performance

R/3 and DBSM architecture

SQL

Efficient ABAP
database programming

© SAP AG

(C) SAP AG BC411 8-9


ABAP SQL

SQL

Open
Open SQL
SQL Native
Native SQL
SQL

DB interface
Embedded SQL

Database

© SAP AG

ABAP contains a set of database statements known as ABAP Open SQL. These are all similar to
Standard SQL statements. ABAP Open SQL has the following characteristics:
Its syntax is the same as that of Standard SQL
It is a subset of Standard SQL
It contains both shortened and extended forms
It ensures that ABAP programs are portable to any relational database management system
(RDBMS) supported by SAP. For this reason, you should always try to use it instead of Native SQL.

As well as Open SQL, you can use Native SQL statements. This is advisable in cases where Native
SQL is more efficient than Open SQL. However, if you use it to change database contents, you may
cause data inconsistencies, because Native SQL bypasses the SAP database interface. You must also
expect to encounter portability problems. If you do use Native SQL statements, it is better to place
them in includes.
SQL statements are passed to the database interface on the applciation server, where they are
converted into the relevant form for the database. The converted statements are then passed to the
database and are executed.

(C) SAP AG BC411 8-10


From SQL Statement to Result Set
Data to be transferred

Relevant data
SELECT - the search result -
clause

WHERE clause

Search area Data to be searched - only


restricted when the
FROM clause search uses an index

One or more tables

SELECT field1 field2 field3 field4


FROM ( table INNER JOIN table ON R

table~field1 = table~field1 )
WHERE ... AND field1 IN ('A','B','C') AND field3 LIKE 'T%'
© SAP AG

SQL is set-oriented. An SQL statement specifies a set of data required by an application.


The SELECT clause specifies the fields that you want to read (projection). Only those fields from
the table entries selected are transferred over the network to the application process.
The WHERE clause specifies a set of table entries that meet a particular condition. It specifies the
result set.
The search area is made up of the data entries that have to be searched to satisfy the query. This
area is not explicitly specified in the query, but is determined by the optimizer, based on the table
indexes.
If the search result is small, the search result and search area will, ideally, be identical.
For large search results (more than 20% of the table), using an index is only an extra burden.

(C) SAP AG BC411 8-11


Efficient ABAP Database Programming

Business transaction
performance

R/3 and DBMS architecture

SQL

Efficient ABAP
database programming

© SAP AG

(C) SAP AG BC411 8-12


Five Rules of Open SQL Programming

Five rules
DBMS-independent where possible

© SAP AG

(C) SAP AG BC411 8-13


Basis for the Five Rules

ORACLE
INFORMIX
ADABAS
DB2/400 (AS/400)
Microsoft SQL Server (MSS)

Not considered:
DB2/6000
DB2/MVS
R

ORACLE Parallel Server (OPS)


© SAP AG

The rules explained on the following pages are based on the following database management
systems:
ORACLE
INFORMIX
ADABAS
DB2/400 (uses EBCDIC code page)
Microsoft SQL Server

(C) SAP AG BC411 8-14


Rule 1

Keep the result set small

© SAP AG

The result set must be stored in the memory of the DBMS (not necessarily in a data packet) and
should therefore be as small as possible.
The projection of the result set must be transferred over the network to the application server.
Keeping the result set small thus reduces the load on the network.

(C) SAP AG BC411 8-15


Exercise: Read all Flights for a Year

Turn to the Exercises appendix for a


description of the task

© SAP AG

(C) SAP AG BC411 8-16


1. Keep the Result Set Small
Use a WHERE condition wherever possible

REPORT
REPORT sapbc411s_flights_of_one_year
sapbc411s_flights_of_one_year
PARAMETERS:
PARAMETERS: param1(4).
param1(4).
DATA:
DATA: BEGIN
BEGIN OF
OF search_string,
search_string,
param(4),
param(4),
rest
rest value
value '%',
'%',
END
END OF
OF search_string.
search_string.

SELECT
SELECT ** FROM
FROM sflight
sflight INTO
INTO wa_sflight.
wa_sflight.
CHECK
CHECK sflight-fldate(4)
sflight-fldate(4) == param1.
param1.
WRITE:
WRITE: // wa_sflight-carrid,
wa_sflight-carrid, wa_sflight-
wa_sflight-
connid,
connid, ...
... ENDSELECT.
ENDSELECT.

Instead, use

search_string-param
search_string-param == param1.
param1.
SELECT
SELECT ** FROM
FROM sflight
sflight INTO
INTO wa_sflight
wa_sflight WHERE
WHERE
fldate
fldate LIKE
LIKE search_string.
search_string.
WRITE:
WRITE: // wa_sflight-carrid,
wa_sflight-carrid, wa_sflight-
wa_sflight-
connid,
connid, ...
...
ENDSELECT.
ENDSELECT. R

Performance difference:SELECT * ... CHECK. ENDSELECT. 300,000 ms (400 entries)


SELECT ... WHERE . 3,700 ms
© SAP AG

Do not use the first version listed above. The system has to read the entire contents of the table,
place them in the DBMS cache, and transfer them over the network to the database interface. After
this, the program throws most of the data away.
Use the second version. Here, the DBMS only reads the data that is really required.
Rule: Specify all known conditions in the WHERE clause. The DBMS cannot optimize a statement
without one.
Exceptions: Retrieving data for all company codes...
Making a client copy...
Programming a utility function...

SELECT statements without a WHERE clause usually indicate a design error in your program,
especially when the SELECT applies to an SAP table that expands rapidly (such as BKPF, BSEG,
COBK, COEP, LIPK, MKPF, VBAK, VBAP).
Programs that address this kind of table perform well when your system first goes live, but the
runtime increases constantly with time, since the tables grow daily, and often considerably.
Hint: The runtime numbers in the examples above and in further examples depend on the database
system and the total number of records in the table.

(C) SAP AG BC411 8-17


Benefits of Rule 1

R/3 work process R/3 work process R/3 work process

Network
communication

DB work process DB work process DB work process

DB CPU
use
DB memory
use Database
Database cache service
processes

Physical I/O

Operating system

Database files R

© SAP AG

The benefits of observing rule 1 are that:


There are no more physical I/Os on the database than are really necessary.
No unneeded data is stored in the database cache, reducing the probability of existing data being
deleted from the cache.
The CPU use of the database host is minimized.
The network communication between the database and the R/3 work process is restricted to data that
is actually needed by the application.

(C) SAP AG BC411 8-18


Rule 2

Minimze the amount of data transferred


between the database and the application
server

© SAP AG

You can reduce the network communication between the DBMS and the application server still
further by using certain options in the SELECT clause.

(C) SAP AG BC411 8-19


Exercise: Reading the First 10 Flights

Turn to the Exercises appendix for a


description of the task

© SAP AG

(C) SAP AG BC411 8-20


2. Minimize Data Transfer I

Use data selectively


REPORT
REPORT sapbc411d_read_10_flights.
sapbc411d_read_10_flights.

SELECT
SELECT carrid
carrid connid
connid FROM
FROM sbook
sbook
WHERE
WHERE carrid
carrid == 'LH'
'LH'
INTO
INTO (wa-carrid,
(wa-carrid, wa-connid).
wa-connid).
IF
IF sy-dbcnt
sy-dbcnt >> 10.
10.
EXIT.
EXIT.
ENDIF.
ENDIF.
WRITE:
WRITE: // wa-carrid,
wa-carrid, wa-connid.
wa-connid.
ENDSELECT.
ENDSELECT.
Instead, use

SELECT
SELECT carrid
carrid connid
connid FROM
FROM sbook
sbook INTO
INTO wa
wa
UP
UP TO
TO 10
10 ROWS
ROWS WHERE
WHERE carrid
carrid == 'LH'.
'LH'.
WRITE:
WRITE: // wa-carrid,
wa-carrid, wa-connid,
wa-connid, ...
...
ENDSELECT.
ENDSELECT.

Performance difference: SELECT column... EXIT. ENDSELECT. 300,000 ms


SELECT column ... UP TO 10 ROWS. 34,000 ms
R

© SAP AG

In the first version, the processing is ended by the program after the tenth entry. However, the
database has already read the first 32K of the table SBOOK (175 entries) and transferred the entries
to the database interface.
In the second version, the UP TO 10 ROWS addition ensures that only the first ten entries are read
and transferred from the database to the database interface.

(C) SAP AG BC411 8-21


2. Minimize Data Transfer

Field list or SELECT * ?


REPORT
REPORT sapbc411d_select_fieldlist.
sapbc411d_select_fieldlist.

TABLES:
TABLES: SBOOK.
SBOOK.
SELECT
SELECT ** FROM
FROM sbook
sbook
WHERE
WHERE carrid
carrid ne
ne 'BA'.
'BA'.
WRITE:
WRITE: // wa-carrid,
wa-carrid, wa-connid
wa-connid
ENDSELECT.
ENDSELECT.

Instead, use

SELECT
SELECT customid
customid class
class FROM
FROM sbook
sbook
INTO
INTO (wa-carrid,
(wa-carrid, wa-connid)
wa-connid)
WHERE
WHERE carrid
carrid ne
ne 'BA'.
'BA'.
WRITE:
WRITE: // wa-customid,
wa-customid, wa-class,
wa-class, ...
...
ENDSELECT.
ENDSELECT.

Performance difference: SELECT column... . ENDSELECT. 2.2 sec (21500 entries)


SELECT * ... ENDSELECT. 6.7 sec R

© SAP AG

(C) SAP AG BC411 8-22


Client/Server Architecture and ABAP Runtime I

Appl.
Appl.
server Database
server
SELECT * FROM SBOOK
REPORT XYZ

Appl.
Appl.
server

Report result Data transfer from


DB server to appl. server

10000 SBOOK records of


97 bytes each require 30
transfers of 32K packets
from the database server R

to the application server

© SAP AG

Each entry in the table SBOOK is 97 bytes long. If you want to read 10,000 entries from the
database, you need to transfer 970,000 bytes from the database to the application server.
The database server and application servers communicate using packets of up to 32,000 bytes
(depending on the network and communication hardware).
This means that you would need around 30 transfers (970,000 / 32,000) for the 10,000 SBOOK
entries.

(C) SAP AG BC411 8-23


Client/Server Architecture and ABAP Runtime II

Appl.
server Database
server
SELECT COL1 FROM SBOOK
REPORT XYZ

Appl.
server

Report result Data transfer from DB


server to application server

10000 SBOOK entries of


97 bytes each requires 30
transfers of 32K packets
from the database server R

to the application server

© SAP AG

By only reading the database fields that you actually need, you reduce the amount of data tranferred
and the corresponding network load.
If you only read the fields booking number (CUSTOMID) and flight class (CLASS), you only need to
transport 90,000 bytes (9 * 10,000), which only requires three packets. You thus save 27 packets of
32,000 bytes each (384,000 bytes) that no longer have to be transported.
Naturally, the real figures differ from those quoted here. The SQL Trace for this operation shows 22
and 4 transfers respectively. The difference is caused by the adminsitration information that also has
to be transported.
Note: The disadvantages of the SELECT list are that you cannot use it with generic functions, and
you have to adjust it if you change the definition of the table in the ABAP Dictionary.

(C) SAP AG BC411 8-24


2. Minimize Data Transfer II

Referencing table fields


REPORT
REPORT sapbc411d_update_set.
sapbc411d_update_set.
DATA:
DATA: wa_sflight
wa_sflight like
like sflight.
sflight.

SELECT
SELECT ** INTO
INTO wa_sflight
wa_sflight FROM
FROM sflight
sflight
WHERE
WHERE carrid
carrid ='LH'.
='LH'.
wa_sflight-seatsocc
wa_sflight-seatsocc == wa_sflight-seatsocc
wa_sflight-seatsocc ++ 1.
1.
UPDATE
UPDATE sflight
sflight from
from wa_sflight.
wa_sflight.
ENDSELECT.
ENDSELECT.

Instead,
Instead, use
use

REPORT
REPORT sapbc411d_update_set.
sapbc411d_update_set.

UPDATE
UPDATE sflight
sflight SET
SET seatsocc
seatsocc == seatsocc
seatsocc ++ 11
WHERE
WHERE carrid
carrid == 'LH'.
'LH'.

Performance difference: SELECT * ... ENDSELECT. 500,000 ms (100 entries)


R

UPDATE ... SET ... 56,700 ms

© SAP AG

Both of the above examples update a field whose value has increased. In the first version, all data
records that satisfy the WHERE condition are read from the database, transferred to the database,
and then transferred back again.
In the second version, only the statement is sent to the database (no data is transferred). You should
use this variant wherever possible. However, it only supports the following simple operations:
field = value
field = field + value
field = field - value
where value is an ABAP field or a field from the same row of the database table.
You can only use the last two variants with numeric fields.

(C) SAP AG BC411 8-25


Exercise: Summation

Turn to the Exercises appendix for a


description of the task

© SAP AG

(C) SAP AG BC411 8-26


2. Minimize Data Transfer 4
Use aggregate functions
COUNT, SUM, MAX, MIN, AVG
REPORT
REPORT sapbc411d_cumulate_loccuram.
sapbc411d_cumulate_loccuram.
...
...
SUM
SUM == 0.
0.
SELECT
SELECT loccuram
loccuram FROM
FROM sbook
sbook into
into wa_sbook
wa_sbook
WHERE
WHERE fldate
fldate like
like '1998%'.
'1998%'.
SUM
SUM == SUM
SUM ++ wa_sbook-loccuram.
wa_sbook-loccuram.
ENDSELECT.
ENDSELECT.
WRITE:
WRITE: // sum.
sum.

Instead,
Instead, use
use

SELECT
SELECT sum(
sum( loccuram
loccuram )) INTO
INTO (sum)
(sum) FROM
FROM sbook
sbook
WHERE
WHERE fldate
fldate LIKE
LIKE '1998%'.
'1998%'.
WRITE:
WRITE: // sum.
sum.

Performance difference: SELECT ... sum = sum + ... ENDSELECT. 3.6 sec (21500 entries)
SELECT sum ( price ) INTO 1.1 sec
© SAP AG

You can use the following aggregate functions in a SELECT statement:


COUNT, SUM, MAX, MIN, and AVG. These functions allow you to summarize one or more
columns of a database table in your result set.
In the first version above, all of the flight entries are read from the database, and the sum is
calculated on the application server.
In the second version, the sum is calculated in the database, and only the result (a single value) is
transported to the application server.

(C) SAP AG BC411 8-27


2. Minimize Data Transfer 5

Aggregate functions III - Differences

Database may approximate differently from the ABAP


runtime system
Databases use null values, ABAP does not
AVG (1, 3, 0, 0) = 1
AVG (1, 3, null, null) = 2

Use the correct data type for the target field


Use type 'F' (floating point) for the AVG function
For the SUM function, use a data type that can store numbers large
enough to avoid an arithmetic overflow
R

© SAP AG

Unlike the ABAP runtime system, database do not use NULL values. A NULL value in the database
means that a fields has not contents. ABAP does not include NULL values in SY-DBCNT, and
conesequently, they are not included in AVG calculations.
Always use a type F field for the result of an AVG calculation, since the result invariably contains
decimals.

(C) SAP AG BC411 8-28


Benefits of Rule 2

R/3 work process R/3 work process R/3 work process

Network
communication

DB work process DB work process DB work process

DB CPU
use
DB memory
use Database
Database cache service
processes

Physical I/O

Operating system

Database files R

© SAP AG

The benefit of observing rule 2 is that:


Only the data required by the application is transferred over the network from the database to the
application server.

(C) SAP AG BC411 8-29


Rule 3

Minimize the number of


transfers between database
and application

© SAP AG

It is usually more effective to retrieve data from the database all at once rather than accessing it
several times, since each database access incurs an overhead.

(C) SAP AG BC411 8-30


3. Minimize the Number of Transfers 1

Use array operations - INSERT

REPORT
REPORT ...
...
LOOP
LOOP AT
AT itab.
itab.
INSERT
INSERT INTO
INTO dbtab
dbtab VALUES
VALUES itab.
itab.
ENDLOOP.
ENDLOOP.

Instead,
Instead, use
use

REPORT
REPORT ...
...
INSERT
INSERT dbtab
dbtab FROM
FROM TABLE
TABLE itab
itab
ACCEPTING
ACCEPTING DUPLICATE
DUPLICATE KEYS.
KEYS.
IF
IF sy-subrc
sy-subrc == 4.
4.
...
... Error
Error handling
handling ...
...
ENDIF.
ENDIF.

© SAP AG

To insert several entries into a database table, use the variant INSERT … FROM TABLE.
In the first version shown above, the application passes single entries to the database to be added to
the table.
In the second version, the entire internal table itab is passed to the database and processed in a single
operation.
If you suspect that some of the entries in itab already exist in the database (duplicate keys), you can
use the ACCEPTING DUPLICATE KEYS addition. This ensures that the INSERT statement does
not terminate when a duplicate key occurs. Instead, it sets SY-SUBRC to a value unequal to zero. In
the simplest case, you would not react to the error. If, on the other hand, you want to ensure that all
of the entries are inserted in the database table, use the statement UPDATE dbtab FROM TABLE
itab.

(C) SAP AG BC411 8-31


Exercise: Reading from More than One Table

Turn to the Exercises appendix for a


description of the task

© SAP AG

(C) SAP AG BC411 8-32


3. Minimize the Number of Transfers 2

Use joins
Joins implemented as SELECT * FROM t1 WHERE ...

views in the ABAP Dictionary SELECT * FROM t2 WHERE ...


SELECT * FROM t3 WHERE ...
SELECT * FROM t4 WHERE ...
SELECT * FROM t5 WHERE ...
Joins in ABAP Open SQL ...
ENDSELECT.
ENDSELECT.
ENDSELECT.
SELECT * FROM t6 WHERE ...
SELECT * FROM t7 WHERE ...
SELECT * FROM t8 WHERE ...
...
ENDSELECT.
ENDSELECT.
ENDSELECT.
ENDSELECT.
ENDSELECT.

© SAP AG

If you use nested SELECT statements, you must expect an adverse effect on performance, especially
if the outer table contains a large number of entries. The inner SELECT statement is processed in
each loop pass of the outer SELECT statement. Using other techniques also means that less data has
to be transferred from the database to the application server.
Insetad of nested SELECT statements, use one of the techniques listed above to read from more than
one database table.
Database views and joins in ABAP Open SQL are covered in this unit.
For more information about FOR ALL ENTRIES and cursor management, refer to the appendix.

(C) SAP AG BC411 8-33


3. Minimize the Number of Transfers 3
ABAP Dictionary view
REPORT
REPORT sapbc411d_select_view.
sapbc411d_select_view.
SELECT
SELECT ** FROM
FROM sflight.
sflight.
WRITE:
WRITE: // sflight-carrid,...
sflight-carrid,...
SELECT
SELECT ** FROM
FROM sbook
sbook WHERE
WHERE carrid
carrid == sflight-carrid
sflight-carrid
AND
AND connid
connid == sflight-connid
sflight-connid
AND
AND fldate
fldate == sflight-fldate.
sflight-fldate.
IF
IF SY_SUBRC
SY_SUBRC NE
NE 0.
0.
WRITE:
WRITE: sbook-bookid,...
sbook-bookid,...
ENDIF.
ENDIF.
ENDSELECT.
ENDSELECT.
ENDSELECT.
ENDSELECT.

Instead, use

SELECT
SELECT **FROM
FROM sflightsbookview.
sflightsbookview.
*View
*View in
inABAP
ABAP Dictionary
Dictionary
WRITE:
WRITE: // sflightsbookview-price,
sflightsbookview-price,
sflightsbookview-paymentsum,
sflightsbookview-paymentsum, ...
...
ENDSELECT.
ENDSELECT.
R

© SAP AG

To use the technique illustrated in the second example, you must first create a view in the ABAP
Dictionary.
This technique has the following advantages:
-You can use the view in other programs.
-Fields common to both tables (join fields) are only transferred from the database to the
applicatino server once.
-The view is implemented in the ABAP Dictionary as an inner join. This means that no data
is transferred if the inner table contains no entries that correspond to the outer table. This is
not always desirable: For example, if you are reading from a text table, it is not acceptable
for nothing to appear in the join result just because a text entry does not exist in a particular
language. In this case, use a left outer join.
-The link between the tables in the join is made by the DBMS and can therefore be
optimized.
-Like database tables, you can buffer views (technical settings).
-The buffering rules are the same as for tables. This means that you should buffer mainly for
read access. This reduces the volume of network access to the database table as well as the
number of accesses to the database files (see table buffering).

(C) SAP AG BC411 8-34


3. Minimize the Number of Transfers 4
Inner join in the FROM clause
SELECT <fieldlist> INTO <target>
FROM <dbtab1> [AS <alias1>]
INNER JOIN <dbtab2> [AS <alias2>]
ON <alias1>~<dbtab1-field1> = <alias2>~<dbtab2-field1>
AND <alias1>~<dbtab1-field2> = <alias2>~<dbtab2-field2>
AND ...
WHERE ...
...
ENDSELECT.

REPORT
REPORT sapbc411d_select_view.
sapbc411d_select_view.
SELECT
SELECT f~carrid
f~carrid f~connid
f~connid ...
... INTO
INTO (sflight-carrid,
(sflight-carrid, ...)
...)
FROM
FROM sflight
sflight AS
AS ff INNER
INNER JOIN
JOIN sbook
sbook AS
AS bb
ON
ON f~carrid
f~carrid == b~carrid
b~carrid
AND
AND f~connid
f~connid == b~connid
b~connid
AND
AND f~fldate
f~fldate == b~fldate.
b~fldate.
WRITE:
WRITE: // sflight-price,
sflight-price, sflight-paymentsum,
sflight-paymentsum, ...
...
ENDSELECT.
ENDSELECT.
R

© SAP AG

You can also read from more than one table using an inner join in the FROM clause of your
SELECT statement.
The above example repeats the example from the last page, and reads bookings from table SBOOK
for flights in table SFLIGHT.
If the field list contains field names that occur in both tables of the inner join, you must differentiate
them by preceding them with an alias name followed by a tilde. You can use the table name as the
alias name. You specify the alias name in the FROM clause using the AS <aliasname> construction.
As well as being written simply, joins have the advantage that only one statement is executed in the
database. However, they have the disadvantage that redudant data from the outer table appears in the
result set if there is a 1:n relationship between the outer and inner tables. This can considerably
increase the amount of data transferred from the database. For this reason, you should use a field list
with a join to identify only those fields that you really need.
The runtime of a join statement is highly dependent on the database optimzer, especially when the
join involves more than two tables. However, it is usually in any case quicker than using nested
SELECT statements.

(C) SAP AG BC411 8-35


3. Minimize the Number of Transfers 5
Inner join
SFLIGHT: SBOOK:
CARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID

AA 00170 2,572 AA 00170 1


LH 40004 6,658 AA 017 2
LH 02 3,162 AA ... ...
QF 0598 1,689 QF 0598 10
... ... ... ... ... ...
Join condition

Join result table in the database


CARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID
Note:
AA 0017 2,572 AA 0017 1 The result set contains
AA 0017 2,572 AA 0017 2 no entries for airline
LH.
AA 0017 2,572 AA ... ... ... R

QF 0598 1,689 QF 0598 10


© SAP AG

In an inner join, the system creates a temorary table containing all of the combinations of lines from
table SFLIGHT and SBOOK whose values meet the logical condition (join condition) specified in
the ON <condition> clause. The system then applies the WHERE condition to this set, the result of
which is the actual result set. To make the above table easier to understand, it is assumed that the two
tables are linked by the CARRID field.
The result of the inner join is the same, regardless of whether the condition occurs in the ON or in
the WHERE clause. However, you cannot have an empty ON clause.
You cannot use an INNER JOIN for pool or cluster tables.
Inner joins always bypass the table buffer and read directly from the database. For this reason, it is
better to use a view from the ABAP Dictionary when accessing tables that are mostly only read.

(C) SAP AG BC411 8-36


3. Minimize the Number of Transfers 6

Left outer join in the FROM clause


SELECT <f1>...<fn> INTO <wa>
FROM <dbtab1> [AS <alias1>]
LEFT [OUTER] JOIN <dbtab2> [AS <alias2>]
ON <alias1>~<dbtab1-field1> = <alias2>~<dbtab2-field1>
AND <alias1>~<dbtab1-field2> = <alias2>~<dbtab2-field2>
AND ...
WHERE ...
... "Do something
ENDSELECT.

REPORT
REPORT sapbc411d_select_view.
sapbc411d_select_view.
...
...
SELECT
SELECT f~carrid
f~carrid f~connid
f~connid ...
... INTO
INTO (sflight-carrid,
(sflight-carrid, ...)
...)
FROM
FROM sflight
sflight AS
AS ff LEFT
LEFT OUTER
OUTER JOIN
JOIN sbook
sbook AS
AS bb
ON
ON f~carrid
f~carrid == b~carrid
b~carrid
AND
AND f~connid
f~connid == b~connid
b~connid
AND
AND f~fldate
f~fldate == b~fldate
b~fldate
WHERE
WHERE f~fldate
f~fldate == '19981119'.
'19981119'.
WRITE:
WRITE: // sflight-price,
sflight-price, sflight-paymentsum,
sflight-paymentsum, ...
... R

ENDSELECT.
ENDSELECT.

© SAP AG

In a left outer join, an entry appears in the join result, even if there is no corresponding entry in the
other table.

(C) SAP AG BC411 8-37


3. Minimize the Number of Transfers 7
Left outer join
SFLIGHT: SBOOK:
CARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID

AA 00170 2,572 AA 00170 1


LH 40004 6,658 AA 017 2
LH 02 3,162 AA ... ...
QF 0598 1,689 QF 0598 10
... ... ... ... ... ...
Join condition

Join result table in the database


CARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID Note:
The result set
AA 0017 ... 2,572 AA 0017 ... 1 always contains
the entire outer
AA 0017 ... 2,572 AA 0017 ... 2
table
AA 0017 ... 2,572 AA ... ... ... R

LH 0400 ... 6,658 NULL NULL ... NULL


© SAP AG

The left outer join contains all combinations of lines from the tables SFLIGHT and SBOOK whose
values meet the join condition specified as ON <condition> (just as in the inner join). The lines in the
left-hand table SFLIGHT that do not meet the condition are then added to the join table, and the
fields from the right-hand table are filled with NULL values. Thus the result set contains all of the
entries from the left-hand table. The WHERE condition is then applied to this temporary table,
eliminating any unwanted entries from the result set.
Certain restrictions have been applied to the left outer join to ensure that the result set of a given join
is always the same on all of the database platforms supported by SAP. For example, you may not
specify conditions for the right-hand table in the WHERE condition. For further information, refer to
the keyword documentation in the ABAP Editor for FROM.

(C) SAP AG BC411 8-38


Exercise: Reading Maximum and Minimum Values

Turn to the Exercises appendix for a


description of the task

© SAP AG

(C) SAP AG BC411 8-39


3. Minimize the Number of Transfers 8
Subquery in the WHERE clause
REPORT
REPORT sapbc411s_select_subquery.
sapbc411s_select_subquery.
DATA:
DATA: ff LIKE
LIKE sflight,
sflight, f1
f1 LIKE
LIKE sflight.
sflight.
SELECT
SELECT carrid
carrid connid
connid fldate
fldate max(
max( seatsocc
seatsocc )FROM
)FROM sflight
sflight
INTO
INTO (f-carrid,f-connid,
(f-carrid,f-connid, f-fldate,
f-fldate, f-seatsocc)
f-seatsocc)
GROUP
GROUP BY
BY by
by carrid
carrid connid
connid
ORDER
ORDER BY
BY carrid
carrid connid.
connid.
SELECT
SELECT carrid
carrid connid
connid fldate
fldate FROM
FROM sflight
sflight
INTO
INTO (f1-carrid,
(f1-carrid, f1-connid,
f1-connid, f1-fldate)
f1-fldate)
WHERE
WHERE carrid
carrid == f-carrid
f-carrid
AND
AND connid
connid == f-connid
f-connid
AND
AND seatsocc
seatsocc == f-seatsocc.
f-seatsocc.
WRITE:
WRITE: // f1-carrid,
f1-carrid, f1-connid,
f1-connid, f1-fldate,
f1-fldate, f-seatsocc.
f-seatsocc.
ENDSELECT.
ENDSELECT.
ENDSELECT.
ENDSELECT.
SELECT
SELECT carrid
carrid connid
connid fldate
fldate seatsocc
seatsocc
INTO
INTO (f-carrid,
(f-carrid, f-connid,
f-connid, f-fldate,
f-fldate, f-seatsocc)
f-seatsocc)
FROM
FROM sflight
sflight AS
AS ff
WHERE
WHERE seatsocc
seatsocc IN
IN
(( SELECT
SELECT MAX(
MAX( seatsocc
seatsocc )) FROM
FROM sflight
sflight
WHERE
WHERE carrid
carrid == f~carrid
f~carrid AND
AND CONNID
CONNID == f~connid
f~connid
ORDER
ORDER BY
BY carrid
carrid connid
connid fldate.
fldate. )) R

WRITE:
WRITE: sflight-carrid,
sflight-carrid, sflight-connid,...
sflight-connid,...
ENDSELECT.
ENDSELECT.
© SAP AG

A subquery is a SELECT statement within a SELECT statement, specified in the WHERE condition
to check whether data from a database table or view meets certain conditions.
It provides a very elegant, very efficient way of programming complex database queries.
The SELECT statement in the WHERE clause is subject to a restricted syntax
SELECT <result> FROM <source> WHERE <condition> [group by field]. A dynamic WHERE
condition or dynamic specification of the table name are not supported in Release 4.0B.

(C) SAP AG BC411 8-40


Exercise: Reading Grouped Data with
Conditions

Turn to the Exercises appendix for a


description of the task

© SAP AG

(C) SAP AG BC411 8-41


3. Minimize the Number of Transfers 9

Having Clause
REPORT sapbc411s_select_having.

SELECT connid fldate count(*) AVG( luggweight )


INTO (connid, fldate, count, avg) FROM sbook
GROUP BY connid fldate WHERE carrid = 'LH'
AND fldate > '19981201'
CHECK avg > 20.
...
ENDSELECT.

SELECT connid fldate count(*) AVG( luggweight )


INTO (connid, fldate, avg) FROM sbook
WHERE carrid = 'LH' AND fldate > '19981201'
GROUP BY connid fldate
HAVING AVG( luggweight ) > 20.
...
ENDSELECT.
R

© SAP AG

In the first example above, the system reads all of the table entries that meet the WHERE condition
and transfers them from the database to the application server to process them further.
The second example uses a HAVING clause. This allows you to apply a logical condition to the
groups defined in the GROUP BY clause. In this way, the result set is selected fully in the database,
considerably reducing the amount of data transferred over the network.

(C) SAP AG BC411 8-42


Benefits of Rule 3

R/3 work process R/3 work process R/3 work process

Network
communication

DB work process DB work process DB work process

DB CPU
use
DB memory
use Database
Database cache service
processes

Physical I/O

Operating system

Database files R

© SAP AG

The benefits of observing rule 3 are that:


The number of data transfers between the database and application server, and thus the network load,
is minimized.
The number of PREPARE and REOPEN operations in the database is reduced, leading to less CPU
use (especially when you avoid using nested SELECT statements).

(C) SAP AG BC411 8-43


Rule 4

Minimize the search overhead

© SAP AG

As already explained at the beginning of this unit, the hit list is determined from the search area. The
search area is determined by the database optimizer, based on the database indexes and how they are
used.
You should always try to minimize the search area by formulating the WHERE condition as exactly
as possible and, if necessary, creating secondary indexes for database tables.

(C) SAP AG BC411 8-44


4. Minimize the Search Overhead 1
Tables and Indexes
Index A Tabelle Index B

Block 1
Satz 4

Satz 2

Block 2
Satz 5
Satz 1
Satz 6

Block 3
Satz 7

Satz 3 R

© SAP AG

General layout of tables and indexes :


Tables are partitioned into several blocks, each with a given size. A block normally contains
several table entries, although a single entry can also span more than one block if the table
structure is particularly wide.
You can construct table indexes including several fields (especially non-key fields), which
allow you to access your data more efficiently. A table may have more than one index. The
R/3 System automatically generates a primary index for each table, containing its key fields.
Any other indexes are known as secondary indexes, and are created separately by users.

The following terms are important when considering runtime:


Full table scan - The database reads every database entry to check which need to be selected.
Index range scan - The database only checks a part of the index.
Index unique scan - The database reads a single entry using the index.

(C) SAP AG BC411 8-45


4. Minimize the Search Overhead 2
General rule I

Use the 'EQ' operator as much as possible

SELECT
SELECT ** FROM
FROM sbook
sbook
WHERE
WHERE carrid
carrid == 'AA'
'AA'
AND
AND connid
connid == '0017'
'0017'
AND
AND fldate
fldate == '19981205'.
'19981205'.
...
... Processing...
Processing...
ENDSELECT.
ENDSELECT.

© SAP AG

The fields in the WHERE condition of the above example that use the EQ operator are the first three
key fields of table SBOOK. This allows the system to process the statement very quickly using the
primary index.
An index field can only be used to process a statement if all of the fields that precede it in the index
are specified using 'EQ' in the WHERE or ON condition. Statements that use the first n fields of an
index can be processed very quickly.
Note: The sequence of fields in the WHERE clause is irrelevant - it is their sequence in the index
that matters.

(C) SAP AG BC411 8-46


4. Minimize the Search Overhead 3
Use 'EQ' as often as possible
REPORT
REPORT sapbc411d_select_many_eq.
sapbc411d_select_many_eq.
SELECT
SELECT carrid
carrid connid
connid fldate
fldate bookid
bookid SBOOK key:
custtype
custtype orderdate
orderdate FROM
FROM sbook
sbook mandt
into
into ...
... carrid
WHERE
WHERE carrid
carrid == 'LH'
'LH'
AND
connid
AND fldate
fldate == '19981119'
'19981119'
AND
AND orderdate
orderdate == '19981118'.
'19981118'. fldate
...
... Processing ...
Processing ... bookid
ENDSELECT.
ENDSELECT.
SELECT
SELECT f~carrid
f~carrid f~connid
f~connid f~fldate
f~fldate b~bookid
b~bookid
b~custtype
b~custtype b~orderdate
b~orderdate INTO
INTO (carrid,
(carrid, connid,
connid,
fldate,
fldate, bookid, custtype) FROM sflight
bookid, custtype) FROM sflight AS
AS ff
INNER
INNER JOIN
JOIN sbook
sbook as
as bb
ON
ON f~carrid
f~carrid == b~carrid
b~carrid
AND
AND f~connid
f~connid == b~connid
b~connid
AND
AND f~fldate
f~fldate == b~fldate
b~fldate
WHERE
WHERE f~carrid
f~carrid == 'LH'
'LH'
AND
AND fldate
fldate == '19981119'
'19981119' AND
AND orderdate
orderdate == '19981118'.
'19981118'. R

...
... Processing
Processing ...
...
ENDSELECT.
ENDSELECT.
© SAP AG

In the first example, the WHERE conditition does not contain the second field of the primary index
(CONNID). This means that the primary index cannot be used effectively. The database can only use
the fields MANDT and CARRID, which are not particularly selective.
If a secondary index exists for the field ORDERDATE, a cost-based optimizer would recognize this as
a quicker option, since the ORDERDATE field is far more selective than the MANDT and CARRID
fields.
In the second example, the first three key fields of SBOOK are specified in the join condition,
allowing the database to use the first part of the primary index to access the data. This makes the
data selection far more selective, leading to shorter runtime.
You would only need to use the second example in situations where it is not possible to create a
suitable secondary index.

(C) SAP AG BC411 8-47


4. Minimize the Search Overhead 4

Key of table Mand Carrid Connid Fldate


SBOOK
1 2 3 4

Primary Mand Carrid Connid Fldate


index

Secondary Carrid Fldate Orderdate


index

© SAP AG

The system creates a primary index for every table in the database. This key corresponds to the
structure of the key fields in the table.
When using the primary index, the system analyzes all of the AND conditions. However, the fields
specified can only be used if they correspond to the structure of the index. For example, if you
include MANDT, CARRID, and FLDATE in the WHERE condition, a primary index search will only
use the fields MANDT and CARRID, since you have not specified the field CONNID.
If, on the other hand, you have created a secondary index with the above structure, a cost-based
optimizer would use it, recognizing that the ORDERDATE field is far more selective.

(C) SAP AG BC411 8-48


4. Minimize the Search Overhead 5
General rule II
Replace inner OR with an IN expression

f0
f0 == x1
x1 AND
AND (f1
(f1 == y1
y1 OROR
f1
f1 == y2
y2 OROR
f1
f1 == y3).
y3).

f0
f0 == x1
x1 AND
AND f1
f1 IN
IN (y1,
(y1, y2,
y2, y3).
y3).

© SAP AG

Some database optimizers do not process OR conditions, and cannot therefore use an index to
process field f1.
Instead, use the IN operator. The optimizer converts the entire expression into a set of 'EQ'
expressions, and can therefore use the index.

(C) SAP AG BC411 8-49


4. Minimize the Search Overhead 6
Index design
Selective fields at the beginning
non-selective: MANDT, BUKRS
very selective: BUCHUNGSNUMMER, BELNR, MATNR, KUNNR,

Small indexes
Avoid overlap (Disjunctive indexes)
Up to 3 indexes per table is OK
Avoid complex WHERE conditions with IN or OR
conditions for index fields
NOT conditions in the SELECT statement cannot be
processed using the index
R

Check how the system uses your indexes


© SAP AG

While table design follows a logical pattern, index design is subject to more technical
considerations. When you design a table, it is a good idea to place fields that represent an
organizational structure (client, company code…) at the beginning of the structure. When you design
an index, the opposite is true.
For an index to work efficiently, you need to place selective fields (for example, object number) at
the beginning. Client and company code are not very selective fields.
You should construct your index from as few fields as possible, since some optimizers can combine
two or more smaller indexes to process a query, but this does not work with large indexes.
Your table indexes should be as disjunctive as possible (that is, with as few common fields as
possible). The more similar your table indexes, the greater the possibility that the optimizer will
choose the wrong one.
Each index that you create makes it slower to insert entries in the table. Updates are slower if you
add index fields. For this reason, tables to which you often add data (transaction data tables) should
have as few indexes as possible. On the other hand, tables from which you normally only read can
have more indexes. As a rule, you should not experience problems with up to three indexes for a
table.
Complex conditions using IN and OR conditions cause the most problems for optimizers. Statements
including NOT conditions cannot be processed using an index.
Use the 'Explain SQL' function in the SQL Trace to check which index the database uses.

(C) SAP AG BC411 8-50


4. Minimize the Search Overhead 7
Cursor cache

Cursor cache
Oracle: global
memory area
Data block
buffer

Application Database AA0017 NewYork San


server server AA0064 San Francisco
LH0400 Frankfurt New
AA0017 New York San Fran
AA0064 San Francisco New
LH0400 Frankfurt New York

Shared SQL
Pool
SELECT C1 FROM SPFLI
SELECT C3 FROM SBOOK
SELECT C2 FROM LIPS
SELECT * FROM MARA
First
access
R

Second
access
© SAP AG

To improve performance, SQL statements are cached both at application server and at database
server level.
This avoids unnecessary declare and prepare operations in the database.
You can support effective cursor caching by programming your SQL statements consistently. For
example, in SELECT <field list> or a WHERE clause, you should always specify the fields in the
same order. The best method is to specify them in the same order in which they occur in the ABAP
Dictionary.

(C) SAP AG BC411 8-51


4. Minimize the Search Overhead 8

R/3 work process R/3 work process R/3 work process

Network
Communication

DB work process DB work process DB work process

DB memory DB CPU
use use
Database
Database cache service
processes

Physical I/O

Operating system

Database files R

© SAP AG

The benefits of observing rule 4 are that:


You cause fewer I/O operations in the database
You minimize the memory used in the database
You minimize the CPU use of the database

(C) SAP AG BC411 8-52


Rule 5

Reduce the
database load

© SAP AG

Unlike application servers and presentation servers, the database server is a one-off resource in your
system. You should therefore try to reduce the database load wherever possible.

(C) SAP AG BC411 8-53


5. Reduce the Database Load 1

Buffer tables
Avoid reading data repetitively
Check for SELECT before changes
ORDER BY vs. SORT
Logical databases

==> improves Scal abilit y


R

© SAP AG

The above points help you to relieve the load on your database.
They also improve the scalability of your R/3 System, since you can add extra application servers to
your system at any time.
This topic discusses in more detail how you can reduce the database load in your system.

(C) SAP AG BC411 8-54


5. Reduce the Database Load 2
- ABAP Open SQL & table buffering
What is table buffering?
When should you buffer tables?
What must you bear in mind when programming SQL
access to buffered tables?

© SAP AG

(C) SAP AG BC411 8-55


5. Reduce the Database Load 3

Table buffering - concept


Read data from
3 database if it is
not already in the
table buffer
Table buffer

SELECT col1 .......... FROM T001


2 Database
1 server
PROGRAM XYZ

Appl.
server

Data transfer from


database server to
RESULT application server and
R

5 table buffer
4
© SAP AG

The following occurs when you access a buffered table:


1) A program requests data from a buffered table.
2) The application executes the program and interprets the SQL statement. If the table is defined as a
buffered table in the ABAP Dictionary, the application server checks its local buffer to see whether
the table (or parts of it) are already stored there.
3) If the table does not exist in the buffer, the SQL statement is passed on to the database.
Otherwise, the required data is passed to the program.
4) The database passes the data back to the application server, which places the data in the table
buffer.
5) The application server passes the data back to the program.

To analyze the buffering of a table, start Transaction ST02 and choose Detail analysis menu, Call
statistics, Show statistics ( Administration -> System administration -> Monitor -> Performance ->
Setup -> Buffers). This allows you to see which customer tables are buffered and how, how often the
tables are changed, and so on.
You can also check the quality of the buffer in Transaction ST02 by choosing the required table.

(C) SAP AG BC411 8-56


5. Reduce the Database Load 4

Why buffer tables?

Table buffer

0.2 - 1 ms
PROGRAM XYZ
SELECT SINGLE col1 .. FROM T001 Database
server

Appl.
server

8 - 600 ms R

© SAP AG

Buffering tables considerably reduces the time required to access data.


Example: It takes 8 - 600 milliseconds to read a single entry of table T001 from the database. By
contrast, it takes between 0.2 and 1 millisecond to read the same entry from the table buffer.

(C) SAP AG BC411 8-57


5. Reduce the Database Load 5

Buffering types
Resident buffering Generic buffering Generic buffering Partial buffering
(100%) 1 key field 2 key fields (single entry)
key1 key2 key3 Daten
001 A 2
key1 key2 key3 Daten 001 A 4
001 A 001 B 1
key1 key2 key3 Daten 001 A 001 B 3
001 001 B 001 B 5
001 001 B 002 A 1
001 002 A 002 A 3
key1 key2 key3 Daten 001 002 A 002 A 6
002 002 B 002 A 8
002 002 B 002 B 1
002 002 B 002 B 2
002 002 C 002 B 3
002 002 C 002 C 0
002 002 D 002 C 3
003 003 A 002 D 5
003 003 A 003 A 2
003 003 A 003 A 3
003 003 B 003 A 6
003 003 B 003 B 2
003 003 C 003 B 4
003 003 C 003 C 2
003 003 C 003 C 3
003 D 003 C 5
003 D 003 C 8
003 D 003 D 1
003 D 2
R
003 D 3
003 D 4

© SAP AG

There are three types of buffering:


Resident buffering (100%): The first time the table is accessed, the entire table is loaded into the table
buffer.
Generic buffering: In this method, you must specify a generic key (first n key fields) in the technical
attributes of the table in the ABAP Dictionary. This splits the table contents into generic areas. When
you access data with one of the generic keys, the whole generic area is loaded into the buffer. Client-
dependent tables are often buffered generically by client.
Partial buffering (single entry): Individual entries are read from the database and stored in the table
buffer.

(C) SAP AG BC411 8-58


5. Reduce the Database Load 6

Buffer Synchronization I

Local buffer is
Application server A
up to date
UPDATE T001... Table buffer ...
R/3 DB interface

Communication system

Database management system


Database is
DDLOG Database up to date
R

© SAP AG

Whenever you change a database table (update, insert, delete, modify), the application server buffer
is updated at the same time.

(C) SAP AG BC411 8-59


5. Reduce the Database Load 7

Synchronizing the buffer II

Local buffer is
up-to-date
Buffer is
Application server A Applciation server B
NOT
UPDATE T001... Table buffer ... Table buffer up-to-date
R/3 DB interface

INSERT DDLOG

Communication system

Database management system


Database is
DDLOG
DDLOG Database up-to-date
R

© SAP AG

If you have a distributed system with more than one application server, the buffer on application
server B is not updated immediately.
The update statement is executed by the R/3 database interface, which writes an entry in table
DDLOG logging the change to table T001.

(C) SAP AG BC411 8-60


5. Reduce the Database Load 8

Synchronizing the buffer III

Local buffer is Buffer synchronized


up-to-date every 1-2 minutes

Application server A Application server B Buffer


Table buffer ... Table buffer invalid
R/3 DB interface R/3 DB interface

SELECT DDLOG

Communication system

Database management system

Database is
DDLOG
DDLOG Database up-to-date
R

© SAP AG

Each application server ('B' here in the example), periodically reads the contents of table DDLOG to
invalidate the contents of its buffer if necessary.
The table buffer in a distributed system is automatically synchronized every 60 seconds (parameter
rsdisp/buferftime).
Within this time, users on application server B can read 'old' data. The buffer data is not marked as
invalid until after the synchronization. Once this has happened, the data, if required again, is reread
from the database.

(C) SAP AG BC411 8-61


5. Reduce the Database Load 9

When is the buffer invalid?


Resident buffering Generic buffering Generic buffering Partial buffering
(100%) 1 key field 2 key fields (single entry)
key1 key2 key3 Data
001
key1 key2 key3 DAta 001
001 A 001
key1 key2 key3 Data 001 A 001
001 001 B 001
001 001 B 002
001 002 A 002
key1 key2 key3 Data 001 002 A 002
002 002 B 002
002 002 B 002
002 002 B 002
002 002 C 002
002 002 C 002
002 002
003
003
003 Changes invalidate Changes using a
003
003 the corresponding work area invalidate
003
003 generic area the individual entry.
All changes 003
Other changes
invalidate the buffer invalidate the
entire table. R

© SAP AG

The degree to which buffered data is invalidated depends on the buffering type.
If you make changes using a work area, the contents are taken from a work area (for example
'UPDATE dbtab.').

(C) SAP AG BC411 8-62


5. Reduce the Database Load 10

When should you buffer tables?

You should buffer a table if


You frequently read from it
It is relatively small
(few entries, or few, short columns)
You mostly only read from it
You rarely change it (a few times a day or month)

Candidates for buffering


Control and Customizing tables
'Small' master data tables
(100 material master records -> few changes) R

© SAP AG

The most important question to address is: Can a table be buffered?


The answer is yes if you process the table mostly in read-only mode, it is relatively small, and if it is
not critical when the data is not updated immediately on all application servers. This is a logical, not
a technical decision.

(C) SAP AG BC411 8-63


5. Reduce the Database Load 11

Buffering tables

1.) Where?
On the technical settings screen for a table in the
ABAP Dictionary.
2.) Buffering types
Full (resident = 100%)
Generic (with the number of key fields for the generic key)
Single entry (partial buffering)

© SAP AG

The buffering type of a table is decided by its typical use. Programmers usually know this in
advance.

(C) SAP AG BC411 8-64


5. Reduce the Database Load 12

SQL statements that bypass the buffer

SELECT ... BYPASSING BUFFER


SELECT ... DISTINCT
SELECT ... COUNT, SUM, AVG, MIN, MAX
SELECT ... ORDER BY f1 ... fn
SELECT ... GROUP BY / HAVING
SELECT ... FOR UPDATE
SELECT ... JOIN
WHERE clause with IS NULL expression
WHERE clause with subquery R

Native SQL statements (EXEC SQL. ... ENDEXEC)


© SAP AG

You should always consider carefully whether to use the above statements on buffered tables.
When you use SELECT ... ORDER BY PRIMARY KEY, the primary index is always used.

(C) SAP AG BC411 8-65


5. Reduce the Database Load 13

Reading data repetitively

Avoid repeatedly reading data


It causes unnecessary database load
It may produce different results each time

© SAP AG

Avoid reading the same data more than once in your applications. This is partly for runtime reasons,
and partly because the R/3 System allows 'dirty reads' (exception: Oracle database).
This means that reading the same data twice can cause different results. Examine whether you can
read data into an internal table, and then read the second time from the internal table instead of the
database table.

(C) SAP AG BC411 8-66


5. Reduce the Database Load 14

ORDER BY or SORT?
ORDER BY
... Does not necessarily mean that a certain index will be used in the
database
… Often causes a large database overhead

Do you really need the data in a particular order?

© SAP AG

There are two ways to read data in a particular order:


1. Using the ORDER BY addition to the SELECT statement. This ensures that the data is returned
correctly sorted from the database.
2. By sorting at application server level, using the SORT statement to sort the data in an internal
table. This reduces the load on the database system.
Try to avoid using ORDER BY. This shifts the cost of sorting the data from the database server to
the application server.
You cannot use the ORDER BY addition to force the database system to use a particular index.
If the sort order is the same as the index used by the database, ORDER BY entails no costs. In this
case, ORDER BY is more efficient.

(C) SAP AG BC411 8-67


5. Reduce the Database Load 15

Logical databases
Predefined, optimized database access
Simplified list creation
Centrally optimized

But: Use the 'correct' logical database!

© SAP AG

The advantage of logical databases is that they remove the coding required for data retrieval from
your application program, simplifying the process of creating lists in executable (type 1) programs.
Note that you must use a logical database with an appropriate structure, otherwise the performance
gains can rapidly become the complete opposite! For an example, refer to the program
SAPBC411D_SELECT_VS_LDB in development class SAPBC411.

(C) SAP AG BC411 8-68


5. Reduce the Database Load 16

R/3 work process R/3 work process R/3 work process

Network
communication

DB work process DB work process DB work process

DB memory DB CPU
use use
Database
Database cache service
processes

Physical I/O

Operating system

Database files R

© SAP AG

The benefits of observing rule 5 are that you:


Cause fewer I/O operations in the database
Minimize the memory use in the database
Minimize the CPU use in the database
Reduce the network communication
The consequence of all of this is that the database load is reduced .

(C) SAP AG BC411 8-69


ABAP Tuning Checklist - I
Does the program contain SELECT * statements?
Convert the statements into SELECT <col1><col2> statements, or
use a projection view
Does the program contain CHECK statements for table
fields within the SELECT … ENDSELECT loop?
Replace the CHECK statement with a suitable WHERE clause
Do SELECT statements on non-key fields use a
suitable database index, or is the table buffered?
If you only (or mostly) read from the table, create an index for it in the
ABAP Dictionary, or buffer it.
Does the program use nested SELECT statements?
Convert the nested select statements into database views or joins in
the select statement.

© SAP AG

(C) SAP AG BC411 8-70


ABAP Tuning Checklist - II

Does the program contain SELECT statements without


a WHERE clause for tables that grow constantly
(BSEG, MKPF, VBAK) ?
Program design is wrong

Are SELECT statements for master data buffered?


Does the program use SELECT… APPEND ITAB…
ENDSELECT to fill internal tables
Change the program to fill the internal table using SELECT … INTO
TABLE.
Does the program use SELECT… ORDER BY…
statements?
Unless there is a suitable index with the same fields as the order by
clause, read the data into an internal table and sort it there.
R

© SAP AG

(C) SAP AG BC411 8-71


ABAP Tuning Checklist - III

Does the program contain calculations?


Examine whether you can transfer calculations using aggregate
functions (MIN, MAX, SUM, AVG, COUNT) in the database.

© SAP AG

(C) SAP AG BC411 8-72


Summary I

In this unit, you have learned the five


rules for more efficient database
programming.
Rule 1
Keep the result set small
Rule 2
Minimize the amount of data
transferred
Rule 3
Minimize the number of data
transfers
R

© SAP AG

(C) SAP AG BC411 8-73


Summary II

Rule 4
Minimize the search
overhead
Rule 5
Reduce the database load

© SAP AG

(C) SAP AG BC411 8-74


Summary III

By observing these rules, you can


minimize the following:
The network communication between the
database and application server
The memory use on the database server
The CPU use on the database server
The number of physical accesses to database
files.

© SAP AG

(C) SAP AG BC411 8-75


Exceptions and Message Handling: Contents

Defining exceptions in function modules and methods


Exception handling

© SAP AG
Unit Objectives

At the end of this unit, you will be able to

Trigger exceptions in function modules and


methods
Catch exceptions in ABAP programs

© SAP AG

(C) SAP AG BC411 9-2


Exceptions
Z_FREESEAT
Exceptions
PLANE_OVERLOAD
Call
.
.
.
CALL FUNCTION / CALL METHOD
EXPORTING ...
IMPORTING ...
EXCEPTIONS ...
Function module/method Plane_overload = 01
. error_message = 02
. others = 03 .
.
IF SEATSOCC > SEATSMAX. CASE sy-
sy-subrc.
subrc
* RAISE plane_overload. WHEN 1.
.
MESSAGE ... RAISING .
.
plane_overload. ENDCASE.
ENDIF.
R

© SAP AG

When you create function modules and methods, you can define exceptions in the interface. You
trigger them in your programs using one of the following statements:
RAISE <exception> or
MESSAGE ... RAISING <exception>.
The effect of these statements depends on whether the calling program is to handle the exceptions
itself (EXCEPTIONS addition set in the call) or not:
If the calling program is to handle the exception, program control passes directly back to the caller with
not program termination and no message. The export parameters have their old values.
If the calling program is not to handle the exception, the function module terminates in a runtime error
when the RAISE statement occurs. If you use MESSAGE… RAISING… the system displays the
message and does not trigger a runtime error.
You can address the general exception ERROR_MESSAGE for any function module or method call.
This is the exception that is triggered when an error message occurs in the function module or
method; it catches all E and A type messages (in batch input programs, these errors are logged), but
ignores I, W, and S messages. You can use the OTHERS exception to catch any exceptions that you
have not specifically queried.

(C) SAP AG BC411 9-3


Catching Runtime Errors

CATCH SYSTEM-EXCEPTIONS <excpt1> = <rc1> ... <excptn> = <rcn>.


...
ENDCATCH.

REPORT sapbc411d_catch.
DATA: char(5) TYPE c VALUE '12A34', pack TYPE p.

CATCH SYSTEM-EXCEPTIONS conversion_errors = 5 others = 6.


pack = char.
ENDCATCH.
IF sy-subrc = 5.
WRITE 'Conversion error'.
ELSEIF sy-subrc = 6.
WRITE 'Other catchable runtime error'.
ENDIF.

© SAP AG

You can catch system exceptions (ABAP runtime errors) in the processing block between the
CATCH and ENDCATCH statements. If a catchable runtime error occurs within this block:
The system jumps from the ABAP statement in which the error occurred directly to the ENDCATCH
statement, irrespective of the number of control structure levels (IF, DO, LOOP, SELECT,
CATCH…) that it has to bypass. The contents of the fields involved in the statement that caused the
error cannot be guaranteed after the ENDCATCH statement.
The return value <rcn>, assigned to the system exception <excptn> is placed in the system field
SY-SUBRC. If there is more than one expression <excptn> = <rcn>, the <rcn> of the first
expression is returned. This is particularly important if you specify two different ERROR classes
that contain the same runtime error.
CATCH… ENDCATCH may occur anywhere where IF …. ENDIF may also occur, that is, it may
not span more than one event block.

(C) SAP AG BC411 9-4


System Exceptions

CATCH SYSTEM-EXCEPTIONS <excpt> = <rc>.


...
ENDCATCH.

Individual bcd_zero_divide
runtime error convt_to_number
...

arithmetic_errors
Error class conversion_errors
...

All catchable runtime


OTHERS
errors R

© SAP AG

<rc1> ... <rcn> must be numeric literals.


<excpt1> ... <exeptn> can be:
- The error ID of the relevant runtime error (for example DBCONVT_NO_NUMBER)
For a list of catchable runtime errors, refer to the online documentation for the CATCH
statement.
- One of the predefined ERROR classes
Catchable runtime errors are assigned to ERROR classes. If you specify a class, the system
catches all of the runtime errors assigned to it. For a list of error classes, refer to the online
documentation for the CATCH statement.
- OTHERS
If you specify OTHERS, the system catches all catchable runtime errors.
The system only catches runtime errors within the current call level. If a PERFORM or CALL
FUNCTION statement occurs between CATCH and ENDCATCH, the system does not catch any
runtime errors that occur in the corresponding subroutine or function module.

(C) SAP AG BC411 9-5


Nested CATCH… ENDCATCH Structures

CATCH SYSTEM-EXCEPTIONS
compute_int_zerodivide = 1
arithmetic_errors = 2.
.
.
CATCH SYSTEM-EXCEPTIONS
file_access_errors = 5.
.
DO 10 TIMES.
COMPUTE i = 1 / 0. Sets
sy-subrc
ENDDO.
.
ENDCATCH.
.
.
Continues
ENDCATCH. processing
R

© SAP AG

You can nest CATCH… ENDCATCH structures to any depth. If a system exception occurs within a
CATCH…ENDCATCH blocks, the system jumps to the ENDCATCH statement.
In the above example, the exception arithmetic_errors occurs in the inner CATCH…
ENDCATCH block (division by zero). This exception is handled in the outer block. The runtime
system looks for the exception in the current block first. If it does not find it, it looks in the next-
higher block.
In the above example, the system exception arithmetic_errors exists in the outer block. The
system therefore carries on processing at the ENDCATCH statement of the outer block.

(C) SAP AG BC411 9-6


Summary

You can trigger exceptions in function modules and


methods using RAISE <excpt> or
MESSAGE … RAISING <excpt>. The first variant
leads to a runtime error if the calling program does
not handle the exception.
You can also catch system exceptions and
exceptions of function modules and methods
globally and handle them using CATCH…
ENDCATCH blocks.

© SAP AG

(C) SAP AG BC411 9-7


ABAP Modularization Units
Memory model
Internal and external subroutines
Function modules
Methods
Screens (CALL SCREEN)
Modules
Events
Lists (LEAVE TO LIST PROCESSING)
Selection screens (CALL SELECTION SCREEN)
Transactions (LEAVE TO / CALL TRANSACTION)
Programs (SUBMIT)
Contexts
Macros
R

Include programs

© SAP AG
Unit Objectives

At the end of this unit, you will be able to


Explain how the memory model works
Explain parameter passing techniques
Identify how data is visible within different
modularization units
Compare the different modularization
techniques

© SAP AG

(C) SAP AG BC411 10-2


Modularization Units
Internal subroutine
External subroutine
Task
Task Function module
structuring
structuring
Method
Transaction
Report (SUBMIT)
Dialog module (obsolete)
Screen (CALL SCREEN)
Selection screen (CALL SELECTION SCREEN)
List (LEAVE TO LIST PROCESSING)
Module
Event
Context
Source
Source code
code
structuring
structuring
Macro R

Include program
© SAP AG

There are two kinds of modularization units: Those that allow you to structure tasks, and those that
allow you to structure your source code.
This unit concentrates on the visibility of data within modularization units. For this purpose, the list
of 'classic' modularization units has been expanded to include screens, selection screens, and other
objects.

(C) SAP AG BC411 10-3


Memory Areas: Logical Model I

SAP System
R/3 database
Lock table

R/3 instance 1

R/3 instance n
System areas

User 1 User 2 ... User n

© SAP AG

The memory model shows how different ABAP modularization units are implemented in the R/3
System.
The database is a central resource in the R/3 System. Each system has only one database.
All components (server instance, client instances, spool processes, and so on) that are connected to
this database or that work with the same database, comprise an R/3 System.
An instance is a part of an R/3 System that provides one or more services. You can start and stop a
single instance without affecting other instances or the R/3 System as a whole. Each R/3 database
can have several SAP instances.
There is a single lock table that applies to all instances.
Each R/3 instance contains a range of system areas, such as the cross-transaction application buffer,
context buffer, and so on.
Each application server can support several active users.
The following pages examine in more detail the area used by a single user.

(C) SAP AG BC411 10-4


Memory Areas: Logical Model II

System areas

User 1: R/3 terminal session 1

User 1: R/3 terminal session n


SAP Memory (SET /GET parameters)

External session 1 1 External session n

Internal session 1 Internal session 1

ABAP memory
ABAP memory

Program 1 ... Program 1

2 2
Internal session n Internal session n

Program 2 Program 2

© SAP AG

When a user logs onto an instance (application server) in an R/3 System, he or she begins a new
terminal session. You can open a further terminal session using RFC
(CALL FUNCTION … DESTINATION).
All of the windows that you open in a terminal session belong to that session. The first window is
opened automatically when you log on. You can create further windows by choosing
System -> Create session or entering /o plus a transaction code in the command field. Existing
windows remain unchanged when you create new ones. Each window is represented in the R/3
System by an external session.
Each of the statements CALL TRANSACTION, CALL DIALOG, and SUBMIT creates a new
internal session. For example, if you enter /nSE38 in your first window, the system executes the
statement CALL TRANSACTION 'SE38', and generates an internal session.
You can use SAP memory and ABAP memory to pass data between programs.
SAP memory is a user-specific memory area for storing field values. Its contents are retained for the
duration of your terminal session, and can be used in all sessions. All external sessions can access
SAP memory. It is therefore not so useful for passing data between internal sessions.
For further information about ABAP memory, refer to the Data clusters appendix.

(C) SAP AG BC411 10-5


Visibility Area of a Program
R/3 Database
Lock table
System areas

User 1: R/3 session 1

User 1: R/3 session n


SAP memory
Visibility
area of the External session 1
program External
ABAP memory

session n
Internal session 1
Program 1 ...

© SAP AG

The shaded area is the area visible to a program. It contains the data in:
- The program's own internal session
- The ABAP memory of the corresponding external session
- The system area of the R/3 instances (for example, the context buffer or shared
memory)
- The lock table
- The R/3 database

(C) SAP AG BC411 10-6


Internal Session
Internal session
Roll area
Current list system
System area

Program <pgm> Function group 1/ Function group n/


class definition class definition
Ext. subroutine 1 Ext. subroutine 1 Ext. subroutine 1

1 1
Ext. subroutine 2 Ext. subroutine 2 Ext. subroutine 2

Main program Additional Additional


group program group 1 program group 2
R

1 CALL FUNCTION / CALL METHOD


© SAP AG

When the system starts an internal session, it creates the main program group. Additional program
groups are created when you call a function module from a function group that has not yet been
loaded (CALL FUNCTION) or when you call a method of a class definition that has not yet been
loaded (CALL METHOD). A program group can contain several programs. The first program in a
program group is the main program.
When you call an external subroutine (PERFORM form(prog) or PERFORM form IN
PROGRAM prog), the corresponding program (if it has not already been loaded) is loaded into the
same program group as the calling program. If, on the other hand, the subroutine is in a function
group or class definition that has not yet been loaded, the system creates a new program group as it
would in a CALL FUNCTION or CALL METHOD statement.

(C) SAP AG BC411 10-7


Table Work Areas / Common Parts
Program group
Roll area
Table work area
Common part C1 Common part C2

Main program Additional program 1 Additional program 2


PROGRAM / <prog> <prog>
FUNCTION POOL

© SAP AG

Table work areas (created using the TABLES) statement and common data areas (DATA
BEGIN/END OF COMMON PART…) are created once for each program group and shared by all
programs within the group.
Note: The above illustration shows a single program group with its shared data areas.
You should avoid using TABLES and COMMON PART wherever possible, since they can lead to
undetected changes in subroutines, modules, events, and screens. Use typed variables instead.
The only situations in which you still need to use the TABLES statement is with logical databases
and when you use ABAP Dictionary fields on screens. Otherwise, TABLES and COMMON PART
are obsolete.

(C) SAP AG BC411 10-8


The Dangers of Working with Common Data
Areas, Call Hierarchies I
PROG1 PROG2 F Group/ Class

ABAP ABAP .. .. .. ABAP


.. .. .. .. .. .. TABLES:
TABLES: SPFLI.
SPFLI.
TABLES:
TABLES: SPFLI.
SPFLI. 11 TABLES:
TABLES: SPFLI.
SPFLI. FUNCTION
FUNCTION TEST_FB.
TEST_FB.
FORM 22
FORM TEST01.
TEST01. PERFORM
PERFORM
CALL
CALL SCREEN
SCREEN 0100.
0100. TEST01(PROG2).
TEST01(PROG2).
PERFORM
PERFORM ENDFORM.
ENDFORM.
TEST01(PROG2).
TEST01(PROG2).
CALL
CALL FUNCTION
FUNCTION ENDFUNCTION.
ENDFUNCTION.
'TEST_FB'
'TEST_FB' CLASS
CLASS IMPLEMENTATION.
IMPLEMENTATION.
...
... METHOD:
METHOD: m1
m1 ...
...
CALL
CALL METHOD
METHOD o1->m1
o1->m1 ENDMETHOD.
ENDMETHOD.
ENDCLASS.
ENDCLASS.
PROG1_0100

SPFLI SPFLI SPFLI


R

© SAP AG

When you first call a function module, a method, or an external subroutine, the system assigns their
data areas firmly to the main program of the program group. Subsequent calls from other program
groups do not change this initial assignment. This means that the main program whose data is shared
by an external subroutine can depend on the call sequence.
The same applies to screne calls from the called form routine. In the example, the screen
PROG1_0100 from the main program of the program group is displayed.
When the subroutine TEST01 is called, the system does not reserve any memory for table SPFLI in
program PROG2. PROG1 and PROG2 share the table work area.

(C) SAP AG BC411 10-9


The Dangers of Working with Common Data
Areas, Call Hierarchies II
PROG1 PROG2 F group / Class

ABAP ABAP ABAP


.. .. .. .. .. .. .. .. ..
TABLES:
TABLES: SPFLI.
SPFLI. TABLES:
TABLES: SPFLI.
SPFLI. TABLES:
TABLES: SPFLI.
SPFLI.
FORM
FORM TEST01.
TEST01. 11
FUNCTION
FUNCTION TEST_FB.
TEST_FB.
CALL
CALL FUNCTION
FUNCTION CALL
CALL SCREEN
SCREEN 0100.
0100. PERFORM
PERFORM
'TEST_FB'
'TEST_FB' ENDFORM.
ENDFORM. TEST01(PROG2).
TEST01(PROG2).
..
22
..
PERFORM
PERFORM ENDFUNCTION.
ENDFUNCTION.
TEST01(PROG2).
TEST01(PROG2).
...

FGROUP_0100

SPFLI SPFLI SPFLI


R

© SAP AG

When you call a function module, the table work areas of the function group are not linked to the
calling program. Instead, you must transfer data using the interface of the function module.
When you call an external subroutine from a function module, the table work areas of the subroutine
are linked to the main program of the function group.
In the above example, when the subroutine TEST01 is called, the system, once again, does not
reserve any memory in program PROG2 for table SPFLI. The main program of the additional
program group and PROG2 share the table work area.
The same applies to screens that you call from form routines. In the example, the system uses screen
0100 and its status from the main program of the function group.
To prevent errors, avoid using TABLES work areas.

(C) SAP AG BC411 10-10


Subroutines, Function Modules, and Methods

Internal subroutine
Each
External subroutine
Task
Task has an
structuring
structuring explicit
Function module interface

Method

© SAP AG

Each of the modularization units listed above has an interface that it uses to exchange data with the
program that calls it.

(C) SAP AG BC411 10-11


Calling a Function Module, Method,
or External Subroutine
External
External session
session 11 ->
-> Window
Window 11

ABAP Memory (session-specific) Internal session 2

Main program Function


of called group 3
TA/program
Function
group 1

Internal session 1
External
PERFORM 1
CALL
Main program Function
METHOD 1
of TA/program group 2
Function
group 1

SAP
SAP Memory
Memory (User-specific,
(User-specific, not
not session-specific)
session-specific)
© SAP AG

When you call a function module or method, the system loads the corresponding function group or
class definition and initializes its global data. The global data is shared by all function modules or
methods in the function group or class within the same internal session.
In a new internal session (created with CALL TRANSACTION, for example), the system creates
new global data for function group 1. This means that the global data for function modules called in
the second session is different to that used by function modules in the first internal session.
The system behaves in the same way if an external subroutine or a method of an instance is called in
a further internal session. The system always creates new global data in the new session.

(C) SAP AG BC411 10-12


Interfaces in Subroutines
PROGRAM
PROGRAM // REPORT
REPORT // FUNCTION
FUNCTION POOL
POOL // CLASS
CLASS POOL
POOL

Main
Global data program

Inter-
face
Read Write
USING CHANG. USING CHANGING TABLES
VALUE VALUE

Local data
Subroutine
Statements
R

© SAP AG

When you write a subroutine, you name its formal parameters and determine how they will be
passed. The formal parameters are the explicit interface for data exchange with the subroutine.
Internal subroutines can access the data in the main program (global data).
You declare local data in subroutines. This data is only visible within the subroutine, and only
occupies memory space while the subroutine itself is running. As well as data, you can declare
statics.
The STATICS statement allows you to declare data within a procedure (form, function module, or
method) that is visible locally but has a static lifetime. This means that instead of lasting for the
runtime of the procedure, they are retained for the entire duration of the calling program. They are
not recreated each time you call the procedure. Instead, the existing variable, with its existing value,
is taken from the stack. This allows you to build a local memory for forms, function modules,
and methods.
You can create a local copy of a global field or table work area using the GLOBAL statement. When
you leave the subroutine, the system restores the old values of the LOCAL objects.

(C) SAP AG BC411 10-13


Methods for Passing Parameters
Form
Form in
in subroutine
subroutine (FORM)
(FORM)
By reference By value
Read USING/TABLES USING VALUE
Write CHANGING/TABLES CHANGING VALUE

Form
Form in
in calling
calling program
program (PERFORM)
(PERFORM)
By reference By value
Read USING/TABLES USING
Write CHANGING/TABLES CHANGING

Cost
Cost No
No parameters
parameters 11
One
One parameter
parameter 1 1.3
1.3
2 1.7
1.7
3 2.1
2.1
Two
Two parameters
parameters 1 1.5
1.5
2 2.3
2.3
3 2.9
2.9
Three 1
Three parameters
parameters 1.7
1.7
2
2.9
2.9 R
3
3.7
3.7
1 By reference 2 By value 3 By value, returning value
© SAP AG

When you write a subroutine, you define how its parameters will be passed.
When you call a subroutine, you use CHANGING to define the actual parameters that may be
changed in the subroutine.
Calling a subroutine without parameters requires hardly any runtime. The more parameters you pass,
the greater the runtime. Passing parameters by reference requires less time than passing them by
value. The costs for passing a single parameter by value depend on its size (of a structure, for
example).

(C) SAP AG BC411 10-14


Interfaces in Function Modules / Methods
FUNCTION
FUNCTION POOL/
POOL/ CLASS
CLASS POOL
POOL

Main program/
class definition
Global data

Interface

IMPORTING EXPORTING TABLES CHANGING EXCEP-


TIONS

Local data
Function module/
method
Statements
R

© SAP AG

When you define a function module, you specify its IMPORTING, EXPORTING, CHANGING,
and TABLES parameters. Methods only have IMPORTING, EXPORTING, and CHANGING
parameters. Programs can only exchange data with function modules and methods using their
interfaces. There is no general access to the data in the calling program.
Function modules can address the data (global data) of their main program (function group).
Methods can access the global data within their class.
You can define local data in function modules and methods. This data is only visible within the
function module or method, and only occupies memory space while the relevant procedure is
actually running.
When you define a function module or method, you can also define exceptions for error handling.

(C) SAP AG BC411 10-15


Screens, Modules, and Events

Screen

Task
Task Module
structuring
structuring

Event

© SAP AG

Screens are always assigned to the main program of the active program group. This program must
contain the screen modules.
The main program must also contain the events for reading data using logical databases.
The events for interactive lists (AT USER-COMMAND) and the page formatting (TOP-OF-PAGE,
END-OF-PAGE) must occur in the main program of the program group containing the screen (see
CALL SCREEN).

(C) SAP AG BC411 10-16


Interfaces of Screens, Modules, and Events
Screen

Flow logic

I/O fields

PROGRAM/FUNCTION
PROGRAM/FUNCTION POOL/CLASS
POOL/CLASS POOL
POOL
Same
names
Global data
Module

Statements No local
data
Event

Statements R

© SAP AG

The interface of a screen consists of its input/output fields. Data transfer between screens and ABAP
programs is automatic as long as the screen fields and ABAP fields have the same names.
Modules have no local data. Instead, they always use the global data of the main program (module
pool).
Events have no local data. Instead, they always use the the global data of the main program
(executable program, type 1).
Note:
Events that read data from tables in logical databases (GET <table>) are implemented internally as
subroutines. Data declarations within these events therefore only declare local fields.

(C) SAP AG BC411 10-17


Screen/List/Selection Screen

Screen (CALL SCREEN)

Task
Task List (LEAVE TO LIST-
LIST-PROCESSING)
structuring
structuring

Sel. screen (CALL SELECTION-


SELECTION-SCREEN)

© SAP AG

(C) SAP AG BC411 10-18


CALL SCREEN

External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11

ABAP Memory (session-specific)


ABAP Memory session-specific)

Internal session 1 Internal session 1

Before call
After call
Main

Screen stack
Screen stack

Main
program screen 2 program
of TA/ of TA/
Function Function
report report
screen 1 group 1 screen 1 group 1

R
SAP
SAP Memory
Memory (User-specific,
(User-specific, not
not SAP
SAP Memory
Memory (User-specific,
(User-specific, not
not
session-specific)
session-specific) session-specific)
session-specific)
© SAP AG

Each internal session has a screen stack.


Each CALL SCREEN statement adds a new screen to the stack and cretes a new list system (refer to
the List System page).
The CALL SCREEN statement calls a screen belonging to the main program of the main or
additional program group, depending on which is active.

(C) SAP AG BC411 10-19


Implicit Exit / LEAVE SCREEN

External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific)

ABAP Memory (session-specific)


Before call
After call
Main Main
program program

Screen stack
Screen stack

screen 2 of TA/ of TA/


report report
Function Function
group 1 screen 1 group 1
screen 1

SAP
SAP Memory
Memory (user-specific,
(user-specific, not
not SAP
SAP Memory
Memory (user-specific,
(user-specific, not
not R

session-specific
session-specific)) session-specific)
session-specific)
© SAP AG

The implicit end of the program or the LEAVE SCREEN statement removes the top entry from the
screen stack, and carries on processing with the next screen.

(C) SAP AG BC411 10-20


List System
Basic list
List level 0

Detail list
List level 1
... ...

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


Detail list
. List level 2
.
. R

. ..
.
© SAP AG

A list system consists of a basic list and any detailed lists belonging to it.
Within the list system, you can have up to ten list levels (basic list plus nine detail lists). You can
find out the current list level from the system field SY-LSIND (0 <= SY-LSIND <= 20).

(C) SAP AG BC411 10-21


Several List Systems

Starting screen Called screen

CALL SCREEN Not


necessarily
displayed
LEAVE TO
LEAVE TO
LIST-PROCESSING
LIST-PROCESSING

List system 1 List system 2


R

© SAP AG

One list system may be assigned to each screen.


You create a new system when you call a new screen and use the LEAVE TO LIST-
PROCESSING statement.

(C) SAP AG BC411 10-22


Several List Systems - Example I

SAPBC411D_CALL_FM_WRITE Function group 1


FUNCTION
FUNCTION WRITE_LIST.
WRITE_LIST.
...
...
.. .. .. WRITE:
WRITE: text.
text.
TOP-OF-PAGE.
TOP-OF-PAGE. ...
... List system
...
... (SAPBC411D_CALL_FM_WRITE) ENDFUNCTION.
ENDFUNCTION.
CALL
CALL FUNCTION
FUNCTION TOP-OF-PAGE.
TOP-OF-PAGE. ...
...
'WRITE_TEXT' 1
'WRITE_TEXT'
..
..
CALL
CALL FUNCTION
FUNCTION
'CALL_SCREEN_AND_WRITE'
'CALL_SCREEN_AND_WRITE'
...

© SAP AG

The program SAPBC411D_CALL_FM_WRITE calls the function module WRITE_LIST. Since


there are no further CALL SCREEN statements, SAPBC411D_CALL_FM_WRITE remains the main
program responsible for the screen. The WRITE statement in the function module therefore writes in
the list system of the main program. The TOP-OF-PAGE event is also assigned to the main program.
The list displayed by the function module is therefore not a standalone list.
The same would apply if you called a method of a class instead of a function module.

(C) SAP AG BC411 10-23


Several List Systems - Example II
Function group 2
FUNCTION
FUNCTION call_screen_and_write.
call_screen_and_write.
...
...
SAPBC411D_CALL_FM_WRITE CALL
CALL SCREEN
SCREEN 200.
200. "Create
"Create new
new list
list
"system
"system
PROCESS
PROCESS BEFORE
BEFORE OUTPUT.
OUTPUT.
.. .. ..
MODULE
MODULE suppress_dialog.
suppress_dialog.
TOP-OF-PAGE.
TOP-OF-PAGE. ...
...
...
...
PROCESS
PROCESS AFTER
AFTER INPUT.
INPUT.
CALL
CALL FUNCTION
FUNCTION
MODULE
MODULE leave_to_list.
leave_to_list.
'WRITE_TEXT'
'WRITE_TEXT'
MODULE
MODULE back.
back.
..
..
MODULE
MODULE suppress_dialog
suppress_dialog OUTPUT.
OUTPUT.
CALL
CALL FUNCTION
FUNCTION
SUPPRESS
SUPPRESS DIALOG.
DIALOG.
'CALL_SCREEN_AND_WRITE'
'CALL_SCREEN_AND_WRITE' 22
ENDMODULE.
ENDMODULE.
MODULE
MODULE LEAVE_TO_LIST
LEAVE_TO_LIST INPUT.
INPUT.
...

LEAVE
LEAVE TO
TO LIST-PROCESSING.
LIST-PROCESSING.
WRITE:
WRITE: ...
...
ENDMODULE.
ENDMODULE.
List System MODULE
MODULE BACK.
BACK.
(function group 2) LEAVE
LEAVE TO
TO SCREEN
SCREEN 0.
0. R

(SAPLFKT2_0200) ENDMODULE.
ENDMODULE.
TOP-OF-PAGE.
TOP-OF-PAGE. ...
...
© SAP AG

In the example, the function module CALL_SCREEN_AND_WRITE creates a new list system within
the function module through the statement CALL SCREEN 200. This means that the function
module can now create a standalone list, since the main program with responsibility for the screen is
now the main program of the function group to which the called function module belongs. The TOP-
OF-PAGE event is also now linked to the main program of the function group.

(C) SAP AG BC411 10-24


LEAVE TO SCREEN

External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific)

ABAP Memory (session-specific)


Before call
After call
Internal session 1 Internal session 1

Screen stack
Screen stack

Main Main
screen 2 program screen 3
program
of TA/ Function of TA/ Function
report group 1 report group 1
screen 1 screen 1

SAP
SAP Memory
Memory (user-specific
(user-specific SAP
SAP Memory
Memory (user-specific,
(user-specific,
R

not
not session-sepecific)
session-sepecific) not
not session-specific)
session-specific)
© SAP AG

The LEAVE TO SCREEN statement replaces the active screen on the stack with the screen that you
are calling.
This has the same effect as using the statements SET SCREEN <nnnn> and LEAVE SCREEN.
LEAVE SCREEN differs from CALL SCREEN in that you cannot return to the calling screen
(screen 2 in the example).
In the case of LEAVE TO SCREEN 0, the system processes any code occurring after the CALL
SCREEN statement if you are working in CALL mode. Otherwise, it exits to the transaction menu.

(C) SAP AG BC411 10-25


CALL SELECTION-SCREEN

External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific)

ABAP Memory (session-specific)


Before call
After call
Internal session 1 Internal session 1

Screen stack
Main
Screen stack

Main
program screen 2 program
of TA/ Function of TA/ Function
report group 1 report group 1
screen 1 screen 1

SAP
SAP Memory
Memory (user-specific
(user-specific SAP
SAP Memory
Memory (user-specific
(user-specific R

not
not session-specific)
session-specific) not
not session-specific)
session-specific)

© SAP AG

CALL SELECTION-SCREEN behaves like CALL SCREEN. A selection screen defined between
the two statements SELECTION-SCREEN BEGIN OF SCREEN <nnnn> and SELECTION-
SCREEN END OF SCREEN <nnnn> is added to the stack. Unlike CALL SCREEN, however, the
system does not create a new list system, since lists are not possible on selection screens.
The selection screen must be defined in the current main program.

(C) SAP AG BC411 10-26


Transaction / Program

Transaction (LEAVE TO / CALL TRANSACTION

Task
Task Program (SUBMIT )
structuring
structuring

© SAP AG

(C) SAP AG BC411 10-27


CALL TRANSACTION ‘TA01’ /
SUBMIT PROG01 AND RETURN
External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11

ABAP Memory (session-specific)


ABAP Memory (session-specific)

New internal session 2

Before call
Main program

After call
of called TA01
or
program PROG01

Internal session 1 Internal session 1


Main program Main program of
of calling calling
transaction transaction or
or program program

SAP
SAP Memory
Memory (user-specific,
(user-specific, SAP
SAP Memory
Memory (user-specific,
(user-specific, R

not
not session-specific)
session-specific) not
not session-specific)
session-specific)

© SAP AG

CALL TRANSACTION and SUBMIT … AND RETURN both open a new internal session that
contains a new program context with the program data.
The new session is placed on top of the stack of internal sessions.
CALL DIALOG behaves in the same way.
Each step in the call chain (CALL TRANSACTION, SUBMIT, CALL DIALOG) creates its own
internal session.

(C) SAP AG BC411 10-28


Implicit Exit / LEAVE PROGRAM

External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific) External
External session
session 11 ->
-> Window
Window 11

ABAP Memory (session-specific)


Internal session 2

Before exiting
Main program of

After exiting
ended TA01
or program PROG01

Internal session 1 Internal session 1


Main program
of transactoin Main
or program program
PROG01

SAP
SAP Memory
Memory (user-specific,
(user-specific, SAP
SAP Memory
Memory (user-specific,
(user-specific, R

not
not session-specific)
session-specific) not
not session-specific)
session-specific)

© SAP AG

When a program ends, the top entry is removed from the stack of internal sessions. Control passes
back to the point at which the program was called.
The same occurs when you use the explicit statement LEAVE PROGRAM.

(C) SAP AG BC411 10-29


LEAVE TO TRANSACTION ‘TA01’
External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
Internal session 3
Main program
of calling
ABAP Memory (session-specific)

ABAP Memory (session-specific)


program

Internal session 2

Before call
Main program 2

After call
Internal session 1 New internal session 1

Main
Main program 1 program
of TA01

SAP
SAP Memory
Memory (user-specific,
(user-specific, SAP
SAP Memory
Memory (user-specific,
(user-specific,
not
not session-specific)
session-specific) not
not session-specific)
session-specific)
© SAP AG

LEAVE TO TRANSACTION deletes all of the sessions in the stack and creates a new session
containing the called transaction.
Like LEAVE TO SCREEN, it does not allow you to return to the caller.

(C) SAP AG BC411 10-30


SUBMIT PROG01

External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific) External
External session
session 11 ->
-> Window
Window 11

ABAP Memory (session-specific)


Internal session 2 New internal session 2
Main program
Main program
of

Before call
of calling
program

After call
program
PROG01

Internal session 1 Internal session 1

Main
Main program 1
program 1

SAP
SAP Memory
Memory (user-specific,
(user-specific, not
not SAP
SAP Memory
Memory (user-specific,
(user-specific, not
not
session-specific)
session-specific) session-specific)
session-specific)
© SAP AG

SUBMIT PROG01 replaces the current session of the calling program with a new internal session in
which the called program is executed.

(C) SAP AG BC411 10-31


Context

Task
Task
structuring
Context (SUPPLY/DEMAND)
structuring

© SAP AG

Refer to the Contexts unit.

(C) SAP AG BC411 10-32


Structuring Source Code

Source
Source code
code Include programs
structuring
structuring

Macros

© SAP AG

The modularization units listed so far in this unit are all used for performing a task. However, there
are other modularizion units - includes and macros - that you can use to structure your source code.

(C) SAP AG BC411 10-33


Include Programs

INCLUDE prog.

*&------------------------------------------------*
*&------------------------------------------------*
*&
*& Module
Module pool
pool SAPBC411D_TEST_TRANSACTION
SAPBC411D_TEST_TRANSACTION **
*&
*& **

INCLUDE
INCLUDE bc411d_test_transactiontop.
bc411d_test_transactiontop.

INCLUDE
INCLUDE bc411d_test_transactioni01.
bc411d_test_transactioni01.

INCLUDE
INCLUDE bc411d_test_transactiono01.
bc411d_test_transactiono01.

INCLUDE
INCLUDE bc411d_test_transactionf01.
bc411d_test_transactionf01.

© SAP AG

You use include programs to create shared program sections or to divide programs into smaller parts
that are easier to maintain.
The INCLUDE statement has the same effect as copying the source code of the include program into
the main program at the point where it occurs. The syntax check also checks the contents of include
programs. Includes are not loaded dynamically at runtime, they are expanded when the program is
generated.
Include programs do not have a parameter interface. They provide a library function for complex
ABAP programs. They are used in the main programs of function modules and in module pools (see
example) to group together parts of the program that logically belong together. The ABAP
Workbench supports complex program development by creating include programs by forward
navigation and assigning unique names to them.
Include programs cannot run independently, but msut be embedded in other programs. You can
embed includes within other includes, but recursive calls are not allowed.
You can use the where-used list function in the Repository Browser to find the programs in which a
particular include is used.

(C) SAP AG BC411 10-34


Macros

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

DATA:
DATA: RESULT
RESULT TYPE
TYPE I,
I,
N1
N1 TYPE
TYPE II VALUE
VALUE 5,
5,
N2
N2 TYPE
TYPE II VALUE
VALUE 6.
6. Output:
The result of 4 + 3 is 7
The result of 2 ** 7 is 128
DEFINE
DEFINE OPERATION.
OPERATION.
RESULT
RESULT == &1
&1 &2
&2 &3.
&3.
OUTPUT
OUTPUT &1
&1 &2
&2 &3
&3 RESULT.
RESULT.
END-OF-DEFINITION.
END-OF-DEFINITION.

DEFINE
DEFINE OUTPUT.
OUTPUT.
WRITE:
WRITE: // 'The
'The result
result of
of &1
&1 &2
&2 &3
&3 is',
is', &4.
&4.
END-OF-DEFINITION.
END-OF-DEFINITION.

OPERATION
OPERATION 44 ++ 33 .. R

OPERATION
OPERATION 22 **
** 7.
7.

© SAP AG

You define macros using the statement block shown above.


You must specify full statements between the DEFINE and END-OF-DEFINITION statements. The
statements may contain up to nine placeholders &1, &2, … , &9. The definition of a macro must
appear in the program before it is called.
You run a macro using the statement <macro> [<p1> <p2> … <p9>].
When the program is generated, the macro is replaced by the corresponding statements, and the
placeholders &i are replaced by the parameters <pi>. Macros may call other macros, but may not
call themselves.
The above example contains definitions for two macros, OPERATION and OUTPUT. OUTPUT is
nested within OPERATION. OPERATION is called three times with different parameters. Note how
the placeholders &1, &2 … are replaced.
The disadvantage of macros is that the macro call is often difficult to interpret, especially if the
definition and call are a long way apart in the program. Another disadvantage is that the Debugger
does not step through macros. Instead, it executes them in a single step.

(C) SAP AG BC411 10-35


Summary

In this unit, you have learned


How the different modularization units fit into the
memory model
How you can pass parameters in ABAP
What data is visible within modularization units
How to evaluate the different modularization units,
based on comparison criteria

© SAP AG

(C) SAP AG BC411 10-36


Dynamic Program Generation: Contents

Dynamic ABAP Programming


Generating temporary and persistent programs at
runtime

© SAP AG
Unit Objectives

At the end of this unit, you will be able to

Generate programs at runtime


Store generated programs temporarily in a
subroutine
Store generated programs permanently in
the R/3 Repository

© SAP AG

(C) SAP AG BC411 11-2


Dynamic ABAP Programming

Dynamic statements
tabname = 'SFLIGHT'.
SELECT * FROM (tabname).

Field symbols
<f>

Generating programs from programs


Program
Program 1 GENERATE
(subrountine) 2

© SAP AG

Dynamic programming means specifying the type, length, offset, number of lines, or name of a
program object at runtime.
ABAP supports various kinds of dynamic programming:
Dynamic extension of internal tables
Dynamic offset and length specification (in MOVE, WRITE TO, formal parameters, and field
symbols)
Dynamic specification of program object names (the name of a table, modularization unit, sort
criterion, control level criterion, and so on)
Dynamic specification of type and data declarations
You can use the following techniques:
Dynamic statements
Certain statements allow dynamic programming. For example, you can specify a function
module name at runtime in the CALL FUNCTION statement.
Field symbols (dynamic ASSIGN, dynamic type specification, ASSIGN COMPONENT)
Program generation from within a program
You can store ABAP code in an internal table and generate it into a program at runtime.

(C) SAP AG BC411 11-3


Dynamic Programming - Examples
TABLES:
TABLES: SFLIGHT
SFLIGHT
DATA:
DATA: fm_name(30)
fm_name(30) TYPE
TYPE cc VALUE
VALUE 'POPUP_TO_CONFIRM_STEP',
'POPUP_TO_CONFIRM_STEP',
screen_no(4)
screen_no(4) TYPE
TYPE nn VALUE
VALUE '0100',
'0100',
tab_name(30)
tab_name(30) TYPE
TYPE cc VALUE
VALUE 'SFLIGHT',
'SFLIGHT',
upro_name(30)
upro_name(30) TYPE
TYPE cc VALUE
VALUE 'MY_FORM',
'MY_FORM',
prog_name(30)
prog_name(30) TYPE
TYPE cc VALUE
VALUE 'sapbc411d_demo',
'sapbc411d_demo',

CALL
CALL FUNCTION
FUNCTION 'POPUP_TO_CONFIRM_STEP'.
'POPUP_TO_CONFIRM_STEP'.
CALL
CALL FUNCTION
FUNCTION fm_name.
fm_name.

CALL
CALL SCREEN
SCREEN '0100'.
'0100'.
CALL
CALL SCREEN
SCREEN screen_no.
screen_no.

SELECT
SELECT ** FROM
FROM sflight.
sflight.
SELECT
SELECT ** FROM
FROM (tab_name).
(tab_name).

PERFORM
PERFORM my_form
my_form IN
IN PROGRAM
PROGRAM sapbc411d_demo.
sapbc411d_demo.
PERFORM
PERFORM (upro_name)
(upro_name) IN
IN PROGRAM
PROGRAM (prog_name).
(prog_name).
R

© SAP AG

The above example contains a range of dynamic statements.


The following program object names are supplied dynamically:
The name of a function module
A screen number
The name of a database table
The name of a program containing a subroutine for an external perform.

(C) SAP AG BC411 11-4


Specifying Names at Runtime

Variable instead of text literal Parentheses

Function modules SQL


CALL FUNCTION <fm>. SELECT (<itab1>)
Authorization checks FROM (<c>) INTO ...
AUTHORITY-CHECK WHERE (<itab2>).
OBJECT <obj> ID <name> Sorting and control level processing
FIELD <field>. in internal tables
Screen SORT <itab> BY (<c>).
CALL SCREEN <scr>. AT NEW (<c>).
AT END OF (<c>).
Transaction
CALL TRANSACTION <tc>. Report
SUBMIT (<c>).
Message
MESSAGE ID <id> TYPE <m_type> Subroutine calls
NUMBER <no>. PERFORM (<c>) IN PROGRAM (<c>).

© SAP AG

If you often need to specify variable program object names in ABAP statements, you can use
variables instead of text literals.
Certain statements also allow you to specify program object names dynamically using the
parenthesis syntax, namely:
The SELECT, FROM, WHERE, GROUP BY and ORDER BY clauses of the SELECT statement.
Sort criteria and control level criteria in internal tables.
The SUBMIT statement.
The long form of the PERFORM statement, that is, PERFORN (<c>) IN PROGRAM (<c>) for
external performs, or PERFORM (<c>) IN PROGRAM for internal calls.
Note that some ABAP statements have a short form that does not support dynamic programming,
but a long form that does (for example, PERFORM, MESSAGE).

(C) SAP AG BC411 11-5


Generating Programs from Within Progams
Generating temporary programs Generating persistent programs

<itab> <itab>
REPORT ztest. REPORT ztest.
FORM display. WRITE 'Generated program'.
WRITE 'Generated program'.
ENDFORM.

GENERATE SUBROUTINE POOL INSERT REPORT

Subroutine pool Repository


ABAP

external PERFORM SUBMIT


R

© SAP AG

If you cannot create a finished version of your source code until runtime, you can generate a
program from within another program. This is particulary useful if you cannot declare data types and
objects until runtime.
You can create either temporary or persistent programs.

(C) SAP AG BC411 11-6


Generating Temporary Programs
GENERATE SUBROUTINE POOL <itab> NAME <program>.
PERFORM <form_name> in program <program>.

REPORT sapbc411d_subroutine_pool.
TYPES: editor_line_type(72) TYPE c.
DATA: source_table TYPE STANDARD TABLE OF editor_line_type
WITH KEY TABLE LINE WITH HEADER LINE,
program_name LIKE sy-cprog.

APPEND: 'REPORT test.' TO source_table,


'FORM display.' TO source_table,
'WRITE ''I am temporary''.' TO source_table,
'ENDFORM.' TO source_table.

GENERATE SUBROUTINE POOL source_table NAME program_name.


PERFORM display IN PROGRAM (program_name).

© SAP AG

To store your source code, create an internal table with the same line type as the ABAP Editor.
The statement GENERATE SUBROUTINE POOL <itab> NAME <program> generates a
temporary program from the internal table <itab>. The program is created automatically, and its
program name is returned to the field <program_name>. You can run the generated code from the
program that generated it using an external perform.

(C) SAP AG BC411 11-7


Generating Persistent Programs

INSERT REPORT <program> FROM <itab>.


SUBMIT <program> [AND RETURN].

TYPES: editor_line_type(72) TYPE c.


DATA: source_table TYPE STANDARD TABLE OF editor_line_type
WITH KEY TABLE LINE WITH HEADER LINE,
program_name LIKE sy-cprog.

APPEND: 'REPORT zgenprog.' TO source_table,


'WRITE ''I'm persistent''.' TO source_table.

INSERT REPORT 'ZGENPROG' FROM source_table.


SUBMIT zgenprog AND RETURN.

© SAP AG

You can generate a persistent program in the R/3 Repository from the coding in your internal table
using the statement INSERT REPORT <program> FROM <itab>.
The attributes are set automatically by the system. You can change them afterwards using the
function module 'TR_TADIR_INTERFACE'.

(C) SAP AG BC411 11-8


Summary

You can program dynamically in ABAP using


dynamic statements, field symbols, and program
generation.
Generating programs from other programs is a very
powerful form of dynamic programming. You can
keep your generated coding either temporarily or
permanently.

© SAP AG

(C) SAP AG BC411 11-9


Appendix

This section contains supplementary material


to be used for reference
This material is not part of the standard course
Therefore, the instructor might not cover this
during the course presentation

© SAP AG 1999
Further Information about Internal Tables and
Extracts

Internal Tables and Extracts


Accessing Table Entries Directly (Release 4.5A)

© SAP AG

(C) SAP AG BC411 12-2


Internal Tables and Extracts (1)
Internal table Extract
TYPES: BEGIN OF line_type. FIELD-GROUPS: header, fg.
f1, f2, f3.
END OF line_type.
DATA: itab TYPE STANDARD TABLE
OF line_type
WITH KEY f1
WITH HEADER LINE.
INSERT: f1 INTO header,
f2, f3 INTO fg.
GET dbtab. APPEND dbtab TO itab. GET dbtab. EXTRACT fg.
END-OF-SELECTION. END-OF-SELECTION.
SORT itab BY f1. SORT BY f1.
LOOP AT itab. LOOP.
AT FIRST. <Statements> . ENDAT.
AT NEW f1. <Statements> . ENDAT.
AT NEW f2. <Statements> . ENDAT.
<Single entry processing>
AT END OF f2. <Statements> . ENDAT.
AT END OF f1. <Statements> . ENDAT.
R

AT LAST. <Statements> . ENDAT.


ENDLOOP.
© SAP AG

There are two steps in defining the record type of an extract dataset:
Declare the required record type (FIELD-GROUPS).
The field group HEADER must be included. Above all, it must contain all of the fields by which you
may later want to sort.
Assign the required fields to the field groups (INSERT … INTO… ).
In the EXTRACT satement, the fields of the header and those of the relevant field group are
supplied with values from the relevant work areas. The field group HEADER and the one specified
in the EXTRACT statement are written to the EXTRACT dataset as a record.
If you process an internal table or extract dataset using the LOOP statement, you can use the AT
FIRST, AT NEW, AT END OF, and AT LAST statements for control level processing. The
statement blocks that follow each of these AT… statements must be concluded with an ENDAT
statement. The processing blocks are called whenever the field <field> or a higher-level field in
the hierarchy changes its contents. Note that AT FIRST, AT NEW, AT END OF, and AT LAST are
control structures, and not events. This means that the sequence in which they occur is decisive for
the program flow.
The extract dataset or internal table must be sorted by group criteria.

(C) SAP AG BC411 12-3


Internal Tables and Extracts (2)
Internal table Extract

☺ Several internal tables Only one EXTRACT dataset

☺ Control level sums at beginning of Control level sums only at the end
a control level (AT FIRST, AT NEW of a control level (AT END OF f, AT
f) LAST)

☺ Many operations (insert, change, Few operations (only append, sort,


delete, single entry access,…) and sequential processing)

☺ Changes possible at any time Extract cannot be extended after


SORT or LOOP

Single line type per internal table ☺ More than one line type possible
Line type is static ☺ Line type is dynamic (INSERT is
not a declarative statement)
Control level processing only ☺ Control level processing according
according to the sequence of fields to the sort sequence (regardless of
in the table structure the sequence of fields in the
header)
SUM operation has high costs R

☺ (SUM(f)) optimized

© SAP AG

There is only one extract dataset in each roll area.


Extracts only allow control level processing at the end of a control level.
The only operations allowed for extracts are append (EXTRACT), SORT, and sequential processing
(LOOP). After the first SORT or LOOP, you can no longer extend the extract with the EXTRACT
statement. Operations such as insert and delete are not allowed.
Extracts allow you to use more than one record type (FIELD-GROUPS), whose fields can be defined
dynamically (INSERT is not a declarative statement). Internal tables have a single line type, which
you define statically.
The control level processing hierarchy for an internal table is the sequence in which the fields occur
in the table definition. It is therefore static, and, in particular, depends on the criteria according to
which the internal table has been sorted. All of the fields to the right of the field <field> are filled
with '*' during AT … ENDAT processing. Control level processing for extracts does not depend on
the field sequence, but is dynamic. This means that you can resort the dataset, after which a
completely new control level processing is possible. The processing sequence corresponds to the sort
key of the extract dataset, that is, the sequence of the fields from the field group HEADER according
to which the extract was sorted.
The SUM function is optimized for extracts, but not for internal tables (see following pages).

(C) SAP AG BC411 12-4


Internal Tables and Extracts (3)
Internal table Extract

LOOP AT itab. LOOP.


AT END OF itab-carrid. AT END OF itab-carrid.
SUM. WRITE itab-seatsmax. WRITE SUM(itab-seatsmax).
ENDAT. ENDAT.
AT LAST. AT LAST.
SUM. WRITE itab-seatsmax. WRITE SUM(itab-seatsmax).
ENDAT. ENDAT.
ENDLOOP. ENDLOOP.
Work area itab
LH 590 *********

Internal table itab Extract


CARRID SEATSMAX CARRID SEATSMAX
AA 140 ... AA 140 ...
LH 320 ... LH 320 ...
590
LH 270 ... LH 270 ...
SQ 340 ... SQ 340 ... SUM(itab-seatsmax)

© SAP AG

With internal tables, you can use the SUM statement within an AT… ENDAT block to calculate a
sum for the current control level or the total sum (in AT FIRST or AT LAST). The system calculates
the sums of all fields with data types P, I, and F, and places them in the corresponding fields of the
work area or header line.
With extracts, you can address the fields SUM(<numfield>) and CNT(<headerfield>) within
the AT END OF … ENDAT and AT LAST … ENDAT processing blocks:
SUM(<numfield>) calculates the sum for each group. The required work fields are generated
automatically, and initialized with zero each time the control level changes.
CNT(<headerfield>) increases by one each time the contents of the header field in question
change. In control level processing, <header field> must come lower in the sort order than the field
on which the control level processing is based.
With extracts, the compiler notes the combination of control levels and fields for which sums are
required. The control level sums are calculated in the LOOP … ENDLOOP block. With internal
tables, the control level sum is not calculated until the SUM statement. Consequently, the cost of
control level sums with internal tables increases quadratically.

(C) SAP AG BC411 12-5


Accessing Table Entries Directly (Release 4.5)
Contents
Aim: To be able to access internal tables without copying
Reading and writing table entries without copying to and from a work
area

Means: ASSIGNING addition in READ and LOOP


„ “INTO wa”” addition can usually be replaced with the ASSIGNING
addition
LOOP AT itab ... ASSIGNING <fs> ...
Corresponds to a LOOP with READ ASSIGNING as its first
statement
After the loop, the field symbol corresponds to the last line of the
table
Control levels and LOOP ... ASSIGNING
R

No copying to output area

© SAP AG
SUM not possible

Until now, access to internal tables has been by means of the header line or a work area (wa). This
has always resulted in high copying costs, especially with deep structures (where a component of the
line type is itself an internal table).
The ASSIGNING addition in the READ and LOOP statements allows you to access a table entry
directly using a field symbol. There is an example of this on the next page, and a further example in
the tips and tricks section of the runtime analysis transaction (SE30) under the entry “Filling nested
internal tables”.
Note that the field symbol always works directly with the body of the table. You cannot change the
key components of an internal table.
If you work without a work area or header line, there are no copying costs when you use control
level processing. On the other hand, there is no area in which you can place the result of a SUM
statement.
The LOOP AT <itab> … ASSIGNING statement is always quicker than LOOP AT <itab>… INTO
<wa> for tables with more than 10 entries, regardless of the width of the table line.
Structure of Deep Tables

* Bottom-up algorithm * Top-down algorithm


* Entries: 50 (outer table) * Entries: 50 (outer table)
10 (inner table) 10 (inner table)
* Line width: 500 (outer) * Line width: 500 (outer)
4 (inner) 4 (inner)

DO 50 TIMES. DO 50 TIMES.
CLEAR wa. APPEND INITIAL LINE TO itab.
DO 10 TIMES. ENDDO.
APPEND n TO wa-inttab.
ADD 1 TO n. LOOP AT itab ASSIGNING <fs>.
ENDDO. DO 10 TIMES.
APPEND wa TO itab. APPEND n TO <fs>-inttab.
ENDDO. ADD 1 TO n.
ENDDO.
ENDLOOP.

© SAP AG

The ASSIGNING variant now makes it possible to fill an internal table using the top-down strategy,
that is, the outer table is filled, followed by the inner table.
The ASSIGNING variant is always quicker with deep tables, since there are no associated copying
costs.
For a full example, refer to the demonstration program
SAPBC411D_TESTFRAME_NESTED_TAB in development class SAPBC411.

(C) SAP AG BC411 13-2


Accessing Table Entries Directly (Release 4.5A)

Aim: To be able to access internal tabes without copying


Reading and writing table entries without copying to and from a work
area

Means: ASSIGNING addition in READ and LOOP


“INTO wa” addition can usually be replaced with the ASSIGNING
addition
LOOP AT itab ... ASSIGNING <fs> ...
Corresponds to a LOOP with READ ASSIGNING as its first
statement
After the loop, the field symbol corresponds to the last line of the
table
Control levels and LOOP ... ASSIGNING
R

No copying to output area


SUM not possible
© SAP AG

Until now, access to internal tables has been by means of the header line or a work area (wa). This
has always resulted in high copying costs, especially with deep structures (where a component of the
line type is itself an internal table).
The ASSIGNING addition in the READ and LOOP statements allows you to access a table entry
directly using a field symbol. There is an example of this on the next page, and a further example in
the tips and tricks section of the runtime analysis transaction (SE30) under the entry “Filling nested
internal tables”.
Note that the field symbol always works directly with the body of the table. You cannot change the
key components of an internal table.
If you work without a work area or header line, there are no copying costs when you use control
level processing. On the other hand, there is no area in which you can place the result of a SUM
statement.
The LOOP AT <itab> … ASSIGNING statement is always quicker than LOOP AT <itab>… INTO
<wa> for tables with more than 10 entries, regardless of the width of the table line.

(C) SAP AG BC411 13-3


Further Information About ABAP Open SQL:
Contents
The FOR ALL ENTRIES addition in the SELECT
statement
Explicit cursors
Disjunctive normal form
The NOT operator
SELECT before changes
Restart logic

© SAP AG
Rule 3: Minimize the Number of Transfers 1

FOR ALL ENTRIES IN

REPORT
REPORT sapbc411d_select_view.
sapbc411d_select_view.
SELECT
SELECT ** FROM
FROM sflight
sflight INTO
INTO TABLE
TABLE sflight_itab.
sflight_itab.
SELECT
SELECT carrid
carrid ...INTO
...INTO CORRESPONDING
CORRESPONDING FIELDS
FIELDS OF
OF sbook
sbook
FROM
FROM sbook
sbook
FOR
FOR ALL
ALL ENTRIES
ENTRIES IN
IN sflight_itab
sflight_itab
WHERE
WHERE carrid
carrid == sflight_itab-carrid
sflight_itab-carrid
AND
AND connid
connid == sflight_itab-connid
sflight_itab-connid
AND
AND fldate
fldate == sflight_itab-fldate.
sflight_itab-fldate.
WRITE:
WRITE: // ...
...
ENDSELECT.
ENDSELECT.

© SAP AG

This example uses the Open SQL statement FOR ALL ENTRIES, which allows you to process a set
of entries in the database. Unlike a nested SELECT statement, where the inner SELECT loop
accesses the database entry by entry, FOR ALL ENTRIES uses an array fetch to read from the
database for all of the entries in an internal table.
SELECT FOR ALL ENTRIES reads all of the database entries corresponding to the lines in an
internal table using a single database access (or at most, a few).
The advantage of using SELECT FOR ALL ENTRIES is that only the relevant data is read,
regardless of how selective the condition in the outer loop. This minimizes the amount of data
transferred.

(C) SAP AG BC411 14-2


Rule 3: Minimize the Number of Transfers 2

Explicit cursor
OPEN
OPEN CURSOR
CURSOR <cursor>
<cursor> FOR
FOR
SELECT
SELECT ** FROM
FROM <dbtab>
<dbtab> WHERE
WHERE <cond>
<cond> ORDER
ORDER BY
BY PRIMARY
PRIMARY KEY.
KEY.
FETCH
FETCH NEXT
NEXT CURSOR
CURSOR <cursor>
<cursor> INTO
INTO <dbtab>.
<dbtab>.

REPORT
REPORT sapbc411d_select_view.
sapbc411d_select_view.
...
...
OPEN
OPEN CURSOR
CURSOR c1
c1 FOR
FOR SELECT
SELECT ** FROM
FROM sflight
sflight WHERE
WHERE cond1
cond1 ORDER
ORDER BY
BY PRIMARY
PRIMARY KEY.
KEY.
OPEN
OPEN CURSOR
CURSOR c2
c2 FOR
FOR SELECT
SELECT ** FROM
FROM sbook
sbook WHERE
WHERE cond2
cond2 ORDER
ORDER BY
BY PRIMARY
PRIMARY KEY.
KEY.
DO.
DO.
FETCH
FETCH NEXT
NEXT CURSOR
CURSOR c1c1 INTO
INTO sflight.
sflight.
IF
IF sy-subrc
sy-subrc <>
<> 0.
0. EXIT.
EXIT. ENDIF.
ENDIF.
IF
IF sy-index
sy-index == 1.
1.
FETCH
FETCH NEXT
NEXT CURSOR
CURSOR c2c2 INTO
INTO sbook.
sbook.
ENDIF.
ENDIF.
WHILE
WHILE sy-subrc
sy-subrc == 00 AND
AND sflight-carrid
sflight-carrid == sbook-carrid
sbook-carrid
AND
AND ...
...
...
... tue
tue etwas...
etwas...
FETCH
FETCH NEXT
NEXT CURSOR
CURSOR c2c2 INTO
INTO sbook.
sbook.
ENDWHILE
ENDWHILE R

IF
IF sy-subrc
sy-subrc <>
<> 0.
0. EXIT.
EXIT. ENDIF.
ENDIF.
ENDDO.
ENDDO. CLOSE
CLOSE CURSOR:
CURSOR: c1,
c1, c2.
c2.
© SAP AG

The OPEN CURSOR statement allows you to open a cursor in any of the relevant tables, which you
can then process in parallel.
The advantage of this is that only one cursor is opened for the inner table, and not every fetch for that
cursor results in an access to the inner table (the database interface reads several entries at once by
array fetch and buffers them).
Furthermore, this method allows you to determine the access path yourself.

(C) SAP AG BC411 14-3


Rule 4: Minimize the Search Overhead

General rule
Use the disjunctive normal form (DNF)
(F0 = x1 and F1 = y1 and F2 = z1)
OR (F0 = x2 and F1 = y2 and F2 = z2)
OR (F0 = x3 and F1 = y3 and F2 = z3)
OR (F0 = x4 and F1 = y4 and F2 = z4)
OR (F0 = x5 and F1 = y5 and F2 = z5)
SELECT
SELECT ** FROM
FROM sflight
sflight WHERE
WHERE
carrid
carrid == 'LH'
'LH' AND
AND (( connid
connid == '0400'
'0400' OR
OR
fldate
fldate == '19981129'
'19981129' ))
ENDSELECT.
ENDSELECT.

SELECT
SELECT ** FROM
FROM sflight
sflight WHERE
WHERE
(( carrid
carrid == 'LH'
'LH' AND
AND connid
connid == '0400'
'0400' ))
OR
OR (( carrid
carrid == 'LH'
'LH' AND
AND fldate
fldate == '19981129'
'19981129' )) R
ENDSELECT.
ENDSELECT.

© SAP AG

In complex WHERE conditions, use the disjunctive normal form, that is, the OR operator ‘outside’
and the AND operator ‘inside’.

(C) SAP AG BC411 14-4


Rule 4: Minimize the Search Overhead

Caution when using the NOT operator


No index support
But: Rule 1 still applies!

SELECT
SELECT ** FROM
FROM sbook
sbook
WHERE
WHERE NOT
NOT (( cancelled
cancelled == 'X'
'X' OR
OR carrid
carrid NE
NE 'LH')
'LH')
... Processing
... Processing ......
ENDSELECT.
ENDSELECT.

SELECT
SELECT ** FROM
FROM sbook
sbook
WHERE
WHERE carrid
carrid == 'LH'
'LH' AND
AND cancelled
cancelled NE
NE 'X'
'X'
... Processing
... Processing ......
ENDSELECT.
ENDSELECT.
R

© SAP AG

If you use the NOT operator, the database cannot use an index. However, using it can still prevent
unnecessary data being transferred between the database and the application server (see rule 1).
It is sometimes possible to reformulate an expression to avoid the NOT operator. In the above
example, you could write:
SELECT ... WHERE carrid = 'LH' AND cancelled NE '0000000006'.

(C) SAP AG BC411 14-5


Rule 5: Reduce the Database Load 1

SELECT before changes

SELECT
SELECT ** FROM
FROM dbtab
dbtab WHERE
WHERE ...
...
IF
IF sy-subrc
sy-subrc == 0.
0.
UPDATE
UPDATE dbtab
dbtab ...
...
ELSE.
ELSE.
INSERT
INSERT dbtab
dbtab ...
...
ENDIF.
ENDIF.

Instead,
Instead, use
use

INSERT
INSERT dbtab
dbtab ...
...
IF
IF sy-subrc <>
sy-subrc <> 0.
0.
UPDATE
UPDATE ...
...
ENDIF.
ENDIF.
R

© SAP AG

Avoid reading data purely to find out whether a particular entry exists.
Depending on your application, you may be able simply to make the changes and then query the
return code SY-SUBRC.

(C) SAP AG BC411 14-6


Rule 5: Reduce the Database Load
Restart logic
Frequent
Frequent way
way of
of processing
processing large
large
amounts
amounts of
of data
data
start
start == space.
space.
DO.
DO.
SELECT
SELECT ** UP
UP TO
TO 1000
1000 ROWS
ROWS FROM
FROM t1
t1
WHERE
WHERE key
key >> start
start
ORDER
ORDER BY
BY PRIMARY
PRIMARY KEY.
KEY.
...
... Process
Process entry
entry from
from t1
t1
(-->
(--> insert,
insert, update,
update, delete)
delete)
ENDSELECT.
ENDSELECT.
IF
IF sy-subrc
sy-subrc == 0.
0.
COMMIT
COMMIT WORK.
WORK.
start
start == t1-key.
t1-key.
ELSE.
ELSE. EXIT.
EXIT. ENDIF.
ENDIF.
ENDDO.
ENDDO.
Instead,
Instead, use
use

Verwenden
Verwenden Sie
Sie besser:
besser: R

OPEN
OPEN CURSOR
CURSOR ...
... WITH
WITH HOLD
HOLD ...
... FOR
FOR
SELECT
SELECT ** FROM
FROM ...
...
© SAP AG

Why partition processing?


To allow a commit,
1.) To avoid the Oracle error '1555 Snapshot too old'
2.) To avoid timeouts due to long runtime
3.) To allow you to process large datasets
4.)To avoid long runtime
You can avoid the first error by using the statement OPEN CURSOR … WITH HOLD, although this
only works if you perform a full table scan and have a commit after each n database entries.
You can only solve the problem of long runtimes by using COMMIT WORK. This resets the time
slice.
If the available memory is too small for the amount of data you want to process, you can use the
PACKAGE SIZE n addition in the SELECT statement to read it in suitably-sized packets.

(C) SAP AG BC411 14-7


Further Information About Modularization Units:
Contents

Comparison criteria

© SAP AG
Comparison Criteria I
Position
Position in
in Elementary
Elementary Modularization
Modularization Units
Units

Subroutine
Subroutine
Function
Function module
module
Method
Method
Screen
Screen
Module
Module
Event
Event
Position
Position in
in Memory
Memory Model
Model
Interface
Interface
Data
Data types
types
Parameter
Parameter specification
specification
Passing
Passing method
method
Checks
Checks
R
Default
Default values
values
Changes
Changes to
to interface
interface
© SAP AG

In fitting the modularization units into the memory model, the following questions arise:
What does the modularization unit do?
What, if anything, is created when you call the modularization unit?
Which data areas, if any, are shared with other programs?
Modularization units allow you to specify a data type when you declare them.
Parameter assignment can depend either on their position or on a keyword.
You can pass parameters by value, by value and return, or by address.
Parameters for which you define default values in the interface or program are optional. You can
also define optional parameters without default values.
If your modularization unit has optional parameters, you do not need to adjust all of its calls when
you change the interface.

(C) SAP AG BC411 15-2


Comparison Criteria II

Shared
Shared data
data areas
areas

Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory

Dialogs
Dialogs

Calls
Calls

Calling
Calling unit
unit

Call
Call type
type

Cost
Cost
** Runtime
Runtime
R

** Memory
Memory occupied
occupied

© SAP AG

There are two kinds of shared data area - those that arise automatically, and those that have to be
declared explicitly (COMMON).
The Data passed (other than interface) field is only filled where a particular type is typical for a
modulariaztion unit. The global ABAP memory can be used for practically all units, but is only
really appropriate for a few.
A local memory can be used for a series of calls to the same modularization unit, or for calls to units
in a single group (for example, a function group).
The calling unit category (for example, in CALL SCREEN), shows the program to which the screen
is assigned. The screen modules must be stored in this program.
When you call a modularization unit with its own dialogs (for example, transactions), you can
specify values for the screen fields. The screens can then be processed without being displayed.
When examining the costs of a modularization unit, you must regard the runtime in the context of
the type of memory occupation (for example, new roll area).

(C) SAP AG BC411 15-3


Comparison Criteria III

Administration
Administration Function
Function

Documentation
Documentation
Catalog
Catalog
Directory
Directory of
of calling
calling programs
programs
Test
Test framework
framework

Reusability
Reusability // Use
Use

© SAP AG

How can you document a modularization unit?


The catalog and directory of calling programs sections refer to all programs.
Test framework indicates whether it is possible to test a modularization unit without a calling
program.
The reusability section describes how a modularization unit can be used.

(C) SAP AG BC411 15-4


Internal Subroutine I
Position
Position in
in elementary
elementary modularization
modularization units
units

Subroutine
Subroutine

Position
Position in
in memory
memory model
model
Part
Part of
of aa main
main program
program (main
(main or
or additional
additional program
program group)
group)
Main
Main program
program and
and subroutines
subroutines have
have common
common data
data areas
areas

Interface
Interface
Passing
Passing methods
methods Value
Value
Value
Value and
and return
return
Address
Address
Checks
Checks Type
Type check
check where
where types
types specified
specified
Parameter
Parameter specification
specification Position
Position in
in call
call
Data
Data types
types All
All data
data types
types
Default
Default values
values No
No R

Changes
Changes to
to interface
interface Calls
Calls need
need to
to be
be updated
updated
© SAP AG

Internal subroutines are called within the same main program.


When you pass a data type, the actual parameter is used in place of the formal parameter. The
system checks whether the type of the actual parameter is compatible with that of the formal
parameter (refer to the Types unit).

(C) SAP AG BC411 15-5


Internal Subroutine II
Shared
Shared data
data areas
areas

Global
Global data
data of
of main
main program
program

Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory
Possibly
Possibly selected
selected fields
fields from
from the
the main
main program
program
Dialogs
Dialogs
Own
Own dialogs
dialogs Screens
Screens always
always belong
belong to
to main
main
program of the program group
program of the program group
User
User interface/
interface/
Input
Input possibilities
possibilities
Call
Call
Calling
Calling unit
unit Program
Program
Call
Call type
type Static
Static or
or dynamic
dynamic R

Cost/runtime
Cost/runtime Factor
Factor 1 (depends on
1 (depends on number
number of
of parameters)
parameters)
Memory
Memory occupied
occupied Main
Main program
program
© SAP AG

The cost of a subroutine call depends on the number of parameters.

(C) SAP AG BC411 15-6


Internal Subroutine III

Administration
Administration Functions
Functions

Documentation
Documentation Main
Main program
program
Catalog
Catalog Yes
Yes
Directory
Directory of
of
calling
calling programs
programs
Test
Test framework
framework No
No

Reusablilty
Reusablilty // Use
Use

Program
Program structure
structure

Repeatedly-used
Repeatedly-used statements
statements (local)
(local)

© SAP AG

The Repository Browser lists the subroutines that exist for a given main program.
The where-used list function returns a list of where an internal subroutine is called.

(C) SAP AG BC411 15-7


External Subroutine I
Position
Position in
in elementary
elementary modularization
modularization units
units
Subroutine
Subroutine

Position
Position in
in memory
memory model
model
Part
Part of
of aa main
main program
program (main
(main or
or additional
additional program)
program)
Call
Call may
may load
load aa new
new program
program
Programs
Programs inin aa program
program group
group have
have shared
shared data
data and
and
table
table work
work areas
areas
Interface
Interface
Passing
Passing methods
methods Value
Value
Value
Value and
and return
return
Address
Address
Checks
Checks Type
Type check
check where
where types
types specified
specified
Parameter
Parameter specification
specification Position
Position in
in call
call
Data
Data types
types All
All data
data types
types
Default
Default values
values No
No R

Changes
Changes to
to interface
interface Calls
Calls need
need to
to be
be updated
updated
© SAP AG

External subroutines are called from another main program.


When you pass data types, the actual parameter must be fully compatible with the formal parameter.
If you do not pass a type, the actual parameter must be at least as long as the formal parameter.

(C) SAP AG BC411 15-8


External Subroutine II
Shared
Shared data
data areas
areas
Table work areas
Table work areas
COMMON
COMMON areas
areas
Global
Global data
data of
of the
the main
main program
program
Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory
Yes
Yes - global data
- global data of
of the
the main
main program
program
Dialogs
Dialogs
Own
Own dialogs
dialogs No
No -- screens
screens belong
belong to
to the
the main
main program
program
of
of the
the program
program group
group
User
User interface/
interface/
Input
Input possibilities
possibilities
Call
Call
Calling
Calling unit
unit Program
Program
Call
Call type
type Static
Static or
or dynamic
dynamic R

Cost/runtime
Cost/runtime Factor
Factor 6, aa new
6, new program
program may
may be
be loaded
loaded when
when
Memory
Memory occupied
occupied the
the routine
routine is
is called
called
© SAP AG

Table work areas are automatically shared between the calling and called programs. You can also
create common data areas using the DATA statement.
The costs of running an external subroutine from a subroutine pool are higher for the first call than
for subsequent calls. In the first call, the entire program has to be loaded.

(C) SAP AG BC411 15-9


External Subroutine III

Administration
Administration functions
functions

Documentation
Documentation Subroutine
Subroutine pool
pool
Catalog
Catalog No
No
Directory
Directory of
of Repository
Repository Infosystem,
Infosystem,
Calling
Calling programs
programs Where-used
Where-used list
list
Test
Test framework
framework No
No

Reusability
Reusability // Use
Use

Shared
Shared subroutines
subroutines in
in an
an application
application
(subroutine
(subroutine pool)
pool)

© SAP AG

You can document individual subroutines in the program documentation of the main program.
The where-used list returns a list of where an external subroutine is called.

(C) SAP AG BC411 15-10


Function Module I
Position
Position in
in elementary
elementary modularization
modularization units
units
Function
Function module
module

Position
Position in
in memory
memory model
model
Part
Part of
of aa main
main program
program (function
(function group)
group)
Call
Call may
may generate
generate aa new
new program
program group
group
Program
Program groups
groups share
share an
an internal
internal session
session

Interface
Interface
Passing
Passing methods
methods Value/address
Value/address (IMPORTING)
(IMPORTING)
Value/address
Value/address (EXPORTING)
(EXPORTING)
Value/address
Value/address (CHANGING)
(CHANGING)
Address
Address (TABLES)
(TABLES)
Checks
Checks Type
Type checks
checks (reference
(reference fields)
fields)
Length
Length checks
checks (ref.
(ref. fields/structures)
fields/structures)
Parameter
Parameter specification
specification Keyword-oriented
Keyword-oriented
Data
Data types
types All
All data
data types
types
R

Default
Default values
values Yes
Yes
Changes
Changes to
to interface
interface May
May require
require changes
changes to
to calls
calls
© SAP AG

You can specify whether the EXPORTING, IMPORTING, and CHANGING parameters should be
passed by value or reference.
If you enter a default value for an IMPORTING parameter, it is optional when you call the function
module. EXPORTING parameters are optional by default. If you change the interface of a function
module, you only need to adapt calls if you add, change, or delete IMPORTING parameters that
have no default value or table parameters.

(C) SAP AG BC411 15-11


Function Module II
Shared
Shared data
data areas
areas
Output list
Output list

Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory
Yes
Yes - global data
- global data in
in the
the function
function group
group
Dialogs
Dialogs
Own
Own dialogs
dialogs Yes.
Yes. Screens
Screens belong
belong to
to the
the main
main program
program
(function
(function group)
group) of
of the
the program
program group
group
User
User interface/
interface/
Input
Input possibilities
possibilities
Call
Call
Calling
Calling unit
unit Program
Program
Call
Call type
type Dynamic,
Dynamic, usually
usually by
by specifying
specifying aa literal
literal R

Cost/runtime
Cost/runtime Factor
Factor 12, a new program may be loaded
12, a new program may be loaded
memory
memory occupied
occupied when
when the
the function
function is
is called
called
© SAP AG

The cost of the first function call in a function group are higher than for subsequent calls, since the
whole function group is loaded in the first call.

(C) SAP AG BC411 15-12


Function Module III

Administration
Administration function
function

Documentation
Documentation Yes
Yes
Catalog
Catalog Yes
Yes
Directory
Directory of
of Repository
Repository Infosystem,
Infosystem,
calling
calling programs
programs Where-used
Where-used list
list in
in
Function
Function Builder
Builder
Test
Test framework
framework Yes
Yes

Reusability
Reusability // Use
Use

Application-specific
Application-specific or
or cross-application
cross-application
Advantages:
Advantages: -- Administration
Administration functions
functions
-- Exception
Exception handling
handling

© SAP AG

You can use the where-used list in the Function Builder or the Repository Information System to
display a list of where the function module is called.

(C) SAP AG BC411 15-13


Screen, CALL SCREEN, CALL SELECTION-
SCREEN I
Position
Position in
in elementary
elementary modularization
modularization units
units

Screen
Screen

Position
Position in
in memory
memory model
model
Screens
Screens always
always belong
belong to
to the
the main
main program
program of
of the
the
current
current program
program group
group
The
The called
called screen
screen is
is loaded
loaded into
into the
the current
current roll
roll area
area

Interface
Interface
Passing
Passing methods
methods Input/output
Input/output fields,
fields, automatic
automatic field
field
transport
transport where
where screen
screen fields
fields and
and
ABAP
ABAP fields
fields have
have the
the same
same names
names
Checks
Checks
Parameter
Parameter specification
specification
Data
Data types
types
Default
Default values
values R

Changes
Changes to
to interface
interface
© SAP AG

The CALL SCREEN and CALL SELECTION-SCREEN statements allow you to process a part of a
dialog. Screens are always assigned to the main program of a program group. This program must
always contain the screen modules. If you use CALL SCREEN or CALL SELECTION-SCREEN
within an additional program group, this group becomes the program group responsible for the
screen. Selection screens called using CALL SELECTION-SCREEN must be defined using
SELECTION-SCREEN BEGIN/END OF SCREEN <nnnn> (or be the standard selection screen of a
program). Another difference is that the system is responsible for returning from a selection screen
(not the ABAP program, as with CALL SCREEN).

(C) SAP AG BC411 15-14


Screen, CALL SCREEN, CALL SELECTION-
SCREEN II
Shared
Shared data
data areas
areas
Global
Global data
data of
of the
the ABAP
ABAP program
program

Data
Data passing
passing (other
(other than
than interface)
interface)
SPA/GPA
SPA/GPA memory
memory
Local
Local memory
memory
Yes
Yes -- global
global data
data of
of the
the ABAP
ABAP program
program
Dialogs
Dialogs
Own
Own dialogs
dialogs

User
User interface/
interface/
input
input possibilities
possibilities
Call
Call
Calling
Calling unit
unit Program
Program
Call
Call type
type Static
Static or
or dynamic
dynamic R

Cost/runtime
Cost/runtime 148
148
Memory
Memory occupied
occupied Loaded
Loaded into
into roll
roll area
area
© SAP AG

The called screen is loaded into the current roll area.

(C) SAP AG BC411 15-15


Screen, CALL SCREEN, CALL SELECTION-
SCREEN III
Administration
Administration functions
functions

Documentation
Documentation Screen
Screen documentation
documentation
Catalog
Catalog Screen
Screen Painter
Painter
Directory
Directory of
of
calling
calling programs
programs No
No
Test
Test framework
framework Yes
Yes

Reusability
Reusability // Use
Use

Local
Local screen
screen chain
chain
Dialog
Dialog box
box on
on aa screen
screen
Customer
Customer modifications
modifications (Adding
(Adding extra
extra fields)
fields)
Dialogs
Dialogs from
from function
function modules
modules
R

© SAP AG

The called screen is loaded into the current roll area.

(C) SAP AG BC411 15-16


Module I
Position
Position in
in elementary
elementary modularization
modularization units
units
Module
Module

Position
Position in
in the
the memory
memory model
model

Modules
Modules are
are part
part of
of the
the main
main program
program
Main
Main program
program and
and modules
modules have
have shared
shared data
data area
area

Interface
Interface
Passing
Passing methods
methods Automatic
Automatic field
field transport
transport between
between
screen
screen and
and ABAP
ABAP fields
fields with
with the
the
same
same names
names
Checks
Checks
Parameter
Parameter specification
specification
Data
Data types
types
Default
Default values
values
R

Changes
Changes to
to interface
interface
© SAP AG

You call modules from the flow logic of a screen.

(C) SAP AG BC411 15-17


Module II
Shared
Shared data
data areas
areas
Yes
Yes -- global
global data
data of
of the
the main
main program
program

Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory
Yes
Yes -- possibly
possibly selected
selected fields
fields of
of main
main program
program
Dialogs
Dialogs
Own
Own dialogs
dialogs

User
User interface/
interface/
Input
Input possibilities
possibilities
Call
Call
Calling
Calling unit
unit Screen
Screen
Call
Call type
type Static
Static R

Cost/runtime
Cost/runtime
Memory
Memory occupied
occupied Main
Main program
program
© SAP AG

Modules do not have any local data. They always access the global data of the main program
(module pool).

(C) SAP AG BC411 15-18


Module III

Administration
Administration functions
functions

Documentation
Documentation Main
Main program
program (module
(module pool)
pool)
Catalog
Catalog No
No
Directory
Directory of
of Repository
Repository Infosystem,
Infosystem,
calling
calling programs
programs Where-used
Where-used list
list in
in
Repository
Repository Browser
Browser
Test
Test framework
framework No
No

Reusability
Reusability // Use
Use

Within
Within aa module
module pool
pool

Can
Can be
be called
called from
from any
any screen
screen

© SAP AG

You can call a module from any screen in the module pool.

(C) SAP AG BC411 15-19


Event I
Position
Position in
in elementary
elementary modularization
modularization units
units
Event
Event
Position
Position in
in the
the memory
memory model
model

Events
Events always
always belong
belong to
to the
the main
main program
program of
of an
an active
active
program
program group
group
The
The main
main program
program and
and the
the events
events have
have aa shared
shared data
data
area
area

Interface
Interface
Passing
Passing methods
methods

Checks
Checks
Parameter
Parameter specification
specification
Data
Data types
types
Default
Default values
values
R

Changes
Changes to
to interface
interface
© SAP AG

Events are triggered by the ABAP runtime system. There is a processing block assigned to each
event. Events for reading data from logical databases must occur in the main program of the main
program group.

(C) SAP AG BC411 15-20


Event II
Shared
Shared data
data areas
areas

Yes
Yes -- global
global data
data of
of the
the main
main program
program

Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory
Yes
Yes -- possibly
possibly selected
selected fields
fields of
of the
the main
main program
program
Dialogs
Dialogs
Own
Own dialogs
dialogs

User
User interface/
interface/
Input
Input possibilities
possibilities
Call
Call
Calling
Calling unit
unit ABAP
ABAP runtime
runtime system
system
Call
Call type
type R

Cost/runtime
Cost/runtime
Memory
Memory occupied
occupied Main
Main program
program
© SAP AG

Events have no local data. They always use the global data of the main program.

(C) SAP AG BC411 15-21


Event III

Administration
Administration functions
functions

Documentation
Documentation Main
Main program
program
Catalog
Catalog No
No
Directory
Directory of
of Where-used
Where-used list
list in
in
calling
calling programs
programs Repository
Repository Browser
Browser
Test
Test framework
framework No
No

Reusability
Reusability // Use
Use

Logical
Logical databases
databases
Interactive
Interactive programming
programming
Page
Page layout
layout

© SAP AG

(C) SAP AG BC411 15-22


Dialog Module I
Position
Position in
in elementary
elementary modularization
modularization units
units
Screen
Screen -- program
program -- module
module

Position
Position in
in memory
memory module
module
Standalone
Standalone program
program
Call
Call creates
creates aa new
new internal
internal session
session
Several
Several internal
internal sessions
sessions share
share one
one external
external session
session with
with
one
one shared
shared ABAP
ABAP memory
memory
Interface
Interface

Passing
Passing methods
methods Name-oriented,
Name-oriented, value
value of
of
SY-SUBRC
SY-SUBRC passed
passed automatically
automatically
Checks
Checks None
None
Parameter
Parameter specification
specification EXPORTING/IMPORTING/USING
EXPORTING/IMPORTING/USING itab
itab
Data
Data types
types All
All data
data types
types except
except object
object references
references
Default
Default values
values No
No R

Changes
Changes toto interface
interface Some
Some adjustment
adjustment of
of calls
calls required
required
© SAP AG

When you call a dialog module, the system opens a new internal session (roll area). A dialog module
consists of a module pool and its associated screnes. The name of the module pool and the number
of the initial screen are stored in table TDCT.
When you call the dialog module, you name the objects that you want to pass to it (EXPORTING)
and the objects that you want the dialog module to return (IMPORTING). Data is transferred by the
ABAP runtime system using global ABAP memory. The data transfer is fieldname-oriented.
Since CALL DIALOG opens a new internal session, you cannot pass references. References can
only point to data objects in the same roll area.

(C) SAP AG BC411 15-23


Dialog Module II
Shared
Shared data
data areas
areas
No
No
Data
Data passing
passing (other
(other than
than interface)
interface)
SPA/GPA
SPA/GPA memory
memory
Global
Global ABAP
ABAP memory
memory
Local
Local memory
memory
No
No
Dialogs
Dialogs
Own
Own dialogs
dialogs Yes
Yes

User
User interface/
interface/ USING
USING <tab>
<tab>
Input
Input possibilities
possibilities
Call
Call
Calling
Calling program
program Program
Program
Call
Call type
type Dynamic,
Dynamic, usually
usually as
as aa literal
literal R

Cost/runtime
Cost/runtime Factor 8000
Factor 8000
Memory
Memory occupied
occupied Own
Own roll
roll area
area
© SAP AG

As well as specifying the data objects that you want to transfer when you call the dialog module, you
can also pass data between the calling program and the module using SPA/GPA memory or ABAP
memory.
The USING <tab> parameter allows you to pass an internal table containing input values for screen
fields.
Since data is always passed to and from dialog modules by value, calling a dialog module can be
very expensive if you need to pass large table work areas or internal tables.
You can use the global ABAP memory as a local memory.

(C) SAP AG BC411 15-24


Dialog Module III
Administration
Administration Functions
Functions

Documentation
Documentation Program
Program documentation
documentation
Catalog
Catalog Table
Table TDCT
TDCT
Repository
Repository Infosystem
Infosystem
Directory
Directory of
of Where-used
Where-used list
list
calling
calling programs
programs in
in Repository
Repository Browser
Browser
Test
Test framework
framework No
No

Reusability
Reusability // Use
Use

Reusable
Reusable subdialogs
subdialogs
Rarely-used
Rarely-used functions
functions removed
removed toto their
their own
own roll
roll area
area
Large
Large amounts
amounts ofof memory
memory must
must bebe available
available
temporarily
temporarily (internal
(internal tables)
tables)
Call
Call can
can be
be expensive
expensive (passing
(passing internal
internal tables)
tables) R

© SAP AG

Table TDCT contains a list of all dialog modules.

(C) SAP AG BC411 15-25


Transaction I
Position
Position in
in elementary
elementary modularization
modularization units
units

Screen
Screen -- program
program -- module
module

Position
Position in
in the
the memory
memory model
model

Standalone
Standalone program
program
Call
Call creates
creates aa new
new internal
internal session
session
Several
Several internal
internal sessions
sessions share
share one
one external
external session
session

Interface
Interface
Passing
Passing methods
methods

Checks
Checks
Parameter
Parameter specification
specification
Data
Data types
types
Default
Default values
values R

Changes
Changes toto interface
interface Requires
Requires some
some changes
changes to
to calls
calls

© SAP AG

When you call a transaction using CALL TRANSACTION, the system opens a new internal session
(roll area). If you have an internal session n where n >= 0, LEAVE TO TRANSACTION closes all
open internal sessions 0 … n and runs the new transaction in session 0.
Each transaction is assigned to a module pool with screens. The difference between transactions and
dialog modules is in the call. Transations can be called directly by the user as well as from a
program (CALL mode). Dialog modules, on the other hand, can only be called from a program. The
system field SY-CALLD indicates whether a program has been activated in CALL mode.
The interface of a transaction is made up of the input/output fields of its screens.

(C) SAP AG BC411 15-26


Transaction II
Shared
Shared data
data areas
areas
No
No
Data
Data passing
passing (other
(other than
than interface)
interface)
SPA/GPA
SPA/GPA memory
memory
Global
Global ABAP
ABAP memory
memory
Local
Local memory
memory
No
No
Dialogs
Dialogs
Own
Own dialogs
dialogs Yes
Yes
User
User interfaces/
interfaces/ a)
a) SPA/GPA
SPA/GPA values
values and
and
AND
AND SKIP
SKIP FIRST
FIRST SCREEN
SCREEN addition
addition
Input
Input possibilities
possibilities b)
b) USING
USING <tab>
<tab>
Call
Call
Calling
Calling unit
unit Program
Program
Call
Call type
type Dynamic
Dynamic R

Cost/runtime
Cost/runtime 8000
8000
Memory
Memory occupied
occupied Own
Own roll
roll area
area
© SAP AG

You can pass data to a transaction either indirectly, using SPA/GPA memory, or directly using an
internal table (USING <tab>), in which you save the input values for screen fields.

(C) SAP AG BC411 15-27


Transaction III
Administration
Administration functions
functions

Documentation
Documentation Transaction
Transaction documentation
documentation
Catalog
Catalog Table
Table TSTC,
TSTC,
Repository
Repository Infosystem
Infosystem
Directory
Directory of
of Where-used
Where-used list
list in
in
calling
calling programs
programs Repository
Repository Browser
Browser
Test
Test framework
framework No
No

Reusability
Reusability // Use
Use

Uses
Uses an
an existing
existing transaction
transaction

Customer
Customer modifications,
modifications, simple
simple variants,
variants,
call original transaction
call original transaction

© SAP AG

Table TSTC contains all transactions.

(C) SAP AG BC411 15-28


Program, SUBMIT I
Position
Position in
in elementary
elementary modularization
modularization units
units

Selection
Selection screen
screen -- program-
program- event
event

Position
Position in
in memory
memory model
model
Standalone
Standalone program
program
Call
Call generates
generates aa new
new internal
internal session
session
Several
Several internal
internal sessions
sessions share
share an
an external
external session
session with
with
shared
shared ABAP
ABAP memory
memory
Interface
Interface
Passing
Passing methods
methods Value
Value (for
(for selection
selection screen
screen
fields)
fields)
Checks
Checks Selection
Selection screen
screen
Parameter
Parameter specification
specification Keyword-oriented
Keyword-oriented
Data
Data types
types Selection
Selection tables,
tables, single
single values
values
Default
Default values
values Yes
Yes -- report
report
R

Changes
Changes to
to interface
interface Some
Some changes
changes to
to calls
calls required
required
© SAP AG

When you start a report using the SUBMIT AND RETURN statement, the system opens a new
internal session (roll area). When the program ends, the new session n+1 is closed and the system
carries on processing in session n-1 (as long as n > 0). If you use SUBMIT without RETURN, the
existing session containing the calling program is replaced by a new internal session in which the
new report is then run.
The interface of the program consists of the selection screen fields. These can be selection tables or
single values, which you can pass in the WITH addition.
Unlike other modularization units, the report that you call cannot pass values back to the calling
program.

(C) SAP AG BC411 15-29


Program, SUBMIT II
Shared
Shared data
data areas
areas
No
No
Data
Data passing
passing (other
(other than
than interface)
interface)
SPA/GPA
SPA/GPA memory
memory
Global
Global ABAP
ABAP memory
memory
Local
Local memory
memory
No
No
Dialogs
Dialogs
Own
Own dialogs
dialogs Yes
Yes
User
User interface/
interface/ Filling
Filling the
the selection
selection screen
screen
Input
Input possibilities
possibilities
Call
Call
Calling
Calling unit
unit Program
Program
Call
Call type
type Static
Static or
or dynamic
dynamic R

Cost/runtime
Cost/runtime 10 000
10 000
Memory
Memory occupied
occupied Own
Own roll
roll area
area
© SAP AG

You can pass data such as table work areas or internal tables to and from the called program using
the global ABAP memory.

(C) SAP AG BC411 15-30


Program, SUBMIT III
Administration
Administration functions
functions

Documentation
Documentation Program
Program documentation
documentation
Catalog
Catalog ABAP
ABAP development
development
Directory
Directory of
of ABAP
ABAP Dictionary
Dictionary
calling
calling programs
programs Repository
Repository Information
Information System
System
Test
Test framework
framework No
No

Reusability
Reusability // Use
Use

Uses
Uses an
an existing
existing report
report

Enables
Enables you
you to
to keep
keep display
display functions
functions (interactive
(interactive program)
program)
in a separate program
in a separate program

© SAP AG

If you want to use complex display functions within a transaction, you can use an interactive
program. You would implement this function in a separate program.

(C) SAP AG BC411 15-31


LEAVE TO LIST PROCESSING I
Position
Position in
in elementary
elementary modularization
modularization units
units

List
List screen
screen -- events
events

Position
Position in
in the
the memory
memory model
model
List
List always
always belong
belong to
to the
the main
main program
program of
of the
the
main
main program
program group
group
Events
Events are
are part
part of
of the
the main
main program
program
Part
Part of
of aa program
program
Interface
Interface
Passing
Passing methods
methods

Checks
Checks
Parameter
Parameter specification
specification
Data
Data structures
structures
Default
Default values
values R

Changes
Changes to
to interface
interface
© SAP AG

You can implement simpler display functions within the module pool of a transaction instead of
starting a new ABAP program using SUBMIT.

(C) SAP AG BC411 15-32


LEAVE TO LIST PROCESSING II
Shared
Shared data
data areas
areas

Global
Global program
program data
data

Data
Data passing
passing (other
(other than
than interface)
interface)

Local
Local memory
memory

Dialogs
Dialogs
Own
Own dialogs
dialogs
User interface/
User interface/
Input
Input possibilities
possibilities

Call
Call
Calling
Calling unit
unit Program
Program (module)
(module)
Call
Call type
type R

Cost/runtime
Cost/runtime Factor
Factor 22
Memory
Memory occupied
occupied Part
Part of
of program
program
© SAP AG

The list is created and processed (interactive program) in the same program as the dialog modules.
The global data of the main program is therefore available both for list output and for the events of
the interactive program.

(C) SAP AG BC411 15-33


LEAVE TO LIST PROCESSING III

Administration
Administration function
function

Documentation
Documentation
Catalog
Catalog
Directory
Directory of
of
calling
calling programs
programs
Test
Test framework
framework

Reusability
Reusability // Use
Use

Display
Display functions
functions are
are implemented
implemented within
within the
the module
module pool
pool

© SAP AG

LEAVE TO LIST PROCESSING is a simple ABAP statement with no special administration


functions.

(C) SAP AG BC411 15-34


String Processing: Contents

String comparisons
String operations

© SAP AG
Unit Objectives

At the end of this unit, you will be able to


List the string comparisons supported in
ABAP
Use string operations

© SAP AG

(C) SAP AG BC411 16-2


String Processing sy-
sy-subrc sy-
sy-fdpos g/k

SEARCH AB

REPLACE AB A

TRANSLATE AB A a b a

SHIFT AB A

CONDENSE AB A

CONCATENATE A +B AB
OVERLAY AB P
AA AA ABAP
R

SPLIT AB AP
© SAP AG

String processing in ABAP uses the following statements:


SEARCH Search in a string
REPLACE Replace the first occurrence of a string
TRANSLATE Replace all characters
SHIFT Shift a string by one place
CONDENSE Remove spaces
CONCATENATE Join a sequence of strings
OVERLAY Overlay two strings
SPLIT Split a string
In all string operations, the operands are treated like type C fields, regardless of their actual field
type. They are not converted.
The following string processing statements set the system field SY-SUBRC:
SEARCH, REPLACE, SHIFT <string1> UP TO <string2>, CONCATENATE, OVERLAY,
SPLIT. SEARCH also sets the system field SY-FDPOS (offset of the found string).
Apart from SEARCH, all string processing statements differentiate between upper- and lowercase.
The standard function STRLEN returns the occupied length of a string.

(C) SAP AG BC411 16-3


Searching in a String
SEARCH <f> FOR <searchstring>.
SEARCH <itab> FOR <searchstring>.

Ab a p o b j e c t
REPORT sapbc411d_string_processing.

DATA: string(100) TYPE c


VALUE 'Abap object '.

SEARCH string FOR 'X'.


SEARCH string FOR 'ObjecT'.
SEARCH string FOR '. .'.
SEARCH string FOR 'OBj*'.
SEARCH string FOR '*ect'.

System field:Sy-fdpos: 0 1 2 3 4 5 6 7 8 9 10 11

© SAP AG

The system searches the field <f> for the string <searchstring>. <searchstring> can be
one of the following:

'string' A string (trailing spaces are ignored)


'.str.' Any characters between the periods (spaces included in the search)
'*str' A word ending in ‘str’, including ‘str’ itself
'str*' A word beginning with ‘str’, including ‘str’ itself
The offset of the found string is placed in the system field SY-FDPOS. If the search string is not
found, SY-FDPOS contains the value 0.
You can use SEARCH <itab> as well as SEARCH <f>. The system then searches for the search
string within the internal table <itab>. This variant sets SY-TABIX with the line index of the line
containing the search string, as well as SY-SUBRC and SY-FDPOS.

(C) SAP AG BC411 16-4


Manipulating Strings
Ab Ap +
REPLACE 'A' WITH 'B' INTO <f>. Bb Ap +

Ab Ap +
TRANSLATE <f> USING 'AB'. Bb Bp +

Ab Ap +
UPPER CASE.
TRANSLATE <f> TO
LOWER
AB AP +

Ab Ap +
SHIFT <f> [BY <n> PLACES] [mode]. b Ap +

Ab Ap +
R

CONDENSE <f> [NO-GAPS]. Ab Ap +


© SAP AG

REPLACE <string1> WITH <string2> INTO <f>.


The first occurrence of <string1> in <f> is replaced by <string2>. In other words, <f> is
both the source and target field.
TRANSLATE <f> USING <string>.
All letters in <f> are replaced according to <string>. <string> contains the search and
replacement characters in pairs. In the above example, each occurrence of ‘A’ in <f> is replaced
with ‘B’.
TRANSLATE <f> TO UPPER | LOWER CASE.
All lowercase letters in <f> are converted to uppercase (or all uppercase letters are converted to
lowercase).
SHIFT <f>.[BY <n> PLACES] [mode].
<f> is shifted one position to the left. The first letter is no longer displayed, and a trailing space
appears at the right-hand end. SHIFT <f> has the following additions:
... RIGHT. Shifts <f> one position to the right.
... CIRCULAR. Shifts <f> cyclically to the left, that is, the outermost character on the
left-hand side is moved to the right hand end.
... RIGHT CIRCULAR. Shifts <f> cyclically to the right.
CONDENSE <f>
Series of spaces are replaced with a single space. If you use the NO-GAPS addition, all spaces are
deleted.
Note: You can delete leading and trailing spaces using SHIFT <f> LEFT DELETING
TRAILING SPACE or SHIFT <f> RIGHT DELETING TRAILING SPACE.

(C) SAP AG BC411 16-5


Joining and Splitting Strings

CONCATENATE <f1> ... <fn> INTO <f>


AB + AP
[... SEPARATED BY <seperator>].
AB AP

A P X BAX
OVERLAY <f1> WITH <f2>.

AB AP

AB AP
<f1> ... <fn>.
SPLIT <f> AT <separator> INTO
TABLE <itab>. R

AB AP
© SAP AG

CONCATENATE <f1> ... <fn> INTO <f> [SEPARATED BY <separator>].


The fields <f1> … <fn> are joined together and placed in <f>. Trailing spaces are ignored in the
component fields. You can use the SEPARATED BY <separator> addition to separate <f1> …
<fn> by the contents of <separator>.
OVERLAY <f1> WITH <f2>.
<f2> overlays <f1> at all positions where <f2> contains the value SPACE. <f2> remains
unchanged.
SPLIT <f> AT <separator> INTO <f1> ... <fn> | INTO TABLE <itab>.
<f> is split wherever <separator> occurs, and placed in the fields <f1> … <fn> or into the
lines of an internal table <itab>.

(C) SAP AG BC411 16-6


String Comparisons

REPORT sapbc411d_string_processing.

DATA: string(100) TYPE c


VALUE 'Abap Object '.
U/L Blanks
IF string CO 'Objetc Abap'. "true
IF string CO 'ABAP '. "false
CO IF string CO 'ie'. "false

IF string CA 'ie'. "true


CA IF string CA 'o'. "false

IF string CS 'ej '. "false


CS IF string CS 'je'. "true

IF string CP '*b*'. "true


CP
IF string CP '+b#*'. "false
IF string CP 'A+AP# *'. "true
R

© SAP AG

The above table shows the cases in which upper- and lowercase and the full length of the left-hand
operand are considered in a comparison.
Each of the operators above has a corresponding negation. These are, in pairs: CO/CN, CA/NA,
CS/NS, CP/NP.
In the logical expression <string1> operator <string2>, the operators have the following
meanings:
CO: 'Contains Only' <string1> only contains characters from <string2>.
CN: 'Contains Not Only' <string1> does not contain characters from <string2>. It is
equivalent to NOT <string1> CO <string2>
CA: 'Contains Any' <string1> contains at least one character from <string2>
NA: 'Contains Not Any' <string1> contains no characters from <string2>
CS: 'Contains String' <string1> contains the string <string2>
NS: 'Contains Not String' <string1> does not contain the string <string2>
CP: 'Contains Pattern' <string1> contains the pattern <string2>
NP: 'Contains Not Pattern' <string1> does not contain the pattern <string2>
The system field sy-fdpos contains the offset of the character that satisfies the condition, or the
length of <string1>.
For further details, refer to the online documentation in the ABAP Editor for the relevant statement.

(C) SAP AG BC411 16-7


Summary

You can process strings using the


following statements:
SEARCH
REPLACE
TRANSLATE
SHIFT
CONDENSE
CONCATENATE
OVERLAY
SPLIT

© SAP AG

(C) SAP AG BC411 16-8


Bit Processing: Contents

Sets as bit patterns


SET BIT/GET BIT
Assigning values to type X fields
Bit calculations
Bit comparisons

© SAP AG
Unit Objectives

At the end of this unit, you will be able


to write programs that
Use a data object with type X to represent a
set of n elements
Set and read bits within type X data objects
Perform bit calculations using BIT-NOT,
BIT-AND, BIT-OR, and BIT-XOR
Compare a field of any type with a type X
field using the O, Z, and M operators

© SAP AG

(C) SAP AG BC411 17-2


Sets as Bit Patterns

Set containing n elements

Monday Tuesday WednesdayThursday Friday Saturday Sunday

0 1 0 0 0 0 1

Type X
with length ‘smallest number >= (n/8)'

© SAP AG

Bit patterns provide a very efficient way of processing sets.


You can represent a set of n elements using a field with type X, whose length is the integer part of
n/8 (there are 8 bits in a byte) plus one byte for the remaining elements. So, for example, if your set
contains 16 elements, you need a type X field with length 2 bytes, and if it contains 17 elements, the
length of the field would be 3 bytes.
If the ith element of the basic set is contained in a set, the corresponding (ith) byte of the X field is set
to 1, otherwise to 0.
The ith bit (1 <= i <= n) of the X field corresponds to the jth bit (1 <= j <= 8) in the kth byte
of the X:
i = (k-1)*8+j, where k and j can be
calculated from i using the following:
k = (i DIV 8) + 1, for i > 8
k = (i DIV 8) , for i <=8
j = (i MOD 8)
The 13th bit in the X field is therefore the 5th bit in the second byte. The 17th bit is the first bit
in the third byte.

(C) SAP AG BC411 17-3


SET BIT and GET BIT
DATA: hex(2) TYPE x, g TYPE i,
val TYPE i VALUE 1.
SET BIT 4 OF hex. WRITE / hex.
SET BIT 7 OF hex TO val. WRITE / hex.
GET BIT 4 OF hex INTO g. WRITE / g.
GET BIT 7 OF hex INTO g. WRITE / g.

SET BIT <i> OF <hex> [TO <f>].

GET BIT <i> OF <hex> INTO <g>.

0 0 0 1 0 0 1 0 0 0 ... 0
1 2 3 4 5 6 7 8 9 10 16
R

© SAP AG

SET BIT <i> OF <hex> TO <f> sets the ith bit of the X field <hex> to either 0 or 1. <i>
is counted from the left of the field, starting with 1.
The TO <f> addition is optional. If you omit it, the ith but in the X field <hex> is set to 1.
GET BIT <i> OF <hex> INTO <g> retrieves the value of the ith bit in the X field <hex>.

(C) SAP AG BC411 17-4


Assigning Values to X Fields
DATA: hex1(2) TYPE x,
hex2(2) TYPE x VALUE '1A4F' ,
c(4) TYPE c VALUE '1A4F' ,
i TYPE i VALUE '6735' .
hex1 = hex2. WRITE / hex1.
hex1 = c. WRITE / hex1.
hex1 = i. WRITE / hex1.

x 1 A 4 F
Bit No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Value
0 0 0 1 1 0 1 0 0 1 0 0 1 1 1 1
215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20
4096 2048 512 64 8 4 2 1 6735
R

© SAP AG

When you assign a type C field to a type X field, ABAP interprets the C field as a hexadecimal
value. One way of making use of this is to specify a text literal with hexadecimal contents for the C
field, for example, VALUE '1A4F'.
When you assign a type I field to a type X field, the decimal value of the I field is converted into its
corresponding hexadecimal value (6735 decimal equals '1A4F' hex). Caution: The internal
representation of integers is platform-dependent. The sequence of the bits in the above example may
be reversed. In other words, programming in the above manner may mean that your program will not
run on all platforms.
Caution: You must write hexadecimal constants in uppercase. Lowercase letters are interpreted as
zeros. For example writing DATA hex2(2) TYPE x VALUE '1a4F' would produce an entirely
different result to the declaration in the above example.

(C) SAP AG BC411 17-5


Bit Calculations
COMPUTE <hex> = <bit_expression> .

<bit_expression>
BIT-NOT <hex2> 01101101
<hex1> BIT-AND <hex2> 10010000
<hex1> BIT-OR <hex2> 11110010
<hex1> BIT-XOR <hex2> 01100010

1 1 1 1 0 0 0 0
<hex1> 1 2 3 4 5 6 7 8

1 0 0 1 0 0 1 R
0
<hex2> 1 2 3 4 5 6 7 8
© SAP AG

The statement COMPUTE <hex> = <bit expression> analyzes the but expression <bit
expression> and places the result into the field <hex>. You can use the four bit operations
BIT-NOT, BIT-AND, BIT-XOR, and BIT-OR. The operands are linked bit by bit according to
the table below.
The priority is: BIT-NOT before BIT-AND before BIT-XOR before BIT-OR. Parenthetical
expressions are allowed.
The operands in <bit expression> and the result field must all be of type X.
Link table:

x y BIT-NOT x x BIT-AND y x BIT-XOR y x BIT-OR y


__________________________________________________________
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 0 1
If the operands are not the same length, they are converted to the length of the result field using
MOVE X TO X logic. This means that operands shorter than the result field are filled with hex 0 at
their right-hand end, and those longer than the result field are truncated at the right-hand end.

(C) SAP AG BC411 17-6


Bit Comparisons
O
<f> Z <hex>
M
DATA: hex1(1) TYPE x, hex2(1) TYPE x.
IF hex1 O hex2. "false
IF hex1 Z hex2. "false
IF hex1 M hex2. "true

1 1 1 1 0 0 0 0
<f> 1 2 3 4 5 6 7 8

Bit mask 1 0 0 1 0 0 1 R 0
<hex> 1 2 3 4 5 6 7 8
© SAP AG

You can test a field of any type against a type X field <hex> using the O, Z, and M operators.
<hex> is interpreted as a bit mask. The comparison only applies to the bits in <f> that have the
value 1 in <hex>. If <f> is shorter than <hex>, it is implicitly filled with null bytes.
The relational operators O, Z, and M have the following meanings:

O (One) The expression is true if all bits in <hex> with the value 1 also have the value 1 in
<f>.
Z (Zero) The expression is true if all bits in <hex> with the value 1 have the value 0 in <f>.
M (Mixed) The expression is true if all bits in <hex> with the value 1 have at least one 1 and at
least
one 0 in <f>.
You can use bit comparisons to check whether a set contains another set. To do this, you specify a
pattern containing the set you want to search for, and use the bit comparison statements to check
whether it belongs to the other set.

(C) SAP AG BC411 17-7


Example: Representing Flights with an X Field
flight_tab
REPORT sapbc411d_bit_processing. 01100110
TYPES: week(1) TYPE x. 10010010
DATA: flight_tab TYPE TABLE OF week 11110010
WITH HEADER LINE, 01100010
01100110
every_week TYPE x VALUE 'FE',
10010010
one_week TYPE x.
11110010
01100010
* fill flight_tab with bit pattern 01100110
10010010
* calculate every_week and one_week 11110010
LOOP AT flight_tab. 01100010
every_week = flight_tab BIT-AND every_week. 01100110
one_week = flight_tab BIT-OR one_week. 10010010
ENDLOOP. 11110010
01100010

On which day of the week is there a every_week 00000010


flight every week:
R

On which days of the week is there flight one_week 11110110


in at least one week:
© SAP AG

The above example uses bit operations to indicate whether there is a flight on a particular day of a
given week. The basic set contains seven elements - the days of the week. This basic set fits into an
X field that is one byte long. The first seven bit positions represent the seven days of the week, and
the eighth remains unused. So, for example, if the second bit is set, this indicates that there is a flight
on the Tuesday of that week.
To provide an overview of all of the weeks of the year, we use an internal table (flight_tab)
with line type X(1).
The variable every_week is initialized with 'FE' (1111 1110). In other words, the relevant
bits (one to seven) are all set. Using BIT-AND to compare every_week with each line of the
internal table, it is possible to find out the days of the week on which there is a flight in every week
of the year, since the relevant bit changes from 1 to 0 if there is not a flight on the corresponding
day.
The variable one_week is initialized with '00'. All bits are therefore set to 0. Using BIT-OR to
compare one_week with each line of the internal table, it is possible to find out the days of the
week on which there is a flight in at least one week of the year, since the relevant bit changes from 9
to 1 if there is a flight on the corresponding day of a given week.

(C) SAP AG BC411 17-8


Summary

You can use the data type X to represent a basic


set of n elements in a single data object.
You can use SET BIT and GET BIT to set or read a
single bit of a type X field.
BIT-NOT, BIT-AND, BIT-OR, and BIT-XOR allow you
to perform calculations with X fields using normal
boolean operations.
O, Z, and M are relational operators for X fields. You
can use them to compare the state of a bit in a field
of any type with a bit in a bit mask.

© SAP AG

(C) SAP AG BC411 17-9


Data Clusters: Contents

EXPORT
IMPORT
DELETE

© SAP AG
Unit Objectives

At the end of this unit, you will be able to


store data objects under an ID
In a cluster database
In the cross-transaction application buffer
(shared buffer)
In ABAP memory
You will be able to use clusters in your
programs, and be aware of their advantages
and disadvantages.

© SAP AG

(C) SAP AG BC411 18-2


Data Clusters: Overview
Data cluster:

KTNRA NAME1 TDM Fields

Structured
fields

Internal
tables

Export Import

DATABASE
ABAP memory A1 Shared buffer
... R

An

© SAP AG

A data cluster is a collection of data objects. A data object can be a field, a structured field, an
internal table, or any complex structure made up of several of these components. You process
clusters using the ABAP statements EXPORT, IMPORT, and DELETE. You can store them in
ABAP memory, in a cluster database, or in the shared buffer.
The following pages explain more about ABAP memory, cluster databases, and the shared buffer.

(C) SAP AG BC411 18-3


Syntax: EXPORT to a Cluster Database
EXPORT <name> FROM <obj>
[<obj>]
TO DATABASE <dbtab>(<ar>) ID <id>.

REPORT xxx
TABLES indx.
EXPORT optional
<field 1> FROM <field a>
<field 2> FROM <field b>
. .
. .
<structure 1> FROM <structure a>
. .
. .
<itab 1> FROM <itab a>
. .
. .
TO DATABASE indx(<ar>) R

ID <id>.

© SAP AG

In the ABAP Dictionary, you can divide a cluster database into a series of work areas with
logically-related data clusters. Work area IDs are two characters long, and may be freely chosen.
Within a work area, you identify each cluster by its cluster ID.
To export data, you need a cluster database. The table INDX is an all-purpose cluster database.
Cluster databases should be created as transparent tables in the ABAP Dictionary, and must have a
standard structure. For further information, refer to the online documentation in the ABAP Editor for
the EXPORT statement.
In the EXPORT statement, you list the data objects that belong to your cluster.
To export data, specify the name of the cluster database and the work area. You identify the cluster
itself by its cluster ID. If you want a data object in the cluster to have a different name from that in
the program, use the optional addition FROM. You can specify the data object in the list in any
order. There is no write-protection when you export data - existing clusters are automatically
overwritten in a new EXPORT.
The data is stored in compressed form in the cluster database.
At the start of your program, declare a work area for your cluster database using the TABLES
statement.
Caution: You cannot export the header line of an internal table. The EXPORT statement always
applies to the entire table contents.

(C) SAP AG BC411 18-4


Syntax: IMPORT and DELETE
IMPORT <name TO <obj>
[<obj>]
FROM DATABASE <dbtab>(<ar>) ID <id>.
REPORT xxx
TABLES indx.
IMPORT optional
<field 1> TO <field a>
<field 2> TO <field b>
. .
. .
<structure 1> TO <structure a>
. .
. .
<itab 1> TO <itab a>
. .
FROM DATABASE indx(<ar>)
ID <id>.
R

DELETE FROM DATABASE INDX(<ar>)


ID <id>.
© SAP AG

When you import data, you can list the data objects in any order in the IMPORT statement. You do
not need to import all of the data objects from your cluster. If you want the data objects in the
program to have different names to those used in the cluster, you can use the optional TO addition.
The IMPORT statement sets the return code field SY-SUBRC, which applies to the entire cluster,
not to individual data objects. SY-SUBRC is unequal to zero if the cluster does not exist.
The structure of the fields, structures, and internal tables that you want to import must correspond to
the structure of the data objects in the database, otherwise a runtime error occurs. Furthermore, you
must import the objects using the same names under which you exported them. If the cluster exists,
the return code is set to zero, whether or not objects have been imported.
Caution: The IMPORT statement always imports the body of an internal table. This means that the
header line of the table remains unchanged by the import.
The DELETE statement deletes the entire cluster and sets the return code field SY-SUBRC. You
cannot delete an individual data object within a cluster.

(C) SAP AG BC411 18-5


Key of the Database Table INDX

11 -- 33 44 -- 55 66 -- 27
27 28
28 -31
-31 Position
Position
Client
Client Area
Area Cluster
Cluster ID
ID Next
Next entry
entry Contents
Contents
001
001 a1
a1 E105
E105 0001
0001 Example
Example

Cluster area: a1 INDX


Next entry: 0003 001 a1 E10 50003

Next entry: 0000 l1 Fortsetzg


Next entry: 0002 001 a1 E10 50002
Key 001 a1 E10 50000 Next entry: 0001 001 a1l2 E10
t1 . .50001
.
Contents f1 f2 f3 l2 t1 . . .
l1 Continued
I1 l2 I3 . . .

© SAP AG

The database table INDX is an example of a table in which you can store data clusters. In your
system, it is installed with a standard key length of 31 bytes.
You can display the structure of the table from the online documentation in the ABAP Editor by
entering the table structure INDX. The key consists of client, work area, cluster ID, and next entry
number. The cluster ID has a default length of 22 bytes, but it can have any length.
For large data clusters, the runtime system automatically appends new entries with the same length.

(C) SAP AG BC411 18-6


ABAP Cluster Databases
Generated, based
on the length for the
cluster table

Structure: Created structure

Key fields
Length 3 2 n 4 m 2
Name MANDT RELID SRTF2 CLUSTR CLUSTD
Type Char Char Char INT4 INT2 LRAW

Client Work Cluster ID Next Your Length Data field


area entry own
counter fields
Examples: (optional)

INDX PERG RETL MLTS


...
R

© SAP AG

You can create your own ABAP cluster tables. To do so, proceed as follows:
Create a table in the ABAP Dictionary as a transparent table. This is your cluster database.
Use the above table structure.
You may leave out the MANDT field (if you include it, it is filled automatically).
The fields RELID, SRTF2, CLUSTR, CLUSTD, and the cluster ID are automatically filled
during an EXPORT.
The optional user-defined fields must be filled before the EXPORT. You can then analyze them after
an IMPORT.
The field names for the cluster ID and the user-defined fields can be chosen freely. The other fields
must be named as above.
The length of the part of the table used for the data cluster is the total length of the structure minus
the length of the first six fields.

(C) SAP AG BC411 18-7


Example: Catalog for INDX

REPORT
REPORT sapbc411d_clustercatalogue.
sapbc411d_clustercatalogue.
TABLES
TABLES indx.
indx.
SELECT-OPTIONS:
SELECT-OPTIONS:
area
area FOR
FOR indx-relid,
indx-relid,
clstr_id
clstr_id FOR
FOR indx-srtfd.
indx-srtfd.

START-OF-SELECTION.
START-OF-SELECTION.
SELECT
SELECT DISTINCT
DISTINCT relid
relid srtfd
srtfd aedat
aedat usera
usera pgmid
pgmid
INTO
INTO (indx-relid,
(indx-relid, indx-srtfd,
indx-srtfd, indx-aedat,
indx-aedat,
indx-usera,
indx-usera, indx-pgmid)
indx-pgmid) FROM
FROM indx
indx
WHERE
WHERE relid
relid IN
IN area
area
AND
AND srtfd
srtfd ININ clstr_id.
clstr_id.
** AND
AND srtf2
srtf2 == 0.
0.

WRITE:
WRITE: // indx-relid,
indx-relid,
indx-srtfd,
indx-srtfd,
indx-aedat
indx-aedat DD/MM/YYYY,
DD/MM/YYYY,
indx-usera,
indx-usera, R

indx-pgmid.
indx-pgmid.
ENDSELECT.
ENDSELECT.
© SAP AG

As well as its key fields and the data cluster, the structure of the database table INDX has optional
fields for administrative data (date of last change, validity date, name of user, and so on. For further
information, refer to the structure INDX.) You can use the SELECT statement to access the key and
administration fields (for example, to create a catalog). The system only fills the administration data
fields if you fill them before the EXPORT using the MOVE statement (for example, MOVE SY-
DATUM TO INDX-AEDAT).

(C) SAP AG BC411 18-8


ABAP Memory - Overview: Communication
Between Internal Sessions
R/3 terminal session

External session 1 External session 2

Internal session 1 Internal session 1


ABAP memory

Export Roll area

ABAP memory
Roll area
Import
Program 1 Program 3

Internal session 2 Internal session 2


Export Roll area Roll area
Import
Program 2 Program 4
R

© SAP AG

A single terminal session in the R/3 System consists of one or more external sessions.
Choosing System -> Create session or entering '/o….' in the command field creates a new external
session. The ABAP memory is active for the duration of an external session.
A new internal session is created when you call a transaction (CALL TRANSACTION), a dialog
module (CALL DIALOG) or a report (SUBMIT… AND RETURN).
For each internal session, the system creates a roll area containing the program data.
You can make data available to several internal sessions by copying it into ABAP memory using
EXPORT … TO MEMORY and using IMPORT … FROM MEMORY to read it.

(C) SAP AG BC411 18-9


Transporting Data Between Programs
(ABAP Memory)
ABAP memory

MYID ABAP/4
IT_SPFLI
SPFLI

PROGRAM p1 ... . PROGRAM p2 ... .


... ...
DATA: p1_spfli LIKE spfli, DATA: p2_spfli LIKE spfli,
it_spfli LIKE spfli it_spfli LIKE spfli
OCCURS 0. OCCURS 0.
... ...
IMPORT IMPORT
spfli TO p1_spfli
spfli TO p2_spfli
it_spfli
FROM MEMORY ID 'MYID'. it_spfli
R

FROM MEMORY ID 'MYID'.


SUBMIT p2.
© SAP AG

The EXPORT … TO MEMORY statement exports data as a cluster to the ABAP memory. The data
is user-specific.
Since the ABAP memory is only available within a call chain (CALL TRANSACTION, CALL
DIALOG, SUBMIT… AND RETURN), the data is lost as soon as the first program in the chain
ends.
The IMPORT statement allows you to read data from ABAP memory into your program.
Unlike the IMPORT… FROM DATABASE variant, the system does not check whether the source
and target fields have the same structure.
You can delete the whole memory using the FREE MEMORY statement, or delete the memory for
a particular ID <id> using the FREE MEMORY ID <id> statement (analogous to FREE
<itab>).

(C) SAP AG BC411 18-10


Shared Buffer - Overview

Application server 1

Export

Shared buffer
Program 1
Import

Export
Program 2
Import

© SAP AG

The cross-transaction application buffer is a memory area within an application server that is
accessible to all of the work processes of an R/3 instance.
You can use it to store and retrieve data from application programs using the statements
- EXPORT ... TO SHARED BUFFER <dbtab>(ar) ID <id> and
- IMPORT ... FROM SHARED BUFFER <dbtab>(ar) ID <id>
and delete data in the buffer using the statement
- DELETE FROM SHARED BUFFER <dbtab>(ar) ID <id>
The data in the application buffer is visible to all transactions on the application server once it has
been exported. Old data may be overwritten by new exports. This means that you should not assume
that your application can reread the same data that it stored. The data can be deleted (for example, by
another, parallel transaction), or be overwritten by new data. For this reason, you should export your
data to a cluster database as well as to the shared buffer, and double check imported data against the
cluster database. In this way, the shared buffer provides a kind of application buffer for the cluster
database. When you use the shared buffer, you may encounter space problems if the cluster is too
large. This results in a catchable runtime error (EXPORT_BUFFER_NO_MEMORY).
The storage structures used in the EXPORT, IMPORT, and DELETE statements, (database table),
must have a standardized structure.

(C) SAP AG BC411 18-11


Cluster Tables and Transparent Tables

Cluster table Transparent table

Only contains data within the In relational database


cluster
Multiple access, since the data is
Little access for large amounts of stored in different tables
data
Data can be linked and evaluated
Heterogenous data (field,
Select with any number of logical
structured fields, internal tables)
conditions
Flexible technique
Not possible to link data
Access requires cluster ID and
area
Access only returns one cluster

© SAP AG

The cluster database contains the data in the required form. The internal administration of the cluster
table means that you can read large quantities of data with relatively few database accesses.
In transparent tables, the standardization means that the data has to be selected from several tables,
requiring more access. However, this can be made more efficient by using joins (from Release 3.1)
in ABAP Open SQL (refer to the unit about ABAP Open SQL). The advantage of transparent tables
is that you can read single obejcts from different tables and relate them to other objects. Compare
this with cluster tables, where you can only read the data of a single cluster and cannot link this data
to that in other clusters.
To access cluster data, you must know the cluster ID and the work area. Furthermore, the access can
only return the data for a single cluster ID (where a SELECT loop could return more than one
cluster). In transparent tables, you can retrieve data based on any logical expression.

(C) SAP AG BC411 18-12


Summary

In this unit, you have learned how to store


data objects under an ID:
In a cluster table
In ABAP memory
In the shared bufffer

© SAP AG

(C) SAP AG BC411 18-13


Exercises

Note:
There may not be sufficient time to work
through all the exercises during the course.
The exercises marked Optional should be seen
as supplementary examples that can be used,
time permitting, during the course. Attendees
can also use these exercises after the course,
to consolidate what they have learned.

© SAP AG
Data used in the exercises:

Data from database tables SGEOCITY, SPFLI, SFLIGHT, SBOOK


All of the Repository objects used in this course can be found in development
class SAPBC411. This development class is supplied to customers. You
should find it in your IDES system.
Names of model solutions
Program name
SAPBC411S_LIST

SAPBC411S_TYPE

SAPBC411S_ASSIGN

SAPBC411S_KEYTAB_DEFINITION
SAPBC411S_KEYTAB_FILL
SAPBC411S_KEYTAB_READ
SAPBC411S_TESTFRAME_ITABS

SAPBC411S_OO_CREATE_CLASS
SAPBC411S_OO_OBJECT_METHOD
SAPBC411S_OO_INTERFACES
SAPBC411S_OO_EVENTS
SAPBC411S_OO_EVENT_PROTOCOLL

SAPBC411S_CONTEXT_GEOGR_DISTAN

SAPBC411S_FLIGHTS_OF_ONE_YEAR
SAPBC411S_READ_10_FLIGHTS
SAPBC411S_CUMULATE_LOCCURAM
SAPBC411S_SEL_SFLIGHT_SBOOK
SAPBC411S_SELECT_SUBQUERY
SAPBC411S_SELECT_HAVING
(C) SAP AG BC411 19-2
SAPBC411S_STRING_BIT_OPERATION

(C) SAP AG BC411 19-3


Unit: Development process and tools
Exercise 1: Correcting the errors in a program and
runtime analysis
Theme: Development process

1.1 Description of program:


The program displays a selection screen containing a default date range of 01.01.1900 to
01.01.2000, and a parameter in which the user can specify a column of a structure,
defined in the program. The program then displays a list of all flights within the specified
period. The list is sorted by the column chosen by the user on the selection screen.

1.2 Copy the template program SAPBC411T_LIST and all of its includes to program
ZBC411_##_LIST. Rename the includes with appropriate names.

1.3 Edit the three includes (<prefix>TOP, <prefix>E01, and <prefix>F01) and correct the
syntax errors and warnings. Edit the main program to remove the syntax errors from the
entire program.

1.4 Check the program using the extended program check and correct any errors and
warnings.

1.5 Perform a runtime analysis for your program. Find out why the runtime is so high and
correct the cause.

(C) SAP AG BC411 19-4


Activities Object Name / Description
Copy program SAPBC411T_List
Create program ZBC411_##_List

Tips & In the ABAP Editor settings, select the ‘Key words large’ option. This
tricks makes it easier to distinguish ABAP keywords from variables and macros.
You do not need to change the program logic.
You need the form routine OUTPUT to display the list.

(C) SAP AG BC411 19-5


Unit: Types
Exercise 1: Adjusting data types
Theme: Data conversions and runtime

1.5 Copy the template program SAPBC411T_TYPE to ZBC411_##_TYPE. The program


calculates the factorial of a number n.

1.6 Use the runtime analysis (Transaction SE30) to check the program for unnecessary type
conversions. Eliminate these by using a single data type throughout the program.

Activities Object Name / Description


Template program SAPBC411T_TYPE
Target program ZBC411_##_TYPE

Tips & Tricks It is possible to avoid all type P conversions in your program. The only
type P conversions that should take place are those in system programs.

(C) SAP AG BC411 19-6


Unit: Field symbols
Exercise 1: Assigning an object to a field symbol
Theme: Different ways of assigning field symbols using the
ASSIGN statement

1.1 Copy the template program SAPBC411T_ASSIGN to ZBC411_##_ASSIGN. The


program reads entries from table SFLIGHT for a given airline, and displays the column
of the table specified in the ‘COMPONO’ parameter. There is an error in the program
that prevents it from running properly.

1.2 Correct the error.

1.3 The required column is displayed with length 30. Change the program so that the
minimum length is displayed, that is, the contents of the field without any trailing spaces.

1.4 Change the program so that the user can enter the component name instead of the
component number.

1.5 a) For the first solution, use


ASSIGN COMPONENT
Optional:
b) Create a second solution that does not use the
ASSIGN COMPONENT statement.

(C) SAP AG BC411 19-7


Activities Object Name / Description
Template program SAPBC411T_ASSIGN
Target program ZBC411_##_ASSIGN

(C) SAP AG BC411 19-8


Unit: Internal tables
Exercise 1:
Theme: Defining internal tables
1.1 Write a program that defines an internal table of each of the three
table types standard, sorted, and hashed.

1.2 Start by defining a line type. This should have the following
structure: TYPES: a TYPE i,
b(1000) TYPE c,
d TYPE p.

1.3 Define the standard and sorted tables with a non-unique key, and the
hashed table with a unique key. The key field in all three cases should
be field a. Define all of the tables without header lines.

Activities Object Name / Description


Program ZBC411_##_itab

Tips &
Tricks

(C) SAP AG BC411 19-9


Unit: Internal tables
Exercise 2:
Theme: Filling internal tables
2.1 Write a program that fills the internal tables that you defined in
exercise 1.

2.2 Do this by defining a parameter in which you can define the


number of entries that you want to add to the table. Use the
parameter to number key field a in ascending order. You can use
any values for the two other fields.

Activities Object Name / Description


Program ZBC411_##_itab

Tips & You can fill all three table types using the statement INSERT <wa> INTO
Tricks TABLE <table>.

(C) SAP AG BC411 19-10


Unit: Internal tables
Exercise 3: Accessing a single line of an internal table
Theme: Runtime of single line access

3.1 Write a program to read a single line from each of the internal
tables that you filled in exercise 2.

3.2 In your program, define a parameter that you can use to specify the
key of the entry you want to read.

3.3 Optional: Measure the runtime required to read the data for the
different table types by embedding your program in the test
framework program.

3.4 Optional: Copy the program SAPBC411T_TESTFRAME to the


program ZBC411T_##_TESTFRAME_ITAB and copy the
corresponding lines of the program ZBC411_##_ITAB into the
form routines f1, f2, and f3. Form routine is an empty routine to
allow the program to measure the runtime of a subroutine call.
Place the data definitions from your program in the TOP include of
the measurement program.

Activities Object Name / Description


Program ZBC411_##_itab
Program template for runtime ZBC411T_testframe
measurement
Optional: Your program for ZBC411_##_testframe
measuring the runtime (copied from
template)

Tips & You can read from all three table types using the statement
READ TABLE <table> WITH TABLE KEY a = <parameter> INTO wa.

(C) SAP AG BC411 19-11


Tricks

(C) SAP AG BC411 19-12


Unit: ABAP Objects
Exercise 1: Defining and implementing classes
Theme: Classes

1.1 Write a program to create the classes C_SHIP and S_TRUCK


1.2 You should both define and implement the classes. At this stage,
create only the private and class attributes (you will add methods
and other features in subsequent exercises). Both classes should
have the attributes listed below.
1.3 Define the attribute INST_ID in the classes as a class attribute. This
will act as a counter for the various instances.
1.4 Define the attribute ID for the number of an instance and the
attribute SHIP_SPEED or TRUCK_SPEED for the current speed.

1.5 Create the following objects for the program:

Activities Object Name / Description


Program ZBC411_##_OO_create_class
Class C_SHIP: Ship class
Class C_TRUCK: Truck class
Attribute SHIP_SPEED, TRUCK_SPEED: speed
Type: integer
Attribute MAX_SPEED: maximum speed
Type: integer
Attribute ID: Identity
Type: integer
Class attribute INST_ID: Instance ID
Type: integer

(C) SAP AG BC411 19-13


Unit: ABAP Objects
Exercise 2: Defining, implementing, and calling methods
Theme: Methods

2.1 Extend the program you wrote in exercise 1 by defining and


implementing methods.
2.2 Both classes should have the methods CONSTRUCTOR,
SPEED_UP, STOP, and WRITE. None of the methods has an
interface.
2.3 Define the instances OSHIP and OTRUCK, and two internal tables
that can store the instances of the classes you have defined.
2.4 Using a DO loop for each class, create two instances of each of the
classes C_TRUCK and C_SHIP and add them to the appropriate
internal table.
2.5 Use a LOOP statement to process the entries of each internal table.
Within the loop, call the methods SPEED_UP and WRITE for the
corresponding instances.

(C) SAP AG BC411 19-14


2.6 Create the following objects for the program:

Activities Object Name / Description


Program ZBC411_##_OO_object_method
Method CONSTRUCTOR: Increase the class
attribute INST_ID by 1, assign the value
to the ID attribute, and set the
MAX_SPEED attribute to 30 for class
C_SHIP and to 140 for class C_TRUCK.
Method SPEED_UP: Check that SPEED is less
than MAX_SPEED, and then increase
the speed by 10 for C_SHIP or by 20 for
C_TRUCK.
Method STOP: Set SPEED to 0.
Method WRITE: Display the following:
'TRUCK- ID = <value>
SPEED = <value>'
Instance OSHIP
OTRUCK
Internal table SHIP_TAB
TRUCK_TAB
with type REF TO class
C_SHIP or C_TRUCK

Tips & Tricks Do not forget to insert the START-OF-SELECTION statement at the
appropriate point.

(C) SAP AG BC411 19-15


Unit: ABAP Objects
Exercise 3: Defining, implementing, and using interfaces
Theme: Interfaces

3.1 Extend your program from exercise 2 by enclosing repetitively-


used logic in an interface that presents a common point of contact
for both classes. Define and implement the interface I_VEHICLE.

3.2 The methods SPEED_UP, STOP, and WRITE, and the attributes
ID and MAX_SPEED should now be defined in the interface, and
implemented in the classes C_SHIP and C_TRUCK. The methods
have no interface.
3.3 Implement the CONSTRUCTOR method so that the interface
attribute ID is supplied with the value of the class attribute
INST_ID. You will also need to adjust the interface attribute
MAX_SPEED accordingly.
3.4 Change the main program so that the two internal tables are replaced
by a single table veh_tab that can contain references to the interface.
3.5 Define an interface reference variable IVEHICLE.
3.6 In a DO lop, fill the internal table VEH_TAB and call the interface
methods SPEED_UP, WRITE, STOP, and WRITE.

(C) SAP AG BC411 19-16


Create the following objects in your program:

Activities Object Name / Description


Program ZBC411_##_OO_interfaces
Interface I_VEHICLE: Methods SPEED_UP,
STOP, WRITE
Attributes: ID and MAX_SPEED.
Method CONSTRUCTOR: Supply values to the
interface attributes ID and
MAX_SPEED.
Attribute Define INST_ID as a class attribute.
Interface method SPEED_UP: Change the name of the
method and its attributes as required. Its
function does not change.
Interface method STOP: Change the name of the method
and its attributes as required. Its function
does not change.
Method WRITE: Change the name of the method
and attributes as required. Its function
does not change.
Internal table VEH_TAB: Replaces the two previous
internal tables. Line type: TYPE REF TO
I_VEHICLE.
Interface reference variable IVEHICLE Type: TYPE REF TO
I_VEHICLE.
DO loops APPEND to the internal table
LOOP Call the interface methods
SPEED_UP, WRITE, STOP, WRITE

(C) SAP AG BC411 19-17


Unit: ABAP Objects
Exercise 4: Defining, calling, handling, and registering
events
Theme: Events

4.1 Copy the template program SAPBC411T_OO_EVENTS to


ZBC411_##_OO_EVENTS and include event handling in it. The
program allows you to create instances of the classes C_SHIP and
C_TRUCK using pushbuttons. You can also call the methods
SPEED_UP, WRITE and STOP using pushbuttons if the cursor is
on an existing object.
4.2 Familiarize yourself with the program SAPBC411S_OO_EVENTS.

4.3 Insert two events. 1.) The interface event SPEED_CHANGE with
export parameter NEW_SPEED and 2.) the class event
BUTTON_CLICKED with export parameter FCODE.
4.4 The event SPEED_CHANGE should be triggered by the interface
methods SPEED_UP and STOP and be handled by the handler
method LIST_CHANGE in the new class C_LIST. The event
BUTTON_CLICKED should be triggered by the class method
USER_ACTION of the new class STATUS and be handled by the
handler method FCODE_HANDLER in class C_LIST.
4.5 Use SET HANDLER to register both handler methods.
4.6 Make the necessary changes at the appropriate points in the
program code.

(C) SAP AG BC411 19-18


4.7 Create the following objects for the program:

Activities Object Name / Description


Program template SAPBC411T_OO_events
Target program ZBC411_##_OO_events
Interface event SPEED_CHANGE
Exporting parameter NEW_SPEED type
I, passed by value
Class event BUTTON_CLICKED
Exporting parameter
FCODE LIKE SY-UCOMM, passed by
value
Handler method FCODE_HANDLER
in the PUBLIC SECTION of class
C_LIST. Define this method for the
event BUTTON_CLICKED of class
status, receiving the import parameter
FCODE.
Handler method LIST_CHANGE
in the PUBLIC SECTION of class
C_LIST. Define this method for the
event SPEED_CHANGE of interface
I_VEHICLE, receiving the import
parameter NEW_SPEED.
Trigger event The interface methods SPEED_UP and
STOP should call the event
SPEED_CHANGE in all classes using
the RAISE EVENT statement and
passing the export parameter. The
parameter must be supplies with the
value of the corresponding actual
parameter.
Trigger event The class event BUTTON_CLICKED
should be triggered by the method
USER_ACTION in class STATUS. Its
export parameter is FCODE, which is set
when the user chooses a pushbutton
(FCODE = SY-UCOMM).
Register events In the main program, register the handler
methods FCODE_HANDLER and
LIST_CHANGE. Register
LIST_CHANGE with the addition FOR
ALL INSTANCES so that it applies to
all instances of the class C_LIST.

(C) SAP AG BC411 19-19


(C) SAP AG BC411 19-20
Unit: ABAP Objects
Exercise 5: Defining, calling, handling, and registering
events
Theme: Logging with events

5.1 Extend your program ZBC411_##_OO_EVENTS or copy the model solution


SAPBC411S_OO_EVENTS to ZBC411_##_OO_EVENTS and include more event
handling. Create a log of the functions that the user has chosen and display a list the first
time the user chooses Cancel. The program should not end until the user presses Cancel a
second time. Familiarize yourself with program
SAPBC411S_OO_EVENT_PROTOKOLL.

5.2 You need to extend the existing program in three places. 1.) Define and implement a class
C_PROTOKOLL with the public class methods FCODE_HANDLER and
WRITE_PROTOCOLL, the public static attribute PROTOCOLL_WRITTEN, and the
private static attribute FCODE_TAB, an internal table for storing the function codes
triggered by the user.

5.3 The method FCODE_HANDLER is the handler method for the event
BUTTON_CLICKED in class STATUS. It imports the function code from the variable
FCODE.

5.4 2.) In the method FCODE_HANDLER of class C_LIST, you need to find out whether the
static variable PROTOCOLL_WRITTEN = 1 when the user chooses CANCEL. If it is,
leave the program. If not, call the static method WRITE_PROTOCOLL of the class
C_PROTOCOLL, and stop the CASE statement with the STOP statement.
5.5 In the method WRITE_PROTOCOLL, loop through the internal table FCODE_TAB and
display the contents. Afterwards, set the attribute PROTOCOLL_WRITTEN to 1.

5.6 Include another SET HANDLER statement to register the method FCODE_HANDLER
for the class C_PROTOKOLL.

(C) SAP AG BC411 19-21


5.7 Create the following objects for the program:

Activities Object Name / Description


Program template SAPBC411S_OO_events or your program
ZBC411_##_OO_events

Define and implement a class C_PROTOCOLL


Class definition FCODE_HANDLER for the event
Public section: class methods BUTTON_CLICKED of class STATUS.
Importing parameter FCODE
WRITE_PROTOCOLL, no interface
PROTOCOLL_WRITTEN TYPE i
Static attribute READ ONLY.
Private section: Internal table FCODE_TAB LIKE sy-ucomm
OCCURS 0.
Class implementation FCODE_HANDLER should inserts
FCODE into the internal table
FCODE_TAB.
WRITE_PROTOCOLL: Loop through the
internal table FCODE_TAB into a local
variable within the method and display the
contents. Then set the static variable
PROTOCOLL_WRITTEN to 1.
Handle event The handler method FCODE_HANDLER
in class C_LIST needs to be changed for
the CANCEL function so that you leave
the program if the static variable
PROTOCOLL_WRITTEN has the value 1
(C_PROTOCOLL=>
PROTOCOLL_WRITTEN = 1),
otherwise, you call the static method
WRITE_PROTOCOLL (CALL
METHOD C_PROTOCOLL=>
WRITE_PRTOCOLL) and then leave the
CASE statement with the STOP
statement.
Register event In the main program, register the handler
method FCODE_HANDLER.
(SET HANDLER
C_PROTOCOLL=>FCODE_HANDLER)

(C) SAP AG BC411 19-22


(C) SAP AG BC411 19-23
Unit: Contexts
Exercise 1: Creating a context to calculate the distance
between two cities
Theme: Creating contexts

1.7 Create a context to calculate the distance between two cities. It


should consist of the following modules:

1.8 Context C_GEOGR_INFO and the function module


CONTEXT_DEMO_COMPUTE_DISTANCE, which calculates
the distance.

It is your task to create a general context for an application that allows a


program to efficiently calculate the distance between two cities.

Activities Object Name / Description


Context ZBC411_##_C_Geogr_Dist

1.3 Create the context and test it within the Context Builder.
Tips &
Tricks

(C) SAP AG BC411 19-24


Unit: Contexts
Exercise 2: Using the context to calculate the distance
between two cities
Theme: Using contexts in programs
2.1 Write a program that uses the context ZBC411_##_C_Geogr_Dist to
calculate the distance between two cities.

2.2 To do this, define a context instance in your program and use the
SUPPLY statement to pass values for the key fields to it. Calculate
the distance between NEW YORK and FRANKFURT, retrieve it
from the context using the DEMAND statement, and display it on a
list. Leave error handling to the system.

1.

Activities Object Name / Description


Program ZBC411_##_Geogr_Dist

Tips &
Tricks

(C) SAP AG BC411 19-25


Unit: ABAP Open SQL
Exercise 1: Read all flights for one year
Theme: Keeping the result set small
1.1 Write a program that displays all flights for a given year from the
table SFLIGHT. Make it possible for the user to enter the year in a
PARAMETER. Read the appropriate entries from SFLIGHT and
display any of their fields in a list.

Activities Object Name / Description


Program ZBC411_##_Flights_Of_One_Year

1.2 Once you have written the program, run the SQL trace on it to measure your database
access times.

Tips &
Tricks

(C) SAP AG BC411 19-26


Unit: ABAP Open SQL
Exercise 2: Reading the first 10 flights
Theme: Minimizing the amount of data transferred
2.3 Write a program that reads the first ten entries for airline LH from
table SFLIGHT (the order in which they occur is not important).
Display the following fields in a list:
SFLIGHT-CARRID
SFLIGHT-CONNID
SFLIGHT-FLDATE
SFLIGHT-PRICE
SFLIGHT-CURRENCY

Activities Object Name / Description


Program ZBC411_##_Read_10_Flights

2.2 Once you have written the program, run the SQL trace on it to measure your database
access times.

Tips &
Tricks

Unit: ABAP Open SQL


Exercise 3: Reading data and calculating the sum
Theme: Minimizing the amount of data transferred
(C) SAP AG BC411 19-27
3.2 Write a program to calculate the booking revenue for 1998 from
field SBOOK-LOCCURAM of table SBOOK.

3.5 You work for a travel agency, and have to write a program that
produces the list described above. The list should have the
following format:
Airline Flight No. Amount in local currency
----------------------------------------------------------------------
AA 0017 4590
AA 0026 8730

Activities Object Name / Description


Program ZBC411_##_Cumulate_Loccuram

3.6 Once you have written the program, run the SQL trace on it to measure your database
access times.
Tips &
Tricks

Unit: ABAP Open SQL


Exercise 4: Reading from more than one table
Theme: Minimizing the number of transfers

(C) SAP AG BC411 19-28


4.1 Write a program that displays the all not overbooked flights of the
year 1998 between Frankfurt and New York.

4.2 You work for a travel agency, and have to write a program that
produces the list described above. The list should display the fields
CARRID, CONNID, and FLDATE.
Carrier Flight number Flight date
------------------------------------------------------
AA 0017 12.29.1998
LH 0400 12.21.1998

Activities Object Name / Description


Program ZBC411_##_Sel_Sflight_Sbook

4.3 Once you have written the program, run the SQL trace on it to measure your database
access times.

Tips &
Tricks

Unit: ABAP Open SQL


Exercise 5: Reading high and low values
Theme: Minimizing the number of transfers

(C) SAP AG BC411 19-29


5.1 Write a program that finds and displays, for each flight in
SFLIGHT, the date with the most seats booked (field SEATSOCC).

5.2 You work for a travel agency, and have to write a program that
produces the list described above. The list should display the fields
CARRID, CONNID, and FLDATE, and the maximum value of the
field SEATSOCC.

5.3 Note: It is not asked for one flight with the most flight, but for all
flights that eventually contain the maximum value.

Activities Object Name / Description


Program ZBC411_##_Sel_Max_Seatsocc

5.4 Once you have written the program, run the SQL trace on it to measure your database
access times.

Tips &
Tricks

Unit: ABAP Open SQL


Exercise 6: Reading grouped data with particular
conditions

(C) SAP AG BC411 19-30


Theme: Minimizing the amount of data transferred

6.1 Write a program to find the number of passengers and the average
luggage weight of all Lufthansa flights after Dec. 01 1998 having
an average luggage weight of 20 kg.

6.2 You work for a travel agency and it is your task to write a program
that produces the list described above. The list should contain the
fields CARRID (‘LH’), CONNID, FLDATE; the average luggage
weight (LUGGWEIGHT) and the total number of all passengers
(COUNT(*)),and be structured as follows:
CARRID CONNID FLDATE avg. LUGGWEIGHT number of pass.
LH 0400 12.02.1998 31 12

Activities Object Name / Description


Program ZBC411_##_Select_Having

1.4 Once you have written the program, run the SQL trace on it to measure your database
access times.

(C) SAP AG BC411 19-31


Tips & Use the addition GROUP BY carrid connid fldate in the SELECT
Tricks statement.

(C) SAP AG BC411 19-32


Unit: String Processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: String processing

1.9 Write a program to convert the value of a type I input field into a
binary string. Display the binary string as a 32-character type C
field.

Activities Object Name / Description


Program ZBC411_##_String_Operation

Tips & Method: Use a WHILE loop with the MOD and DIV statements to retrieve
Tricks the individual bits of the input value and place them in an output field
using CONCATENATE.
Use a loop counter to count the number of digits, and then use the
SHIFT <output field> RIGHT BY <number> PLACES,
to shift free places to the right. Use
TRANSLATE <output field> USING <val>
to change the spaces to zeros.
You can use the template program SAPBC411T_STRING_OPERATION
for your solution

(C) SAP AG BC411 19-33


Unit: Bit processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: Bit processing

1.10 Repeat the string processing exercise, but this time use bit
operations.
Write a program to convert the value of a type I input field into a
binary string. Display the binary value in a 32-character type C
field.

Activities Object Name / Description


Program ZBC411_##_ Bit_Operation

Tips &
Tricks
One way of solving this problem is to place the input value into a hex field
and use a WHILE loop and the
GET BIT sy-index OF <hexfield> INTO <field>
statement to find out which bits have the value 1.
You then need to place these bits into the output field with the correct
offset. Before you start, initialize the output field using
CLEAR <output field> WITH '0'.
You may use the template program SAPBC411T_##_BIT_OPERATION
for your solution.

(C) SAP AG BC411 19-34


Solutions

© SAP AG
Unit: Development process and tools
Exercise 1: Correcting the errors in a program and
runtime analysis
Theme: Development process

Model solution SAPBC410S_LIST


TOP include
*&-------------------------------------------------------------*
*& Include BC411S_LISTTOP
*
*&
*
*&-------------------------------------------------------------*

PROGRAM sapbc411s_list MESSAGE-ID bc411 LINE-SIZE 130.

*TABLES statement not necessary

PARAMETERS:
s_from TYPE s_date DEFAULT '19000101',
s_to TYPE s_date DEFAULT '20000101',
s_sort(1) TYPE c DEFAULT '1'.

DATA:
slist TYPE tab_slist,
result TYPE c.

*CONSTANTS c_length is not used

*Macro definition increases runtime unnecessarily

(C) SAP AG BC411 20-2


SAPBC411S_LISTEE01 Include (Event include)
*--------------------------------------------------------------*
* INCLUDE BC411S_LISTE01
*
*--------------------------------------------------------------*
*wrong parameters passed

CALL FUNCTION 'SAPBC411_GET_DATA' EXPORTING p_from = s_from


p_to = s_to
IMPORTING p_list = slist
EXCEPTIONS no_data = 1.
*Returncode check and possible EXIT statement were missing

IF sy-subrc <> 0.
WRITE 'No flights found'(001).
EXIT.
ENDIF.

*Spelling error and wrong parameter passed


PERFORM sort TABLES slist USING s_sort CHANGING result.

IF result = space.
MESSAGE s000.
ENDIF.

*Spelling error and wrong parameter passed


PERFORM output USING slist.

(C) SAP AG BC411 20-3


SAPBC411S_LISTEF01 (Form include)
*---------------------------------------------------------------*
* INCLUDE BC411S_LISTF01
*
*---------------------------------------------------------------*

*pass parameter p_sortindex as reference


FORM sort TABLES p_list TYPE tab_slist
USING p_sortindex TYPE c
CHANGING p_result TYPE c.

*l_field1(clength) not required


*defining l_component as type i reduces unnecessary type p
*conversion
*see runtime analyses

DATA:
l_component TYPE i.
FIELD-SYMBOLS
<l_fs>.
p_result = 'X'.
*spelling error
l_component = p_sortindex.
*Spelling error in field symbol
ASSIGN COMPONENT l_component OF STRUCTURE p_list TO <l_fs>.
* Clear before EXIT
IF sy-subrc <> 0.
CLEAR p_result.
EXIT.
ENDIF.
SORT p_list BY <l_fs>.
*Macro definition increases runtime. Macro unnecessary
ENDFORM.

*---------------------------------------------------------------*
* FORM OUTPUT
*
*---------------------------------------------------------------*

(C) SAP AG BC411 20-4


*
*Pass Parameter p_list with VALUE

FORM output USING p_list TYPE tab_slist.


DATA:
*Spelling error: LIKE LINE OF p_list instead of LIKE LINE OF *
*l_list
l_list_wa LIKE LINE OF p_list.
*Status LISTE instead of LIST. And SET PF-STATUS only once
*outside of the LOOP.
SET PF-STATUS 'LISTE'.

LOOP AT p_list INTO l_list_wa.


*l_list_wa-price without currency clause
WRITE: /
l_list_wa-fldate,
l_list_wa-countryfr,
l_list_wa-cityfrom,
l_list_wa-countryto,
l_list_wa-cityto,
l_list_wa-price CURRENCY l_list_wa-currency,
l_list_wa-currency.
ULINE.
ENDLOOP.
WRITE 'End of list'(002).
ENDFORM.

*empty FORM work. Not necessary

*PERFORM after FORM can not be reached.

(C) SAP AG BC411 20-5


Unit: Types
Exercise 1: Adjusting Data Types
Theme: Runtime of Data Type Conversions

Solution SAPBC411S_TYPE

*&-----------------------------------------------------------------*
*& Report SAPBC411T_TYPE
*
*&-----------------------------------------------------------------*
*&
*

REPORT sapbc411t_type .

PARAMETERS:
*n type i avoids type P conversions. Also true for variable result
n TYPE i.

DATA:
result TYPE i.

*n of Type i. Don't pass as string. Avoids internal conversions.


IF n > 12.
WRITE 'N is too large'(001).
EXIT.
ENDIF.

PERFORM fakultaet USING n CHANGING result.

WRITE: / n, result.

*------------------------------------------------------------------*
* FORM FAKULTAET
*

(C) SAP AG BC411 20-6


*------------------------------------------------------------------*
* --> VALUE(P_N)
*
* --> P_RESULT
*
*------------------------------------------------------------------*
*p_n pass as reference is faster. Complete type definition reduces
*errors.
FORM fakultaet USING p_n TYPE i
CHANGING p_result TYPE i.
DATA:
*l_temp only with length 1 required. Defined as type i avoids
*conversions in calculations

l_temp TYPE i.
*Value 0 not as string. Avoids internal conversions. Also true with
*p_result

IF p_n = 0.
p_result = 1.
EXIT.
ENDIF.
*Don't pass value 1 as string
l_temp = p_n - 1.
PERFORM fakultaet USING l_temp CHANGING p_result.
p_result = p_n * p_result.

ENDFORM.

(C) SAP AG BC411 20-7


Unit: Field symbols
Exercise 1: Assigning an object to a field symbol
Theme: Different ways of assigning field symbols using the
ASSIGN statement

Model solution SAPBC410S_BIT_OPERATION


*&------------------------------------------------------------------
*& Report SAPBC411S_ASSIGN
*&
*&------------------------------------------------------------------

REPORT sapbc411t_assign.

PARAMETERS:
carrid TYPE sflight-carrid DEFAULT 'LH',
compno TYPE i DEFAULT '1',
compname(8) TYPE c DEFAULT 'CONNID'.

PERFORM write_selected_field USING compno.


ULINE.
PERFORM write_selected_field_2 USING compname.
ULINE.
PERFORM write_selected_field_3 USING compname.

*------------------------------------------------------------------*
* FORM WRITE_SELECTED_FIELD
*
*------------------------------------------------------------------*
* ........
*
*------------------------------------------------------------------*
* --> P_COMPNO
*

(C) SAP AG BC411 20-8


*------------------------------------------------------------------*

FORM write_selected_field USING p_compno TYPE any.

DATA:
l_wa_sflight TYPE sflight,
l_field(30) TYPE c,
l_length TYPE i.
FIELD-SYMBOLS:
<l_fs>.

SELECT * FROM sflight INTO l_wa_sflight WHERE carrid = carrid.


PERFORM assign_component USING l_wa_sflight
p_compno
CHANGING l_field.
l_length = STRLEN( l_field ).
ASSIGN l_field(l_length) TO <l_fs>.
IF sy-subrc = 0.
WRITE / <l_fs> COLOR COL_NEGATIVE.
ENDIF.
ENDSELECT.
ENDFORM.
*------------------------------------------------------------------*
* FORM ASSIGN_COMPONENT
*
*------------------------------------------------------------------*
* ........
*
*------------------------------------------------------------------*
* --> P_STRUCTURE
*
* --> P_COMPONENT
*
* --> P_RESULT
*
*------------------------------------------------------------------*
FORM assign_component USING p_structure TYPE any
p_component TYPE any
CHANGING p_result TYPE any.
FIELD-SYMBOLS:
<l_fs>.

(C) SAP AG BC411 20-9


ASSIGN COMPONENT p_component OF STRUCTURE p_structure TO <l_fs>.
MOVE <l_fs> TO p_result.

ENDFORM.
*------------------------------------------------------------------*
* FORM WRITE_SELECTED_FIELD_2
*
*------------------------------------------------------------------*
* ........
*
*------------------------------------------------------------------*
* --> P_COMPNO
*
*------------------------------------------------------------------*
FORM write_selected_field_2 USING p_compname TYPE c.

DATA:
l_wa_sflight TYPE sflight,
l_field(30) TYPE c,
l_length TYPE i.
FIELD-SYMBOLS:
<l_fs>.

SELECT * FROM sflight INTO l_wa_sflight WHERE carrid = carrid.


PERFORM assign_component USING l_wa_sflight
p_compname
CHANGING l_field.
l_length = STRLEN( l_field ).
ASSIGN l_field(l_length) TO <l_fs>.
WRITE / <l_fs> COLOR COL_NEGATIVE.
ENDSELECT.

ENDFORM.

(C) SAP AG BC411 20-10


*------------------------------------------------------------------*
* FORM WRITE_SELECTED_FIELD_3
*
*------------------------------------------------------------------*
* ........
*
*------------------------------------------------------------------*
* --> P_COMPNO
*
*--------------------------------------------------------------------
-*
FORM write_selected_field_3 USING p_compname TYPE c.

DATA:
l_wa_sflight TYPE sflight, "#EC *
l_field_name(30) TYPE c,
l_length TYPE i.

FIELD-SYMBOLS:
<l_fs>.

SELECT * FROM sflight INTO l_wa_sflight WHERE carrid = carrid.


CONCATENATE 'L_WA_SFLIGHT-' p_compname INTO l_field_name.
ASSIGN (l_field_name) TO <l_fs>.
l_length = STRLEN( <l_fs> ).
ASSIGN <l_fs>(l_length) TO <l_fs>.
WRITE / <l_fs> COLOR COL_NEGATIVE.
ENDSELECT.

ENDFORM.

(C) SAP AG BC411 20-11


Unit: Internal Tables
Exercise 1
Theme: Defining Internal Tables

Soultion SAPBC411S_KEYTAB_DEFINITION
*&-----------------------------------------------------------------*
*& Report SAPBC411S_KEYTAB_DEFINITION
*
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411s_keytab_definition .

TYPES: BEGIN OF struc,


a TYPE i,
b(1000) TYPE c,
d TYPE p,
END OF struc.

DATA: std_tab TYPE STANDARD TABLE OF struc


WITH NON-UNIQUE KEY a,
sort_tab TYPE SORTED TABLE OF struc
WITH NON-UNIQUE KEY a,
hash_tab TYPE HASHED TABLE OF struc
WITH UNIQUE KEY a.

(C) SAP AG BC411 20-12


Unit: Internal Tables
Exercise 2:
Theme: Filling internal tables

Solution SAPBC411S_KEYTAB_FILL
*&-----------------------------------------------------------------*
*& Report SAPBC411S_KEYTAB_FILL *
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411s_keytab_fill.
* Type definition for internal tables

TYPES: BEGIN OF struc,


a TYPE i,
b(1000) TYPE c,
d TYPE p,
END OF struc.

* internal table definition

DATA: std_tab TYPE STANDARD TABLE OF struc


WITH NON-UNIQUE KEY a,
sort_tab TYPE SORTED TABLE OF struc
WITH NON-UNIQUE KEY a,
hash_tab TYPE HASHED TABLE OF struc
WITH UNIQUE KEY a.

PARAMETERS: value TYPE i.


DATA: wa TYPE struc.

(C) SAP AG BC411 20-13


* fill internal tables

DO value TIMES.
wa-a = sy-index.
wa-b = 'interne Tabellen machen Spaß'(001).
wa-d = '100.01'.
INSERT wa INTO TABLE std_tab.
INSERT wa INTO TABLE sort_tab.
INSERT wa INTO TABLE hash_tab.
ENDDO.

(C) SAP AG BC411 20-14


Unit: Internal Tables
Exercise 3: Accessing a single entry
Theme: Runtime for accessing single entries

Solution SAPBC411S_KEYTAB_READ
*&-----------------------------------------------------------------*
*& Report SAPBC411S_KEYTAB_DEFINITION
*
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411s_keytab_definition .

* Type definition for internal tables

TYPES: BEGIN OF struc,


a TYPE i,
b(1000) TYPE c,
d TYPE p,
END OF struc.

* internal table definition

DATA: std_tab TYPE STANDARD TABLE OF struc


WITH NON-UNIQUE KEY a,
sort_tab TYPE SORTED TABLE OF struc
WITH NON-UNIQUE KEY a,
hash_tab TYPE HASHED TABLE OF struc
WITH UNIQUE KEY a.

PARAMETERS: value TYPE i, read_val TYPE i.

DATA: wa TYPE struc.

* fill internal tables


DO value TIMES.

(C) SAP AG BC411 20-15


wa-a = sy-index.
wa-b = 'interne Tabellen machen Spaß'(001).
wa-d = '100.01'.
INSERT wa INTO TABLE std_tab.
INSERT wa INTO TABLE sort_tab.
INSERT wa INTO TABLE hash_tab.
ENDDO.

*read a line from the internal tables.

READ TABLE std_tab INTO wa WITH TABLE KEY a = read_val.


WRITE: / wa-a, wa-b, wa-d.
READ TABLE sort_tab INTO wa WITH TABLE KEY a = read_val.
WRITE: / wa-a, wa-b, wa-d.
READ TABLE hash_tab INTO wa WITH TABLE KEY a = read_val.
WRITE: / wa-a, wa-b, wa-d.

(C) SAP AG BC411 20-16


Unit: ABAP Objects
Exercise 1: Defining and Implementing Classes
Theme: Classes

Solution SAPBC411S_OO_CREATE_CLASS
REPORT oo_interfaces_1 NO STANDARD PAGE HEADING.

********************************************************************
* Simple example for classes definition and implementation.
********************************************************************

CLASS c_ship DEFINITION.


PUBLIC SECTION.
* methods/interfaces will be defined later
PRIVATE SECTION.
DATA: ship_speed TYPE i.
DATA: max_speed TYPE i VALUE 30.
DATA: id TYPE i.
CLASS-DATA: inst_id TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.


PUBLIC SECTION.
* methods/interfaces will be defined later
PRIVATE SECTION.
DATA: truck_speed TYPE i.
DATA: max_speed TYPE i VALUE 10.
CLASS-DATA: inst_id TYPE i.
ENDCLASS.

(C) SAP AG BC411 20-17


********************************************************************
* Implementations
********************************************************************

CLASS c_ship IMPLEMENTATION.


* here all METHOD will be implemented
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.


* here all METHOD will be implemented
ENDCLASS.

********************************************************************
* Program
********************************************************************

START-OF-SELECTION.

(C) SAP AG BC411 20-18


Unit: ABAP Objects
Exercise 2: Creating Instances, Defining, Implementing,
and Calling Methods
Theme: Instances and Methods

Solution SAPBC411S_OO_OBJECTS_METHODS
REPORT sapbc411s_oo_object_method NO STANDARD PAGE HEADING.

********************************************************************
* Simple example for classes definition/implementation with methods
********************************************************************

CLASS c_ship DEFINITION.


PUBLIC SECTION.
New parts are marked bold and italic
METHODS constructor. "Is called automatically in Rel. 4.5A in
"CREATE OBJECT
METHODS speed_up.
METHODS stop.
METHODS write.
PRIVATE SECTION.
DATA: ship_speed TYPE i.
DATA: max_speed TYPE i VALUE 30.
DATA: id TYPE i.
CLASS-DATA: inst_id TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.


PUBLIC SECTION.

(C) SAP AG BC411 20-19


METHODS constructor. "Is called automatically in Rel. 4.5A
"in CREATE OBJECT
METHODS speed_up.
METHODS stop.
METHODS write.
PRIVATE SECTION.
DATA: truck_speed TYPE i.
DATA: max_speed TYPE i VALUE 10.
DATA: id TYPE i.
CLASS-DATA: inst_id TYPE i.

ENDCLASS.

********************************************************************
* Implementations
********************************************************************

CLASS c_ship IMPLEMENTATION.


METHOD constructor.
inst_id = inst_id + 1.
id = inst_id.
max_speed = 30.
ENDMETHOD.
METHOD speed_up.
CHECK ship_speed < max_speed.
ship_speed = ship_speed + 10.
ENDMETHOD.
METHOD stop.
ship_speed = 0.
ENDMETHOD.
METHOD write.
WRITE: / 'Ship: ID = ', id, ' Speed = ', ship_speed.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.


METHOD constructor.

(C) SAP AG BC411 20-20


inst_id = inst_id + 1.
id = inst_id.
max_speed = 130.
ENDMETHOD.
METHOD speed_up.

CHECK truck_speed < max_speed.


truck_speed = truck_speed + 50.
ENDMETHOD.
METHOD stop.
truck_speed = 0.
ENDMETHOD.
METHOD write.
WRITE: / 'Truck: ID = ', id, ' Speed = ', truck_speed.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Program
********************************************************************

START-OF-SELECTION.
DATA oship TYPE REF TO c_ship.
DATA otruck TYPE REF TO c_truck.

DATA ship_tab TYPE REF TO c_ship OCCURS 0.


DATA truck_tab TYPE REF TO c_truck OCCURS 0.
*-------------------------------------------------------------------
*--- create some instances (ID is set automatically).
DO 2 TIMES.
CREATE OBJECT oship.
CALL METHOD oship->constructor.
APPEND oship TO ship_tab.
ENDDO.
DO 2 TIMES.
CREATE OBJECT otruck.
CALL METHOD otruck->constructor.
APPEND otruck TO truck_tab.
ENDDO.

(C) SAP AG BC411 20-21


*---- speed up and write
LOOP AT ship_tab INTO oship.
CALL METHOD oship->speed_up.
CALL METHOD oship->write.
ENDLOOP.
LOOP AT truck_tab INTO otruck.
CALL METHOD otruck->speed_up.
CALL METHOD otruck->write.
ENDLOOP.

(C) SAP AG BC411 20-22


Unit: ABAP Objects
Exercise 3: Defining, Implementing, and Using Interfaces
Theme: Interfaces

Solution SAPBC411S_OO_INTERFACES
REPORT sapbc411s_oo_interfaces NO STANDARD PAGE HEADING.

********************************************************************
* Simple example of interfaces
********************************************************************
new parts are marked bold, italic
INTERFACE i_vehicle.
DATA: id TYPE i READ-ONLY.
METHODS: speed_up,
write,
stop.
ENDINTERFACE.

*-------------------------------------------------------------------

CLASS c_ship DEFINITION.


PUBLIC SECTION.
METHODS constructor. "Is called automatically in Rel. 4.5A
"in CREATE OBJECT

INTERFACES i_vehicle.
PRIVATE SECTION.
DATA ship_speed TYPE i.
DATA: max_speed type i.
CLASS-DATA: inst_id TYPE i.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.


PUBLIC SECTION.

(C) SAP AG BC411 20-23


METHODS constructor. "Is called automatically in Rel. 4.5A
"in CREATE OBJECT

INTERFACES i_vehicle.
PRIVATE SECTION.
DATA truck_speed TYPE i.
DATA: max_speed type i.
CLASS-DATA: inst_id TYPE i.
ENDCLASS.

********************************************************************
* Implementations
********************************************************************

CLASS c_ship IMPLEMENTATION.


METHOD constructor.
inst_id = inst_id + 1.
i_vehicle~id = inst_id.
max_speed = 30.
ENDMETHOD.
METHOD i_vehicle~speed_up.
CHECK ship_speed < max_speed.
ship_speed = ship_speed + 10.
ENDMETHOD.
METHOD i_vehicle~stop.
ship_speed = 0.
ENDMETHOD.
METHOD i_vehicle~write.
WRITE: / 'Ship: ID = ', i_vehicle~id, ' Speed = ', ship_speed.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.


METHOD constructor.
inst_id = inst_id + 1.
id = inst_id.
max_speed = 130.

(C) SAP AG BC411 20-24


ENDMETHOD.
METHOD i_vehicle~speed_up.
CHECK truck_speed < speed.
truck_speed = truck_speed + 50.
ENDMETHOD.
METHOD i_vehicle~stop.
truck_speed = 0.
ENDMETHOD.
METHOD i_vehicle~write.
WRITE: / 'Truck: ID = ', i_vehicle~id, ' Speed = ', truck_speed.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Program
********************************************************************

START-OF-SELECTION.
DATA oship TYPE REF TO c_ship.
DATA otruck TYPE REF TO c_truck.
DATA ivehicle TYPE REF TO i_vehicle.

DATA veh_tab TYPE REF TO i_vehicle OCCURS 0.

*----------------------------------------
*--- create some instances (ID is set automatically).
DO 2 TIMES.
CREATE OBJECT oship.
CALL METHOD oship->constructor.
APPEND oship TO veh_tab.
ENDDO.

DO 2 TIMES.
CREATE OBJECT otruck.
CALL METHOD otruck->constructor.
APPEND otruck TO veh_tab.
ENDDO.

*---- speed up and write


LOOP AT veh_tab INTO ivehicle.
(C) SAP AG BC411 20-25
CALL METHOD ivehicle->speed_up.
CALL METHOD ivehicle->speed_up.
CALL METHOD ivehicle->write.
CALL METHOD ivehicle->stop.
CALL METHOD ivehicle->write.
SKIP.
ENDLOOP.

(C) SAP AG BC411 20-26


Unit: ABAP Objects
Exercise 4: Defining, Implementing, Handling, and
Registering Events
Theme: Events

Solution SAPBC411S_OO_EVENTS
Refer to the program for the definition of the screen
REPORT sapbc411s_oo_events NO STANDARD PAGE HEADING.

INCLUDE <list>.

********************************************************************
* Declarations
********************************************************************
new parts are marked bold
INTERFACE i_vehicle.
DATA max_speed TYPE i.
EVENTS: speed_change EXPORTING value(new_speed) TYPE i.
METHODS: speed_up,
stop.
ENDINTERFACE.

*-------------------------------------------------------------------

CLASS c_ship DEFINITION.


PUBLIC SECTION.
METHODS constructor. "Is called automatically in Rel. 4.5A
"in CREATE OBJECT

INTERFACES i_vehicle.
PRIVATE SECTION.
* ALIASES max FOR i_vehicle~max_speed. "Rel. 4.5A
DATA ship_speed TYPE i.
ENDCLASS.

*-------------------------------------------------------------------

(C) SAP AG BC411 20-27


CLASS c_truck DEFINITION.
PUBLIC SECTION.
METHODS constructor. "Is called automatically in Rel. 4.5A
"in CREATE OBJECT

INTERFACES i_vehicle.
PRIVATE SECTION.
* ALIASES max FOR i_vehicle~max_speed. "Rel. 4.5A
DATA truck_speed TYPE i.
ENDCLASS.

*-------------------------------------------------------------------

CLASS status DEFINITION.


PUBLIC SECTION.
CLASS-EVENTS button_clicked EXPORTING value(fcode) LIKE sy-ucomm.
CLASS-METHODS: class_constructor, "Is called automatically in
"Rel. 4.5A in CREATE OBJECT

user_action.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list DEFINITION.


PUBLIC SECTION.
METHODS: fcode_handler FOR EVENT button_clicked OF status
IMPORTING fcode,
list_change FOR EVENT speed_change OF i_vehicle
IMPORTING new_speed,
list_output.
PRIVATE SECTION.
DATA: id TYPE i,
ref_ship TYPE REF TO c_ship,
ref_truck TYPE REF TO c_truck,
BEGIN OF line,
id TYPE i,
flag,
iref TYPE REF TO i_vehicle,

(C) SAP AG BC411 20-28


speed TYPE i,
END OF line,
list LIKE SORTED TABLE OF line WITH UNIQUE KEY id.
ENDCLASS.

********************************************************************
* Implementations
********************************************************************

CLASS c_ship IMPLEMENTATION.


METHOD constructor.
i_vehicle~max_speed = 30.
ENDMETHOD.
METHOD i_vehicle~speed_up.
CHECK ship_speed < i_vehicle~max_speed.
ship_speed = ship_speed + 10.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = ship_speed.
ENDMETHOD.
METHOD i_vehicle~stop.
CHECK ship_speed > 0.
ship_speed = 0.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = ship_speed.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.


METHOD constructor.
max = 150.
ENDMETHOD.
METHOD i_vehicle~speed_up.
CHECK truck_speed < ivehicle~max_speed.
truck_speed = truck_speed + 50.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = truck_speed.
ENDMETHOD.
METHOD i_vehicle~stop.
(C) SAP AG BC411 20-29
CHECK truck_speed > 0.
truck_speed = 0.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = truck_speed.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS status IMPLEMENTATION.


METHOD class_constructor.
SET PF-STATUS 'VEHICLE'.
WRITE 'Click a button!'.
ENDMETHOD.
METHOD user_action.
RAISE EVENT button_clicked EXPORTING fcode = sy-ucomm.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list IMPLEMENTATION.


METHOD fcode_handler.
CLEAR line.
CASE fcode.
WHEN 'CREA_SHIP'.
id = id + 1.
CREATE OBJECT ref_ship.
CALL METHOD ref_ship->constructor.
line-id = id.
line-flag = 'S'.
line-iref = ref_ship.
APPEND line TO list.
WHEN 'CREA_TRUCK'.
id = id + 1.
CREATE OBJECT ref_truck.
CALL METHOD ref_truck->constructor.
line-id = id.
line-flag = 'T'.
line-iref = ref_truck.

(C) SAP AG BC411 20-30


APPEND line TO list.
WHEN 'SPEED_UP'.
CHECK sy-lilli > 0. "absolute line number in list
READ TABLE list INDEX sy-lilli INTO line.
CALL METHOD line-iref->speed_up.
WHEN 'STOP'.
LOOP AT list INTO line.
CALL METHOD line-iref->stop.
ENDLOOP.
WHEN 'CANCEL'.
LEAVE PROGRAM.
ENDCASE.
CALL METHOD list_output.
ENDMETHOD.
METHOD list_change.
line-speed = new_speed.
MODIFY TABLE list FROM line.
ENDMETHOD.
METHOD list_output.
sy-lsind = 0. "List level
SET TITLEBAR 'TIT'.
LOOP AT list INTO line.
IF line-flag = 'S'.
WRITE / icon_ws_ship AS ICON.
ELSEIF line-flag = 'T'.
WRITE / icon_ws_truck AS ICON .
ENDIF.
WRITE: 'Speed = ', line-speed.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Global data of program
********************************************************************

DATA list TYPE REF TO c_list.

********************************************************************
* Program events
(C) SAP AG BC411 20-31
********************************************************************

START-OF-SELECTION.

CREATE OBJECT list.

SET HANDLER: list->fcode_handler,


list->list_change FOR ALL INSTANCES.

*-------------------------------------------------------------------

AT USER-COMMAND.
CALL METHOD status=>user_action.

*************************************************************

(C) SAP AG BC411 20-32


Unit: ABAP Objects
Exercise 5: Defining, Implementing, Handling, and
Registering Events
Theme: Logging with Events

Solution SAPBC411S_OO_EVENT_PROTOCOLL
Refer to the program for the screen definition
REPORT sapbc411s_oo_event_protokoll NO STANDARD PAGE HEADING.

INCLUDE <list>.

********************************************************************
* Declarations
********************************************************************

INTERFACE i_vehicle.
DATA max_speed TYPE i.
EVENTS: speed_change EXPORTING value(new_speed) TYPE i.
METHODS: speed_up,
stop.
ENDINTERFACE.

*-------------------------------------------------------------------

CLASS c_ship DEFINITION.


PUBLIC SECTION.
METHODS constructor.
INTERFACES i_vehicle.
PRIVATE SECTION.
* ALIASES max FOR i_vehicle~max_speed. "Rel 4.5A
DATA ship_speed TYPE i.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.

(C) SAP AG BC411 20-33


PUBLIC SECTION.
METHODS constructor.
INTERFACES i_vehicle.
PRIVATE SECTION.
* ALIASES max FOR i_vehicle~max_speed. "Rel 4.5A
DATA truck_speed TYPE i.
ENDCLASS.

*-------------------------------------------------------------------

CLASS status DEFINITION.


PUBLIC SECTION.
CLASS-EVENTS button_clicked EXPORTING value(fcode) LIKE sy-ucomm.
CLASS-METHODS: class_constructor,
user_action.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list DEFINITION.


PUBLIC SECTION.
METHODS: fcode_handler FOR EVENT button_clicked OF status
IMPORTING fcode,
list_change FOR EVENT speed_change OF i_vehicle
IMPORTING new_speed,
list_output.
PRIVATE SECTION.
DATA: id TYPE i,
ref_ship TYPE REF TO c_ship,
ref_truck TYPE REF TO c_truck,
BEGIN OF line,
id TYPE i,
flag,
iref TYPE REF TO i_vehicle,
speed TYPE i,
END OF line,
list LIKE SORTED TABLE OF line WITH UNIQUE KEY id.
ENDCLASS.

********************************************************************
(C) SAP AG BC411 20-34
* Protocoll by event handling
****** PROTOCOLL MODIFICATION ******

CLASS c_protocoll DEFINITION.


PUBLIC SECTION.
CLASS-METHODS: fcode_handler FOR EVENT button_clicked OF status
IMPORTING fcode.
CLASS-METHODS: write_protocoll.
CLASS-DATA: protocoll_written TYPE i READ-ONLY.
PRIVATE SECTION.
CLASS-DATA fcode_tab LIKE sy-ucomm OCCURS 0.
ENDCLASS.

CLASS c_protocoll IMPLEMENTATION.


METHOD fcode_handler. "-- Arg: fcode
APPEND fcode TO fcode_tab.
ENDMETHOD.
METHOD write_protocoll.
DATA comm LIKE sy-ucomm.
LOOP AT fcode_tab INTO comm.
WRITE: / comm.
ENDLOOP.
protocoll_written = 1.
ENDMETHOD.
ENDCLASS.

****** PROTOCOLL MODIFICATION END ******

********************************************************************
* Implementations
********************************************************************

CLASS c_ship IMPLEMENTATION.


METHOD constructor.
i_vehicle~max_speed = 30.
ENDMETHOD.
METHOD i_vehicle~speed_up.
CHECK ship_speed < i_vehicle~max_speed.
ship_speed = ship_speed + 10.
RAISE EVENT i_vehicle~speed_change
(C) SAP AG BC411 20-35
EXPORTING new_speed = ship_speed.
ENDMETHOD.
METHOD i_vehicle~stop.
CHECK ship_speed > 0.
ship_speed = 0.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = ship_speed.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.


METHOD constructor.
i_vehicle~max_speed = 150.
ENDMETHOD.
METHOD i_vehicle~speed_up.
CHECK truck_speed < i_vehicle~max_speed.
truck_speed = truck_speed + 50.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = truck_speed.
ENDMETHOD.
METHOD i_vehicle~stop.
CHECK truck_speed > 0.
truck_speed = 0.
RAISE EVENT i_vehicle~speed_change
EXPORTING new_speed = truck_speed.
ENDMETHOD.
ENDCLASS.

*-------------------------------------------------------------------

CLASS status IMPLEMENTATION.


METHOD class_constructor.
SET PF-STATUS 'VEHICLE'.
WRITE 'Click a button!'.
ENDMETHOD.
METHOD user_action.
RAISE EVENT button_clicked EXPORTING fcode = sy-ucomm.
ENDMETHOD.
(C) SAP AG BC411 20-36
ENDCLASS.

*-------------------------------------------------------------------
CLASS c_list IMPLEMENTATION.
METHOD fcode_handler.
CLEAR line.
CASE fcode.
WHEN 'CREA_SHIP'.
id = id + 1.
CREATE OBJECT ref_ship.
CALL METHOD ref_ship->constructor.
line-id = id.
line-flag = 'C'.
line-iref = ref_ship.
APPEND line TO list.
WHEN 'CREA_TRUCK'.
id = id + 1.
CREATE OBJECT ref_truck.
CALL METHOD ref_truck->constructor.
line-id = id.
line-flag = 'T'.
line-iref = ref_truck.
APPEND line TO list.
WHEN 'SPEED_UP'.
CHECK sy-lilli > 0. "absolut line number in list
READ TABLE list INDEX sy-lilli INTO line.
CALL METHOD line-iref->speed_up.
WHEN 'STOP'.
LOOP AT list INTO line.
CALL METHOD line-iref->stop.
ENDLOOP.
WHEN 'CANCEL'.
********* PROTOLL MODIFCATION ****
IF c_protocoll=>protocoll_written = 1.
LEAVE PROGRAM.
ENDIF.
CALL METHOD c_protocoll=>write_protocoll.
STOP.
ENDCASE.
****** PROTOCOLL MODIFICATION END ******

(C) SAP AG BC411 20-37


CALL METHOD list_output.
ENDMETHOD.
METHOD list_change.
line-speed = new_speed.
MODIFY TABLE list FROM line.
ENDMETHOD.
METHOD list_output.
sy-lsind = 0. "List level
SET TITLEBAR 'TIT'.
LOOP AT list INTO line.
IF line-flag = 'C'.
WRITE / icon_ws_ship AS ICON.
ELSEIF line-flag = 'T'.
WRITE / icon_ws_truck AS ICON .
ENDIF.
WRITE: 'Speed = ', line-speed.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Global data of program
********************************************************************

DATA list TYPE REF TO c_list.

********************************************************************
* Program events
********************************************************************

START-OF-SELECTION.

CREATE OBJECT list.

SET HANDLER: list->fcode_handler,


list->list_change FOR ALL INSTANCES.

****** PROTOCOLL MODIFICATION ******


(C) SAP AG BC411 20-38
*--- extension for protocoll of commands
SET HANDLER: c_protocoll=>fcode_handler.
****** PROTOCOLL MODIFICATION END ******

*-------------------------------------------------------------------

AT USER-COMMAND.
CALL METHOD status=>user_action.

********************************************************************

(C) SAP AG BC411 20-39


Unit: Contexts
Exercise 1: Creating a context to calculate the distance
between two cities
Theme: Creating contexts

Model solution context C_GEOGR_DISTANC: See definition in the Context


Builder (Transaction SE33)

Modules used:
Name Type Name .

DISTANCE Function module


Context_demo_compute_distance
C_GEOGR_INFORMATION Context C_GEOGR_INFORMATION

Module Distance
Parameters I/O Fieldname .

Longitude1 I Longitude
Lattitude1 I Lattitude
Longitude2 I Longitude_1
Lattitude2 I Latitude_1
Distance O Distance

*Anmerkung: Note the parameters are the import parameters of the


function module Context_demo_compute_distance. The field names are
those used in the context, and are also those that you will use in
the SUPPLY and DEMAND statements in exercise 2.

(C) SAP AG BC411 20-40


ModuleC_Geogr_Information
Parameters I/O Field names
Cityfrom I City
Countryfrom I Country
Cityto I City_1
Countryto I Country_1
Latitudefrom O Latitude
Longitudefrom O Longitude
Latitudeto O Latitude_1
Longitudeto O Longitude_1
*Note: These paraemters are the input/output parameters of the
modules of context C_Geogr_Information. The field names are those
used in the current context, and are those that you will use in the
SUPPLY and DEMAND statements in the second exercise.

(C) SAP AG BC411 20-41


Unit: Contexts
Exercise 2: Using the context from exercise 1 to calculate
the distance between two cities
Theme: Using contexts in programs

Model solution SAPBC411S_CONTEXT_GEOGR_DISTANC

*&-----------------------------------------------------------------*
*& Report SAPBC411S_CONTEXT_GEOGR_DISTAN
*
*&
*
*&-----------------------------------------------------------------*
*& This Report demands the geographical latitude and longitude
* of two cities from a context
*& Error messages from the context are dealt with in the
* program.
*&-----------------------------------------------------------------*

*&-----------------------------------------------------------------*
*& Include BC411_DCONTEXT_GEOGR_DISTANCE
*
*&
*
*&-----------------------------------------------------------------*
* Begin of TOP Include

program zbc411s_context_geogr_distatop.

include <list>. "includes include <symbol> und include


"<icon>
contexts: c_geogr_distanc.

types context_typ type context_t_c_geogr_distanc.

data: latitudefrom type context_typ-latitude,


longitudefrom type context_typ-longitude,

(C) SAP AG BC411 20-42


latitudeto type context_typ-latitude,
longitudeto type context_typ-longitude,
distance like latitudefrom.
*
parameters: p_cityfr type context_typ-city default 'FRANKFURT',
p_counfr type context_typ-country default 'DE',
p_cityto type context_typ-city default 'NEW YORK',
p_counto type context_typ-country default 'US'.
*

data: geogr_distance_inst1 type context_c_geogr_distanc.

data itab like symsg occurs 0 with header line.

* End of TOP Include

* Begin of main program

include zbc411s_context_geogr_distatop.

start-of-selection.
perform get_data.
if sy-subrc <> 0.
perform write_mess.
else.
perform write_data.
endif.

form get_data.
supply city = p_cityfr
country = p_counfr
city_1 = p_cityto
country_1 = p_counto
to context geogr_distance_inst1.

demand longitude = longitudefrom


latitude = latitudefrom
longitude_1 = longitudeto
latitude_1 = latitudeto
(C) SAP AG BC411 20-43
distance = distance
from context geogr_distance_inst1 messages into itab.
endform.

form write_mess.
sy-tvar0 = 'With error handling'(007).
write: 'Display error message from internal table'(006).
loop at itab.
write: / itab-msgty, itab-msgid, itab-msgno,
itab-msgv1, itab-msgv2.
endloop.
endform.

*output
form write_data.
write: /(20) 'City'(001) color 1, '|',
(22) 'Longitude'(002) color 1, '|',
(22) 'Latitude'(003) color 1, '|'.
uline.
write: / p_cityfr color 4, '|',
longitudefrom color 2, '|',
latitudefrom color 2,'|'.
write: / p_cityto color 4, '|',
longitudeto color 2, '|',
latitudeto color 2,'|'.
uline.
format color 3.
write /72 ' '.
write: 1(20) 'Distance'(004), '|', (21) distance, (32) 'km'.

endform.

(C) SAP AG BC411 20-44


Unit: ABAP Open SQL
Exercise 1: Reading all flights for one year
Theme: Runtime of a single access

Solution SAPBC411S_FLIGHTS_OF_ONE_YEAR
*&------------------------------------------------------------------
*& Report SAPBC411S_FLIGHT_OF_ONE_YEAR
*
*
*&-----------------------------------------------------------------
REPORT sapbc411s_fligts_of_one_year .

PARAMETERS: param1(4) DEFAULT '1998'.

DATA: wa_sflight LIKE sflight.


DATA: BEGIN OF search_string,
param(4),
rest VALUE '%',
END OF search_string.
DATA: t1 TYPE i, t2 TYPE i.

GET RUN TIME FIELD t1.

SELECT * FROM sflight INTO wa_sflight.


CHECK wa_sflight-fldate(4) = param1.
* WRITE: / wa_sflight-carrid, wa_sflight-connid.
ENDSELECT.

GET RUN TIME FIELD t1.


WRITE: / 'SELECT ... CHECK:'(001), t1, Number:'(002), sy-dbcnt.

(C) SAP AG BC411 20-45


search_string-param = param1.
GET RUN TIME FIELD t1.

SELECT * FROM sflight INTO wa_sflight


WHERE fldate LIKE search_string.
* WRITE: / wa_sflight-carrid, wa_sflight-connid.
ENDSELECT.

GET RUN TIME FIELD t2.


t2 = t2 - t1.
WRITE: / 'SELECT ... WHERE:'(003), t2, Number:'(002), sy-dbcnt.

(C) SAP AG BC411 20-46


Unit: ABAP Open SQL
Exercise 2: Reading the first 10 flights
Theme: Using data selectively

Solution SAPBC411S_READ_10_FLIGHTS
*&-----------------------------------------------------------------*
*& Report SAPBC411S_READ_10_FLIGHTS
*
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411s_read_10_flights .

DATA: t1 TYPE i, t2 TYPE i.


DATA: BEGIN OF wa,
carrid LIKE sbook-carrid,
connid LIKE sbook-connid,
END OF wa.

GET RUN TIME FIELD t1.

SELECT carrid connid INTO wa FROM sbook


WHERE carrid ='LH' .
IF sy-dbcnt > 10.
EXIT.
ENDIF.
* WRITE: / wa-carrid, wa-connid.
ENDSELECT.

GET RUN TIME FIELD t1.


WRITE: / 'SELECT ... IF sy-dbcnt > 10'(001), Time:'(002), t1.
GET RUN TIME FIELD t1.

SELECT carrid connid FROM sbook INTO wa


UP TO 10 ROWS WHERE carrid = 'LH'.
* WRITE: / wa-carrid, wa-connid.

(C) SAP AG BC411 20-47


ENDSELECT.

GET RUN TIME FIELD t2.


t2 = t2 - t1.
WRITE: / 'SELECT ... UP TO 10 ROWS:'(003),Time:'(002), t2.

(C) SAP AG BC411 20-48


Unit: ABAP Open SQL
Exercise 3: Calculating sums
Theme: Using aggregate functions

Solution SAPBC411S_CUMULATE_LOCCURAM
*&-----------------------------------------------------------------*
*& Report SAPBC411D_CUMULATE_LOCCURAM
*
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411d_cumulate_loccuram .

DATA: wa_loccuram LIKE sbook-loccuram.


DATA: wa_loccurkey LIKE sbook-loccurkey.
DATA: sum TYPE sbook-loccuram.
DATA: t1 TYPE i, t2 TYPE i.
*-slow version-----------------------------------------------------
GET RUN TIME FIELD t1.
sum = 0.

SELECT loccuram wunit FROM sbook INTO (wa_loccuram, wa_loccurkey)


WHERE fldate LIKE '1998%'.
sum = sum + wa_loccuram.
ENDSELECT.

GET RUN TIME FIELD t1.


WRITE: / 'Total revenue'(002), sum CURRENCY wa_loccurkey.
WRITE: / 'Entries read'(001), sy-dbcnt, 'Time:'(003), t1.
SKIP 3.

(C) SAP AG BC411 20-49


*-fast version -----------------------------------------------------
sum = 0.
GET RUN TIME FIELD t1.

SELECT SUM( loccuram ) INTO (sum)


FROM sbook WHERE fldate LIKE '1998%'.

GET RUN TIME FIELD t2.


t2 = t2 - t1.
WRITE: / 'Total revenue'(002), sum CURRENCY wa_loccurkey.
WRITE: / 'Entries read'(001), sy-dbcnt, 'Time:'(003), t2.

(C) SAP AG BC411 20-50


Unit: ABAP Open SQL
Exercise 4: Reading from more than one table
Theme: Join

Solution SAPBC411S_SEL_SFLIGHT_SBOOK
&------------------------------------------------------------------*
& Report SAPBC411D_SEL_SFLIGHT_SBOOK *
&
*
&------------------------------------------------------------------*

REPORT sapbc411s_sel_sflight_sbook .

TYPES: BEGIN OF t_flight_book,


carrid TYPE sbook-carrid,
connid TYPE sbook-connid,
fldate TYPE sbook-fldate,
price TYPE sflight-price,
currency TYPE sflight-currency,
paymentsum TYPE sflight-paymentsum,
bookid TYPE sbook-bookid,
customid TYPE sbook-customid,
END OF t_flight_book.
DATA: it_fb TYPE t_flight_book OCCURS 0 WITH HEADER LINE.
DATA: t1 TYPE i, t2 TYPE i.

GET RUN TIME FIELD t1.

SELECT carrid connid fldate price currency paymentsum


FROM sflight
INTO (it_fb-carrid, it_fb-connid, it_fb-fldate,
it_fb-price, it_fb-currency, it_fb-paymentsum).
SELECT bookid customid
FROM sbook
INTO (it_fb-bookid, it_fb-customid)
WHERE carrid = it_fb-carrid

(C) SAP AG BC411 20-51


AND connid = it_fb-connid
AND fldate = it_fb-fldate.
APPEND it_fb.
ENDSELECT.
ENDSELECT.

GET RUN TIME FIELD t1.


WRITE: / 'Time (manually):'(001), 'Time:'(002), t1.
*loop at it_fb.
* WRITE: / it_fb-carrid, it_fb-connid, it_fb-fldate, it_fb-price
* CURRENCY it_fb-currency,
* it_fb-bookid, it_fb-customid.
*endloop.

GET RUN TIME FIELD t1.

SELECT f~carrid f~connid f~fldate f~price f~currency f~paymentsum


b~bookid b~customid
FROM sflight as f INNER JOIN sbook as b
ON f~carrid = b~carrid AND
f~connid = b~connid AND
f~fldate = b~fldate
INTO TABLE it_fb.

GET RUN TIME FIELD t2. t2 = t2 - t1.


WRITE: / 'Time using JOIN:'(003), 'Time:'(002), t2.
*LOOP AT it_fb.
* WRITE: / it_fb-carrid, it_fb-connid, it_fb-fldate, it_fb-price,
* currency it_fb-currency
* it_fb-bookid, it_fb-customid.
*ENDLOOP.
WRITE: 'sy-dbcnt', sy-dbcnt.

(C) SAP AG BC411 20-52


Unit: ABAP Open SQL
Exercise 5: Reading extreme values
Theme: Subquery

Solution SAPBC411S_SELECT_SUBQUERY
*&-----------------------------------------------------------------*
*& Report SAPBC411D_SELECT_SUBQUERY
*
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411d_select_subquery.

DATA: f TYPE sflight, f1 TYPE sflight.


DATA: t1 TYPE i, t2 TYPE i.

GET RUN TIME FIELD t1.

SELECT carrid connid MAX( seatsocc ) FROM sflight


INTO (f-carrid, f-connid, f-seatsocc)
GROUP BY carrid connid
ORDER BY carrid connid.
SELECT carrid connid fldate FROM sflight
INTO (f1-carrid, f1-connid, f1-fldate)
WHERE carrid = f-carrid
AND connid = f-connid
AND seatsocc = f-seatsocc.
* WRITE: / f1-carrid, f1-connid, f1-fldate, f-seatsocc.
ENDSELECT.
ENDSELECT.

GET RUN TIME FIELD t1.


WRITE: / 'Time with nesting:'(001), t1.

GET RUN TIME FIELD t1.

(C) SAP AG BC411 20-53


SELECT carrid connid fldate seatsocc FROM sflight as f
INTO (f-carrid, f-connid, f-fldate, f-seatsocc)
WHERE seatsocc =
( select MAX( seatsocc ) FROM sflight
WHERE carrid = f~carrid
AND connid = f~connid )
ORDER BY carrid connid fldate.
* WRITE: / f-carrid, f-connid, f-fldate, f-seatsocc.
ENDSELECT.

GET RUN TIME FIELD t2. t2 = t2 - t1.


WRITE: / 'Time with subquery:'(002), t2.
WRITE: / 'sy-dbcnt', sy-dbcnt.

(C) SAP AG BC411 20-54


Unit: ABAP Open SQL
Exercise 6: Reading grouped data with conditions
Theme: HAVING clause

Solution SAPBC411S_SELECT_HAVING
*&-----------------------------------------------------------------*
*& Report SAPBC411S_SELECT_HAVING
*
*&
*
*&-----------------------------------------------------------------*

REPORT sapbc411s_select_having.
DATA: t1 TYPE i, t2 TYPE i.
DATA: count TYPE i, max TYPE i.
DATA: connid TYPE sbook-connid.
DATA: fldate TYPE sbook-fldate.
DATA: avg TYPE f.

* SELECT and CHECK--------------------------------------------------


GET RUN TIME FIELD t1.

SELECT connid fldate COUNT(*) AVG( luggweight )


INTO (connid, fldate, count, avg)
FROM sbook
WHERE carrid = 'LH'
AND fldate > '19981201'
GROUP BY connid fldate.
CHECK avg > 2.
WRITE: / 'LH', connid, fldate, avg, count.
ENDSELECT.
WRITE: / 'sy-dbcnt:', sy-dbcnt.
GET RUN TIME FIELD t2.
t2 = t2 - t1.
WRITE: / 'Time with CHECK:'(001), 'Time:'(002), t2.

* HAVING CLAUSE-----------------------------------------------------

(C) SAP AG BC411 20-55


GET RUN TIME FIELD t1.

SELECT connid fldate COUNT( * ) AVG( luggweight )


INTO (connid, fldate, count, avg)
FROM sbook
WHERE
carrid = 'LH' AND
fldate > '19981201'
GROUP BY connid fldate
HAVING AVG( luggweight ) > 2.
WRITE: / 'LH', connid, fldate, avg, count.
ENDSELECT.

GET RUN TIME FIELD t2.


t2 = t2 - t1.
WRITE: / 'Time with HAVING:'(003), t2.

(C) SAP AG BC411 20-56


Unit: String processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: String processing

Model solution SAPBC411S_STRING_OPERATION


*&------------------------------------------------------------------
*& Report SAPBC411S_STRING_OPERATION
*&
*&------------------------------------------------------------------

REPORT sapbc411s_string_operation.

PARAMETERS: n TYPE i.

DATA: binstr(32) TYPE c,


digits TYPE i,
rest TYPE c,
i TYPE i.

* Decimal to binary conversion using string operations


i = n.
WHILE i <> 0.
rest = i MOD 2.
CONCATENATE rest binstr INTO binstr.
i = i DIV 2.
ADD 1 TO digits.
ENDWHILE.

IF digits < 32.


digits = 32 - digits.
SHIFT binstr RIGHT BY digits PLACES.
TRANSLATE binstr USING ' 0'.
ENDIF.

(C) SAP AG BC411 20-57


WRITE: / 'Decimal to binary conversion using string
operations:'(005),
/ 'Decimal:'(002), n LEFT-JUSTIFIED,
/ 'binary:(003) '(004), binstr.

(C) SAP AG BC411 20-58


Unit: Bit processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: Bit processing

Model solution SAPBC410S_BIT_OPERATION


*&------------------------------------------------------------------
*& Report SAPBC411S_BIT_OPERATION
*&
*&------------------------------------------------------------------

REPORT sapbc411s_bit_operation.

PARAMETERS: n TYPE i.
* Decimal to binary conversion using bit operations
DATA: binstr(32) TYPE c
DATA: hex(4) TYPE x,
offs TYPE i,
b TYPE i.

CLEAR binstr WITH '0'.


hex = n.
DO 32 TIMES.
GET BIT sy-index OF hex INTO b.
IF b = 1.
offs = sy-index - 1.
binstr+offs(1) = '1'.
ENDIF.
ENDDO.
SKIP.
WRITE: / 'Decimal to binary conversion using bit operations:'(001),
/ 'Decimal:'(002), n LEFT-JUSTIFIED,
/ 'Binary:'(003), binstr.

(C) SAP AG BC411 20-59


Glossary

© SAP AG
ABAP Glossary
Each entry in the glossary contains a reference to the application component to which it belongs. You can use this
path in the R/3 Library to find further information. For example, for more information about ABAP Dictionary,
look under ABAP Workbench (application component BC-DWB).

A
0ABAP Dictionary
ABAP Workbench (BC-DWB)
Central and redundancy-free storage facility for all data used in the R/3 System. The ABAP Dictionary describes
the logical structure of application development objects and their representation in the structures of the underlying
relational database. All runtime environment components such as application programs or the database interface,
get information about these objects from the ABAP Dictionary. The ABAP Dictionary is an active data dictionary
and is fully integrated into the ABAP Workbench.
1ABAP Native SQL
ABAP Workbench (BC-DWB)
ABAP Native SQL allows you to include database-specific SQL statements in an ABAP program. Most ABAP
programs containing database-specific SQL statements do not run with different databases. If different databases
are involved, use Open SQL. To execute ABAP Native SQL in an ABAP program, use the statement EXEC.
2ABAP Open SQL
ABAP Workbench (BC-DWB)
Subset of standard SQL statements.
To avoid conflicts between database tables and to keep ABAP programs independent from the database system
used, SAP has generated its own set of SQL statements known as Open SQL.
Using Open SQL allows you to access all database tables available in the R/3 System, regardless of the
manufacturer.
3ABAP Program
ABAP Workbench (BC-DWB)
Program written in the ABAP programming language.
An ABAP program consists of a collection of processing locks, which are processed sequentially as soon as they
are called by the runtime system.
There are two main kinds of ABAP program:
• Report programs (ABAP reports)
• Dialog programs
4ABAP Query
Basis Services/Communication Interfaces (BC-SRV)
ABAP Workbench tool that allows users without knowledge of the ABAP programming language, or table or
field names, to define and execute their own reports.
To determine the structure of reports in ABAP Query, users only have to enter texts, and select fields and options.
Fields are selected from functional areas and can be assigned a sequence by numbering.
There are three types of report available:
• Basic lists
• Statistics
• Ranked lists
5ABAP Report
ABAP Workbench (BC-DWB)
ABAP program that reads and analyzes the data in database tables without modifying the database.
ABAP report programs are defined as type '1' programs and are linked to a particular logical database. Both of
these values are specified in the program attributes.
When you execute an ABAP report program, you can display the resulting output list - also known as a report - on
the screen or send it to a printer.

(C) SAP AG BC411 22-2


6ABAP Workbench
ABAP Workbench (BC-DWB)
SAP's integrated graphical programming environment.
The ABAP Workbench supports the development and modification of R/3 client/server applications written in
ABAP.
You can use the tools of the ABAP Workbench to
• write ABAP code
• design screens
• create user interfaces
• use predefined functions
• get access to database information
• control access to development objects
• test applications for efficiency
• debug applications
7Activation
ABAP Workbench (BC-DWB)
Process that makes an object available at runtime.
When you activate an object, the system generates a load version that application programs and screens can access
and use.
8Amodal Dialog Box
Graphical User Interface (BC-FES-GUI)
Dialog box, allowing the user to work on one screen without the previous screen first being closed.
9Application Hierarchy
Business Navigator (BC-BE-NAV)
Organizational tool for displaying all of the business applications in the R/3 System.
The application hierarchy has a user interface similar to that of a file manager, with a hierarchical structure. You
can display either the standard applications delivered with the system, or a company-specific hierarchy.
10Application Link Enabling
Integration Technology ALE (CA-BFA-ALE)
Application Link Enabling (ALE) refers to the creation and operation of distributed applications.
The basic idea is to guarantee a distributed, but integrated, R/3 installation. This involves business-controlled
message exchange with consistent data across loosely linked SAP applications.
Application integration is achieved not via a central database, but via synchronous and asynchronous
communication.
ALE comprises the following three layers:
• application services
• distribution services
communication services
11Application Toolbar
Graphical User Interface (BC-FES-GUI)
Element of the graphical user interface,
The application toolbar is situated below the standard toolbar on the screen. It contains pushbuttons, which allow
users quick access to application-specific functions, and occupies the whole of the primary window.
Before you can assign a function to a pushbutton, you must assign it to a function key.
12Authorization
Computing Center Management System (BC-CCM)
Authority to perform a particular action in the R/3 System.
Each authorization refers to one authorization object and defines one or more permissible values for each
authorization field listed in the authorization object.
Authorizations are combined in profiles which are entered in a user's master record.
13Authorization Field
Computing Center Management System (BC-CCM)
(C) SAP AG BC411 22-3
Element of an authorization object.
In authorization objects, authorization fields represent values for individual system elements which are supposed
to undergo authorization checking to verify a user's authorization.
14Authorization Object
Computing Center Management System (BC-CCM)
Element of the authorization concept.
Authorization objects allow you to define complex authorizations.
An authorization object groups together up to 10 authorization fields in an AND relationship in order to check
whether a user is allowed to perform a certain action.
To pass an authorization test for an object, the user must satisfy the authorization check for each field in the
object.
15Authorization Profile
Computing Center Management System (BC-CCM)
Element of the authorization concept.
An authorization profile gives a user access to the system. It contains authorizations, identified by the name of an
authorization object. Users have all of the authorizations contained in each profile entered in their user master
record.

B
16Batch Input
Basis Services/Communications Interfaces (BC-SRV)
Interface allowing you to import large amounts of data into an R/3 System.
You use batch input to import legacy data into your new R/3 System, and for periodic imports of external data.
17Batch Input Session
Basis Services/Communications Interfaces (BC-SRV)
Set of transactions supplied with data by a program.
The transactions are stored as a stack. You can then run the session later in dialog mode. The database changes are
not made until you have run the session.
This method allows you to import large quantities of data into an R/3 System in a short time.

C
18Change Request
ABAP Workbench (BC-DWB)
Information folder in the Workbench Organizer and Customizing Organizer for entering and administrating all
changes to Repository objects and Customizing settings made during a development project.
19Change Request, Transportable
ABAP Workbench (BC-DWB)
A change request that can be transported into other systems once it has been released.
20Client
Business Engineer (BC-BE)
In commercial, organizational and technical terms, a self-contained unit in an R/3 System with separate master
records and its own set of tables.
See also the glossary entry for "logical system".
21Clipboard
Graphical User Interface (BC-FES-GUI)
Memory resource that stores a copy of the last information to be copied with the 'Copy' function, or cut with the
'Cut' function.
You can use the 'Paste' function to copy data stored in the clipboard to the current program.
The clipboard is managed by the operating system.
22Command Field
Graphical User Interface (BC-FES-GUI)

(C) SAP AG BC411 24-4


Input field in the standard toolbar to the right of the ENTER pushbutton.
You can enter fastpaths or transaction codes in this field, to choose menu entries or call transactions respectively.
23Control Group Change
ABAP Workbench (BC-DWB)
Point at which the system changes from one control group to another in a report.
The control group change represents a change in the value of whichever field is currently most significant. In an
ABAP program, you trigger it with the AT NEW statement.

D
24Data Definition Language
ABAP Workbench (BC-DWB)
Language used to define all the attributes and properties of a database management system
The query language SQL (Structured Query Language) consists of two kinds of statements:
• DDL (data definition language)
• DML (data manipulation language)
25Data Extract
ABAP Workbench (BC-DWB)
Sequential dataset in the memory area of a report.
26Data Manipulation Language
ABAP Workbench (BC-DWB)
Language for processing data in a database management system.
The query language SQL (Structured Query Language) consists of two kinds of statements:
• DDL (data definition language)
DML (data manipulation language)
27Data Model
Data Model (BC-RMC-DMO)
Structured description of data objects, their attributes, and the relationships between them.
There are different types of data model, depending on the types of data structure you want to define (for example,
relational data model).
28Data Object
ABAP Workbench (BC-DWB)
Physical unit used by a program.
Each data object has a certain data type, which defines how ABAP processes it. All data object occupy memory
space.
29Data Type
ABAP Workbench (BC-DWB)
Attribute of a Data Object
Data types describe the technical attributes of data objects. They are purely descriptions, and occupy no memory
space.
30Database Commit
ABAP Workbench (BC-DWB)
In a database commit, all of the database update requests from the current logical unit of work (LUW) are written
to the database.
In the R/3 System, database commits are either triggered automatically or manually, using the ABAP statement
COMMIT WORK (or, in Native SQL, the database-specific equivalent).
31Database Rollback
ABAP Workbench (BC-DWB)
If you discover an error within an LUW, you can undo all of the update requests in the LUW (that is, since the last
commit) using a database rollback.
In the R/3 System, database rollbacks are either triggered automatically or manually, using the ABAP statement
ROLLBACK WORK (or, in Native SQL, the database-specific equivalent).

(C) SAP AG BC411 25-5


32Database View
ABAP Workbench (BC-DWB)
A type of view in the ABAP Dictionary.
Database views are implemented using an equivalent view in the underlying database system.
33Development Class
ABAP Workbench (BC-DWB)
Group of logically related development objects. A development class contains all the objects which must be
corrected and transported as a whole. The objects which make up a transaction usually belong to one development
class. Customer development classes begin with 'Y' or 'Z'.

E
34EDI
IDoc Interface / Electronic Data Interchange (CA-EDI)
Electronic Data Interchange.
Business-to-business electronic data interchange (for example, sales documents). The business partners may be in
different countries, and might be using different hardware, software, and communication services. The data is
formatted according to fixed standards.
In addition, SAP ALE enables companies to exchange data internally.
35Event Keyword
ABAP Workbench (BC-DWB)
Type of ABAP keyword.
An event keyword defines a processing block in an ABAP program. The processing block is processed when the
particular event occurs.
Examples. GET, START-OF-SELECTION, AT SELECTION-SCREEN.

F
36Function Group
ABAP Workbench (BC-DWB)
Group of functions that logically belong together and use a shared program context at runtime.
The function group is a container program for the function modules that it contains. Functions that work with the
same data are usually all included in the same function group.
Function groups are an administrative unit within the Function Builder.
37Function Module
ABAP Workbench (BC-DWB)
Reusable function.
Function modules are external subroutines that you maintain centrally in the Function Builder, and which can be
called from any ABAP program. This allows you to avoid redundancy in your coding and makes programming
more efficient.
Unlike normal subroutines, function modules have a defined interface.
38Functional Area
Basis Services/Communications Interfaces (BC-SRV)
You can use ABAP Query to define reports without any previous programming knowledge. When you create a
query, you must assign it to a functional area, which determines the tables and fields that the query can use.
Functional areas in ABAP Query are usually subsets of logical databases.
39Functional Group
Basis Services/Communications Interfaces (BC-SRV)
Element of ABAP Query
A functional group is a collection of fields that forms a logical unit. You use them to provide users with a
selection of fields so that he or she does not need to sort through all of the fields in a logical database in order to
create a query.
You must assign a field to a functional group in order for it to be used later in a query.

(C) SAP AG BC411 27-6


G
40GUI Status
Graphical User Interface (BC-FES-GUI)
Main element of the graphical user interface.
A GUI status consists of:
• A menu bar with menus
• A standard toolbar
• An application toolbar
• Functions, and function key settings

H
41Hide Area
ABAP Workbench (BC-DWB)
Main memory area for storing key fields of a line in a report list.
If you want to select further data based on a line selection, the system can find the key fields that it requires in the
hide area.
You must place the key fields into the hide area yourself using the HIDE statement.

I
42Icon
Graphical User Interface (BC-FES-GUI)
Graphical representation of an object or functions. Icons are small colored bitmaps that are used for pushbuttons,
checkboxes, and radio buttons, either with or without text.
Unlike symbols, icons always have the same size, which is one of two, selected automatically by the system
according to the font size.

(C) SAP AG BC411 30-7


43IDES
IMG (BC-BE-IMG)
The R/3 International Demonstration and Education System.
IDES contains several fictional companies that model the different business processes in the R/3 System. Simple
user guides and sample master and transaction data allow you to simulate a wide range of scenarios. This makes
IDES a useful tool for training your project team.
44Inheritance
ABAP Workbench (BC-DWB)
Data Modeler (BC-RMC-DMO)
Passing of attributes from one data object to another.
Attributes can either be passed generally (all attributes), or by copying individual characteristics.
Workflow (BC-BMT-WFM)
“is a” relationship between object types in which shared attributes and methods of supertypes are passed
automatically to subtypes.
Subtypes usually have the same key fields as the supertype, but a more wide-ranging function.
45Internal Table
ABAP Workbench (BC-DWB)
Temporary data structure that exists during the runtime of a program.
Internal tables are one of two structured data types in ABAP. They consist of any number of table lines, each of
which has the same structure. They may or may not have a header line.
The header line is a structure, and serves as a work area for the internal table. The data type of the line can be
either elementary or structured.

L
46List
Graphical User Interface (BC-FES-GUI)
Standard function in the R/3 System used to display lists.
47List Header
ABAP Workbench (BC-DWB)
First line of the screen in a list.
The list header is often the same as the title of the program. However, you can maintain it independently of the
program title.
48Logical Database
ABAP Workbench (BC-DWB)
Special ABAP program that combines the contents of certain database tables.
You can attach a logical database to an ABAP report program as one of the program attributes. It supplies the
report with a set of hierarchically-structured table lines, which can come from different database tables. This saves
the programmer from having to retrieve the data him- or herself.
The term “logical database” applies not only to the program, but also to the data itself.
49Logical Unit of Work
ABAP Workbench (BC-DWB)
Inseparable sequence of database operations, working on the all-or-nothing principle, where the operations are
either all carried out, or all canceled.
From the point of view of the database system, logical units of work (LUWs) are crucial to the integrity of the
data in the database.

M
50Menu
Graphical User Interface (BC-FES-GUI)
Graphical element for choosing functions.

(C) SAP AG BC411 32-8


Menus are graphical elements that present the user with a series of options, each of which triggers a function in
the system. This can include opening a submenu.
There are two types of menu:
• Menu bars
• Action menus
To choose a menu entry, single-click it with the mouse, or position the cursor on it using the arrow keys and press
ENTER.
51Menu Bar
Graphical User Interface (BC-FES-GUI)
Element of the graphical user interface.
The menu bar appears directly below the title bar in the primary window.
When you choose an entry in the menu bar, the system opens the corresponding action menu below the entry. You
can put up to 6 menus in the menu bar, to which the system automatically adds the ‘System’ and ‘Help’ menus.
52Menu Exit
ABAP Workbench (BC-DWB)
Placeholder in the standard system for customers’ own menu entries.
Menu exits allow you to link your own functions to menu entries reserved in the standard system as part of the
enhancement concept (Transaction CMOD). You use an associated function module exit to implement the
function.
53Menu Painter
ABAP Workbench (BC-DWB)
Development tool in the ABAP Workbench for designing the graphical user interface of an ABAP program. Each
GUI consists of a title and a GUI status.
The GUI status contains the following elements:
• Menu bar with menus
• Standard toolbar
• Application toolbar
Functions, assigned to function keys.
54Message Class
ABAP Workbench (BC-DWB)
Collection of messages that are used by a particular application.
Each ABAP program is linked to a message class. The name of the class can be up to 20 characters.
55Metadata
ABAP Workbench (BC-DWB)
Data that describes other data.
Metadata are data definitions, usually stored in a data dictionary.
56Modal Dialog Box
Graphical User Interface (BC-FES-GUI)
Dialog box that must be processed or canceled before the screen behind it can be processed further.
57Modification
ABAP Workbench (BC-DWB)
Customer-specific change to an R/3 Repository object.
When you upgrade the system, you need to check, and possibly update, your modified objects.

P
58Processing Block
ABAP Workbench (BC-DWB)
Group of program statements that are processed together as a unit at a particular point.
ABAP is an event-oriented language (the flow of a program is controlled by events). Program sections are
therefore grouped into processing blocks, which are assigned to particular events. Events are triggered in the
program using event keywords.

(C) SAP AG BC411 33-9


A processing block consists of all of the statements between two event keywords or between an event keyword
and a FORM statement.
59Program
ABAP Workbench (BC-DWB)
A set of statements that provides a solution to a task.
A program consists of a set of statements that are interpreted and executed by a computer.

(C) SAP AG BC411 33-10


Q
60Query
Basis Services/ Communication Interfaces (BC-SRV)
Report that users without programming expertise can generate using ABAP Query.
There are three different types of query:
• Basic list
• Statistic
Ranked list

R
61R/3 Repository
ABAP Workbench (BC-DWB)
Central store for development objects in the ABAP Workbench.
Development objects include ABAP programs, screens, documentation, and so on.
62R/3 Repository Information System
ABAP Workbench (BC-DWB)
Information system that enables you to find information about al of the development objects in the R/3 System
and the relationships between them.
The user interface of the R/3 Repository Information System displays objects in a hierarchical structure similar to
a file manager.
The R/3 Repository Information allows you to:
• Create lists of programs, tables, fields, data elements, and domains.
• Find out where tables and fields are used in ABAP programs and screens.
Display foreign key relationships.
63RFC
ABAP Workbench (BC-DWB)
Remote Function Call.
RFC is an SAP interface protocol based on CPI-C. This simplifies the process of programming communication
between systems.
RFC allows you to call and execute predefined functions in a remote system. They have built-in communication
control, parameter passing, and error handling.

S
64SAP Memory
ABAP Workbench (BC-DWB)
Global, user-specific memory.
You address the SAP memory using SPA/GPA parameters.
65Screen
ABAP Workbench (BC-DWB)
A screen (in the sense of a 'dynpro' or DYNamic PROgram) consists of a screen and its underlying flow logic.
The main components of a screen are:
• attributes (e.g. screen number, next screen)
• layout (the arrangement of texts, fields, and other elements)
• field attributes (definition of the properties of individual fields)
• flow logic (calls the relevant ABAP modules)
66Selection Screen
Graphical User Interface (BC-FES-GUI)
Screen in an ABAP report program.

(C) SAP AG BC411 36-11


You use the selection screen to enter the selection criteria by which the system should retrieve data from the
database.
67Selection Table
ABAP Workbench (BC-DWB)
Internal table containing selection criteria.
The system creates a selection table for each SELECT-OPTIONS statement that you use in an ABAP report
program. They allow you to save complex selections in a standard format.

T
68Table
ABAP Workbench (BC-DWB)
Tabular collection of data. The definition is stored in the ABAP Dictionary, the contents are stored in the
database.
A table consists of columns (sets of data values with the same type) and lines (data records).
Each line of a table can be identified uniquely using a field or a combination of fields.
69Table Work Area
ABAP Workbench (BC-DWB)
Data object created in an ABAP program using the TABLES statement.
A table work area is a structure with the same construction as the corresponding table in the ABAP Dictionary.
70Task
ABAP Workbench (BC-DWB)
Information carrier in the Workbench Organizer for entering and managing all changes to Repository objects and
Customizing settings performed by employees within a development project.
A task is assigned to a change request
71Text Symbol
ABAP Workbench (BC-DWB)
Text constant that you create and maintain outside programs.
You use text symbols instead of text literals to make texts easier to maintain and translate.
Each text symbol is identified by a three-character code.
72Title Bar
Graphical User Interface (BC-FES-GUI)
Element in the graphical user interface.
The title bar is the top line of every primary window and dialog box in the R/3 System.
It contains the title of the window, and icons that allow you to control the window size.
73Transaction
ABAP Workbench (BC-DWB)
A logical process in the R/3 System.
From the user’s point of view, a transaction is a logical unit (for example, to generate a list of customers, change a
customer’s address, create a reservation for a flight, or run a program). From the programmer’s point of view, it is
a complex object, consisting of a module pool and a set of screens. You start transactions using a transaction code.
After logging onto the R/3 System, there are three levels - the SAP level, work area level, and application level. A
transaction is a process at application level. To start the transaction, you can either use the menus or enter a four-
character transaction code. Using the transaction code saves you having to remember the menu path.
Example:
To start a program from the ABAP Workbench, you can either choose Tools → ABAP Workbench → ABAP
Editor, or enter SE38 in the command field.
74Transaction Code
ABAP Workbench (BC-DWB)
Sequence of up to twenty characters that identifies an SAP transaction.
When you enter a transaction code in the command field, the corresponding transaction is started in the R/3
System.
For example, the transaction code SM31 identifies the transaction “Display Table”.

(C) SAP AG BC411 37-12


75Transparent Table
ABAP Workbench (BC-DWB)
Table type in the ABAP Dictionary.
You define transparent tables in the ABAP Dictionary. They are created in the database.
76Transport Request
Computing Center Management System (BC-CCM)
Document for copying corrections between different kinds of system.
Released corrections are collected in a transport request. When you release the request, it is transported.
For example, you can transport corrections from an integration system into a consolidation system.

(C) SAP AG BC411 37-13


77Typing
ABAP Workbench (BC-DWB)
Function in the ABAP Editor that enables you to avoid unnecessary type conversions in ABAP programs.
When the function is called, the system analyzes the parameters in the PERFORM statements and searches in the
FORM statements for formal parameters with similar technical attributes ( type and length). Whenever it finds
two parameters that correspond, it suggests a type for the formal parameter in the FORM statement. You can then
change your coding accordingly.
78User Group
Basis Services/Communication Interfaces (BC-SRV)
Object in ABAP Query.
The assignment to a user group determines which queries a user is allowed to execute and/or maintain.
79User Interface
ABAP Workbench (BC-DWB)
Technical features and functions available to the user to exchange information with the computer system.
In the R/3 System, you design the user interface in the ABAP Workbench with the Screen Painter and the Menu
Painter.

V
80View
ABAP Workbench (BC-DWB)
Application-specific view of different tables in the ABAP Dictionary.
When you create a table, you assign a key according to technical criteria. However, the key fields may be
insufficient for solving certain problems, or some of them may be irrelevant. In this case, you can use a view to
access part of a table or a series of tables.

W
81Web Reporting
Web Basis (CA-B-WEB)
WebRFC applicat allowing Internet users to access information in the R/3 System.
Users can access SAP reports, display lists, and navigate through reporting trees using URLs.

(C) SAP AG BC411 39-14

You might also like