BC411 - Advanced ABAP Programming
BC411 - Advanced ABAP Programming
BC411
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
© 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
Course goal
Course objectives
Contents
Overview diagram
Overall business scenario
© SAP AG
Course Goal
© SAP AG
© SAP AG
Introduction
© SAP AG
Appendices
Exercises
Solutions
Glossary R
© SAP AG
Complex problems:
© SAP AG
© SAP AG
Runtime errors
Debugger
Performance tools
ABAP runtime analysis
GET RUN TIME
SQL TRACE
R
© SAP AG
Unit Objectives
© SAP AG
ABAP
Development Program
Syntax
Syntax check
check
Extended
Extended program
program check
check
Errors
Load
R
Generated form Warnings
© SAP AG
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.
*&
*& 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"
© 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.
*&
*& 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:
© 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.
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.
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.
Material
Management
Overview Statistics
Reorganization
Keep
Release
© SAP AG
Dynamic analysis
Debugging
ABAP runtime
analysis
SQL Trace
© SAP AG
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
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.
© 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.
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.
© 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.
Double-click Form f.
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.
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
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
Breakpoints
© SAP AG
Watchpoints
Logical operator between watchpoints or and
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 <
© 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).
Runtime Analysis
© 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).
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.
Analysis screen
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.
Modularization Units
ABAP programs Program/Report
Subroutines PERFORM
Contexts SUPPLY/DEMAND
Reports SUBMIT R
© SAP AG
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.
SELECT
.
.
.
PERFORM
.
.
SORT
.
.
.
.
.
.
R
Gross Net
© SAP AG
PROGRAM xxx.
DATA: t1 TYPE i,
t2 TYPE i,
run_time TYPE i.
© 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.
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.
© 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.
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.
*& FORM F0
FORM f0.
...
ENDFORM.
*& FORM F1 Variant 1
FORM f1.
Statements for variant 1
ENDFORM.
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).
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.
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.
Bezeichnungen
Transaction = SAPBC411 Client = 000 User = Heilerm
© 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.
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.
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
© 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.
© SAP AG
© 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
Predefined User-defined
Elementary Structured
(Data element)
y r
na
io
m
ct
ra
Di
og
AP
Pr
R
AB
AP
AB
© SAP AG
I Integer 0 4 4
Reference - - -
REF TO
© SAP AG
© 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.
© 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.
F before P before I
REPORT sapbc411d_arithmetic.
DATA: int1 TYPE i, int2 TYPE i,
pack1 TYPE p, float TYPE f.
© SAP AG
Constant
CONSTANTS
Input parameter
PARAMETERS
Selection criteria
SELECT-OPTIONS
RANGES
TABLES
© SAP AG
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.
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.
© 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.
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'.
© 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.
© SAP AG
REPORT xyz.
TABLES: sflight.
DATA: flightinfo_list LIKE bcxaa OCCURS 10,
line_count TYPE I.
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.
© SAP AG
© 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
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>.
p1^ = p2^. 4
© 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.
<fs>
Dynamic offset and length for a string
A B C D E F G H I ...
<fs>
Processing components of a
structure
LH 0400 12/31/1997 ... R
© SAP AG
REPORT sapbc411d_field_symbols.
DATA counter TYPE i. 0
counter = 15. 15
<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.
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
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.
n = STRLEN( string ).
...
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).
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.
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
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>.
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.
© SAP AG
© SAP AG
Unit Objectives
© SAP AG
Predefined User-defined
(P,I,F,C,N,D,T,X,REF TO)
Elementary Structured
Dynamic
table
extension !!!
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.
Key access
© SAP AG
Access using n
R
Mainly index Mainly key Only key
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>.
© SAP AG
6
Time in microseconds
+0
1E
5
+0
1E
0
00
10
00
10
0
10 10 1
© 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.
<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.
© 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.
© 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
© 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).
Work area wa
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.
© SAP AG
4th page:
M entries
(e.g.1024)
8-16 KB
R
© SAP AG
4th page:
M entries
(e.g.1024)
8-16 KB
R
© SAP AG
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.
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.
© 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.
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.
© 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.
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
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.
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).
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.
© 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.
© 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.
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.
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.
© 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.
MODIFY
DELETE
READ But LOOP always
LOOP uses a full table scan
n O(1) O(1) O(1)
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.
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.
© 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.
© SAP AG
Encapsulation Abstraction
Function
Method
Data Method
Function Function Function
Method
© 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.
Interface
Object Public
attributes
attributes
Flight
Airline
Address Flight number
Public
Private Customer
access
access Passenger Methods
list
BOOK
Events
© SAP AG
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.
© 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.
module module
… …
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.
stelle
Interface Data baustein Data
Function
… ... …
...
module
… …
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).
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.
© SAP AG
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.
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.
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.
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.
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.
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
© 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.
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
© 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.
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
© 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.
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.
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.
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).
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.
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.
© 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).
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.
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.
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.
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>.
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.
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.
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.
ENDCLASS. ENDCLASS.
© 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.
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.
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.
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.
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.
© SAP AG
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).
Contexts
How to use contexts
Where to use contexts
Buffering contexts
Maintaining contexts
© SAP AG
Unit Objectives
© SAP AG
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.
© SAP AG
Table
Table // View
View
© 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.
Context: DEMO_CITIES
© 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.
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.
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.
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.
CONTEXTS: <context>.
DATA: <instance> TYPE context_<context>.
REPORT xxx.
CONTEXTS: 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.
Presentation
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.
REPORT ....
CONTEXTS: geogr_information.
© 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.
Presentation
© SAP AG
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.
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.
© 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.
REPORT sapbc411d_context_geogr_distan.
DATA: distance TYPE p.
...
CONTEXTS geogr_information.
DATA: geogr_information_inst TYPE context_geogr_information.
© 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.
REPORT sapbc411d_context_geogr_info.
© 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.
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.
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.
© SAP AG
© SAP AG
© SAP AG
Unit Objectives
© SAP AG
Business transaction
performance
SQL
Efficient ABAP
database programming
© SAP AG
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).
Business transaction
performance
SQL
Efficient ABAP
database programming
© SAP AG
Database server
Communication WP Local
with user data ...
Application server
© 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.
Network
communication
DB CPU
use
DB memory
use Database
Database cache service
processes
Physical I/O
Operating system
Database files R
© SAP AG
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.
Business transaction
performance
SQL
Efficient ABAP
database programming
© SAP AG
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.
Relevant data
SELECT - the search result -
clause
WHERE clause
table~field1 = table~field1 )
WHERE ... AND field1 IN ('A','B','C') AND field3 LIKE 'T%'
© SAP AG
Business transaction
performance
SQL
Efficient ABAP
database programming
© SAP AG
Five rules
DBMS-independent where possible
© SAP AG
ORACLE
INFORMIX
ADABAS
DB2/400 (AS/400)
Microsoft SQL Server (MSS)
Not considered:
DB2/6000
DB2/MVS
R
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
© 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.
© SAP AG
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
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.
Network
communication
DB CPU
use
DB memory
use Database
Database cache service
processes
Physical I/O
Operating system
Database files R
© SAP AG
© 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.
© SAP AG
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.
© 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.
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.
© SAP AG
Appl.
Appl.
server Database
server
SELECT * FROM SBOOK
REPORT XYZ
Appl.
Appl.
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.
Appl.
server Database
server
SELECT COL1 FROM SBOOK
REPORT XYZ
Appl.
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.
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'.
© 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.
© SAP AG
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
© 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.
Network
communication
DB CPU
use
DB memory
use Database
Database cache service
processes
Physical I/O
Operating system
Database files R
© SAP AG
© 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.
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.
© SAP AG
Use joins
Joins implemented as SELECT * FROM t1 WHERE ...
© 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.
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).
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.
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.
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.
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.
© SAP AG
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.
© SAP AG
Having Clause
REPORT sapbc411s_select_having.
© 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.
Network
communication
DB CPU
use
DB memory
use Database
Database cache service
processes
Physical I/O
Operating system
Database files R
© SAP AG
© 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.
Block 1
Satz 4
Satz 2
Block 2
Satz 5
Satz 1
Satz 6
Block 3
Satz 7
Satz 3 R
© SAP AG
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.
...
... 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.
© 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.
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.
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
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.
Cursor cache
Oracle: global
memory area
Data block
buffer
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.
Network
Communication
DB memory DB CPU
use use
Database
Database cache service
processes
Physical I/O
Operating system
Database files R
© SAP AG
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.
Buffer tables
Avoid reading data repetitively
Check for SELECT before changes
ORDER BY vs. SORT
Logical databases
© 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.
© SAP AG
Appl.
server
5 table buffer
4
© SAP AG
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.
Table buffer
0.2 - 1 ms
PROGRAM XYZ
SELECT SINGLE col1 .. FROM T001 Database
server
Appl.
server
8 - 600 ms R
© SAP AG
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
Buffer Synchronization I
Local buffer is
Application server A
up to date
UPDATE T001... Table buffer ...
R/3 DB interface
Communication system
© SAP AG
Whenever you change a database table (update, insert, delete, modify), the application server buffer
is updated at the same time.
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
© 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.
SELECT DDLOG
Communication 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.
© 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.').
© SAP AG
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.
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.
© 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.
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
© SAP AG
Logical databases
Predefined, optimized database access
Simplified list creation
Centrally optimized
© 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.
Network
communication
DB memory DB CPU
use use
Database
Database cache service
processes
Physical I/O
Operating system
Database files R
© SAP AG
© SAP AG
© SAP AG
© SAP AG
© SAP AG
Rule 4
Minimize the search
overhead
Rule 5
Reduce the database load
© SAP AG
© SAP AG
© SAP AG
Unit Objectives
© SAP AG
© 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.
REPORT sapbc411d_catch.
DATA: char(5) TYPE c VALUE '12A34', pack TYPE p.
© 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.
Individual bcd_zero_divide
runtime error convt_to_number
...
arithmetic_errors
Error class conversion_errors
...
© SAP AG
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.
© SAP AG
Include programs
© SAP AG
Unit Objectives
© SAP AG
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.
SAP System
R/3 database
Lock table
R/3 instance 1
R/3 instance n
System areas
© 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.
System areas
ABAP memory
ABAP memory
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.
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
1 1
Ext. subroutine 2 Ext. subroutine 2 Ext. subroutine 2
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.
© 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.
© 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.
FGROUP_0100
© 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.
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.
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.
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.
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).
Main program/
class definition
Global data
Interface
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.
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).
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.
Task
Task List (LEAVE TO LIST-
LIST-PROCESSING)
structuring
structuring
© SAP AG
External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
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
External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific)
Screen stack
Screen stack
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.
Detail list
List level 1
... ...
. ..
.
© 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).
© SAP AG
© SAP AG
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.
External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific)
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.
External
External session
session 11 ->
-> Window
Window 11 External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific)
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.
Task
Task Program (SUBMIT )
structuring
structuring
© SAP AG
Before call
Main program
After call
of called TA01
or
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
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.
External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific) External
External session
session 11 ->
-> Window
Window 11
Before exiting
Main program of
After exiting
ended TA01
or 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.
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.
External
External session
session 11 ->
-> Window
Window 11
ABAP Memory (session-specific) External
External session
session 11 ->
-> Window
Window 11
Before call
of calling
program
After call
program
PROG01
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.
Task
Task
structuring
Context (SUPPLY/DEMAND)
structuring
© SAP AG
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.
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.
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
© SAP AG
© SAP AG
Unit Objectives
© SAP AG
Dynamic statements
tabname = 'SFLIGHT'.
SELECT * FROM (tabname).
Field symbols
<f>
© 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.
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
© 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).
<itab> <itab>
REPORT ztest. REPORT ztest.
FORM display. WRITE 'Generated program'.
WRITE 'Generated program'.
ENDFORM.
© 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.
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.
© 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.
© 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'.
© SAP AG
© SAP AG 1999
Further Information about Internal Tables and
Extracts
© 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.
☺ 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)
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
© 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.
© 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
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.
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.
© SAP AG
Rule 3: Minimize the Number of Transfers 1
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.
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.
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’.
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'.
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.
Verwenden
Verwenden Sie
Sie besser:
besser: R
OPEN
OPEN CURSOR
CURSOR ...
... WITH
WITH HOLD
HOLD ...
... FOR
FOR
SELECT
SELECT ** FROM
FROM ...
...
© SAP AG
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.
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).
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
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
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
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.
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
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.
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.
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.
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.
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.
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).
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
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
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
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).
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.
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.
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.
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
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.
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.
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
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.
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.
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
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.
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.
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.
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.
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.
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
String comparisons
String operations
© SAP AG
Unit Objectives
© SAP AG
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
Ab a p o b j e c t
REPORT sapbc411d_string_processing.
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:
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
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
REPORT sapbc411d_string_processing.
© 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.
© SAP AG
© SAP AG
Unit Objectives
© SAP AG
0 1 0 0 0 0 1
Type X
with length ‘smallest number >= (n/8)'
© SAP AG
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>.
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.
<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:
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.
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.
© SAP AG
EXPORT
IMPORT
DELETE
© SAP AG
Unit Objectives
© SAP AG
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.
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.
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.
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
© 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.
Key fields
Length 3 2 n 4 m 2
Name MANDT RELID SRTF2 CLUSTR CLUSTD
Type Char Char Char INT4 INT2 LRAW
© 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.
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).
ABAP memory
Roll area
Import
Program 1 Program 3
© 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.
MYID ABAP/4
IT_SPFLI
SPFLI
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>).
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.
© 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.
© SAP AG
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:
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
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.
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.
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.
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.
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.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.
Tips &
Tricks
Tips & You can fill all three table types using the statement INSERT <wa> INTO
Tricks TABLE <table>.
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.
Tips & You can read from all three table types using the statement
READ TABLE <table> WITH TABLE KEY a = <parameter> INTO wa.
Tips & Tricks Do not forget to insert the START-OF-SELECTION statement at the
appropriate point.
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.
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.
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.
1.3 Create the context and test it within the Context Builder.
Tips &
Tricks
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.
Tips &
Tricks
1.2 Once you have written the program, run the SQL trace on it to measure your database
access times.
Tips &
Tricks
2.2 Once you have written the program, run the SQL trace on it to measure your database
access times.
Tips &
Tricks
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
3.6 Once you have written the program, run the SQL trace on it to measure your database
access times.
Tips &
Tricks
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
4.3 Once you have written the program, run the SQL trace on it to measure your database
access times.
Tips &
Tricks
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.
5.4 Once you have written the program, run the SQL trace on it to measure your database
access times.
Tips &
Tricks
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
1.4 Once you have written the program, run the SQL trace on it to measure your database
access times.
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.
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
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.
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.
© SAP AG
Unit: Development process and tools
Exercise 1: Correcting the errors in a program and
runtime analysis
Theme: Development process
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.
IF sy-subrc <> 0.
WRITE 'No flights found'(001).
EXIT.
ENDIF.
IF result = space.
MESSAGE s000.
ENDIF.
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
*
*---------------------------------------------------------------*
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.
WRITE: / n, result.
*------------------------------------------------------------------*
* FORM FAKULTAET
*
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.
REPORT sapbc411t_assign.
PARAMETERS:
carrid TYPE sflight-carrid DEFAULT 'LH',
compno TYPE i DEFAULT '1',
compname(8) TYPE c DEFAULT 'CONNID'.
*------------------------------------------------------------------*
* FORM WRITE_SELECTED_FIELD
*
*------------------------------------------------------------------*
* ........
*
*------------------------------------------------------------------*
* --> P_COMPNO
*
DATA:
l_wa_sflight TYPE sflight,
l_field(30) TYPE c,
l_length TYPE i.
FIELD-SYMBOLS:
<l_fs>.
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>.
ENDFORM.
DATA:
l_wa_sflight TYPE sflight, "#EC *
l_field_name(30) TYPE c,
l_length TYPE i.
FIELD-SYMBOLS:
<l_fs>.
ENDFORM.
Soultion SAPBC411S_KEYTAB_DEFINITION
*&-----------------------------------------------------------------*
*& Report SAPBC411S_KEYTAB_DEFINITION
*
*&
*
*&-----------------------------------------------------------------*
REPORT sapbc411s_keytab_definition .
Solution SAPBC411S_KEYTAB_FILL
*&-----------------------------------------------------------------*
*& Report SAPBC411S_KEYTAB_FILL *
*&
*
*&-----------------------------------------------------------------*
REPORT sapbc411s_keytab_fill.
* Type definition for 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.
Solution SAPBC411S_KEYTAB_READ
*&-----------------------------------------------------------------*
*& Report SAPBC411S_KEYTAB_DEFINITION
*
*&
*
*&-----------------------------------------------------------------*
REPORT sapbc411s_keytab_definition .
Solution SAPBC411S_OO_CREATE_CLASS
REPORT oo_interfaces_1 NO STANDARD PAGE HEADING.
********************************************************************
* Simple example for classes definition and implementation.
********************************************************************
ENDCLASS.
*-------------------------------------------------------------------
*-------------------------------------------------------------------
********************************************************************
* Program
********************************************************************
START-OF-SELECTION.
Solution SAPBC411S_OO_OBJECTS_METHODS
REPORT sapbc411s_oo_object_method NO STANDARD PAGE HEADING.
********************************************************************
* Simple example for classes definition/implementation with methods
********************************************************************
ENDCLASS.
*-------------------------------------------------------------------
ENDCLASS.
********************************************************************
* Implementations
********************************************************************
*-------------------------------------------------------------------
********************************************************************
* Program
********************************************************************
START-OF-SELECTION.
DATA oship TYPE REF TO c_ship.
DATA otruck TYPE REF TO c_truck.
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.
*-------------------------------------------------------------------
INTERFACES i_vehicle.
PRIVATE SECTION.
DATA ship_speed TYPE i.
DATA: max_speed type i.
CLASS-DATA: inst_id TYPE i.
ENDCLASS.
*-------------------------------------------------------------------
INTERFACES i_vehicle.
PRIVATE SECTION.
DATA truck_speed TYPE i.
DATA: max_speed type i.
CLASS-DATA: inst_id TYPE i.
ENDCLASS.
********************************************************************
* Implementations
********************************************************************
*-------------------------------------------------------------------
********************************************************************
* 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.
*----------------------------------------
*--- 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.
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.
*-------------------------------------------------------------------
INTERFACES i_vehicle.
PRIVATE SECTION.
* ALIASES max FOR i_vehicle~max_speed. "Rel. 4.5A
DATA ship_speed TYPE i.
ENDCLASS.
*-------------------------------------------------------------------
INTERFACES i_vehicle.
PRIVATE SECTION.
* ALIASES max FOR i_vehicle~max_speed. "Rel. 4.5A
DATA truck_speed TYPE i.
ENDCLASS.
*-------------------------------------------------------------------
user_action.
ENDCLASS.
*-------------------------------------------------------------------
********************************************************************
* Implementations
********************************************************************
*-------------------------------------------------------------------
*-------------------------------------------------------------------
*-------------------------------------------------------------------
********************************************************************
* Global data of program
********************************************************************
********************************************************************
* Program events
(C) SAP AG BC411 20-31
********************************************************************
START-OF-SELECTION.
*-------------------------------------------------------------------
AT USER-COMMAND.
CALL METHOD status=>user_action.
*************************************************************
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.
*-------------------------------------------------------------------
*-------------------------------------------------------------------
*-------------------------------------------------------------------
*-------------------------------------------------------------------
********************************************************************
(C) SAP AG BC411 20-34
* Protocoll by event handling
****** PROTOCOLL MODIFICATION ******
********************************************************************
* Implementations
********************************************************************
*-------------------------------------------------------------------
*-------------------------------------------------------------------
*-------------------------------------------------------------------
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 ******
********************************************************************
* Global data of program
********************************************************************
********************************************************************
* Program events
********************************************************************
START-OF-SELECTION.
*-------------------------------------------------------------------
AT USER-COMMAND.
CALL METHOD status=>user_action.
********************************************************************
Modules used:
Name Type Name .
Module Distance
Parameters I/O Fieldname .
Longitude1 I Longitude
Lattitude1 I Lattitude
Longitude2 I Longitude_1
Lattitude2 I Latitude_1
Distance O Distance
*&-----------------------------------------------------------------*
*& 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 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.
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.
Solution SAPBC411S_FLIGHTS_OF_ONE_YEAR
*&------------------------------------------------------------------
*& Report SAPBC411S_FLIGHT_OF_ONE_YEAR
*
*
*&-----------------------------------------------------------------
REPORT sapbc411s_fligts_of_one_year .
Solution SAPBC411S_READ_10_FLIGHTS
*&-----------------------------------------------------------------*
*& Report SAPBC411S_READ_10_FLIGHTS
*
*&
*
*&-----------------------------------------------------------------*
REPORT sapbc411s_read_10_flights .
Solution SAPBC411S_CUMULATE_LOCCURAM
*&-----------------------------------------------------------------*
*& Report SAPBC411D_CUMULATE_LOCCURAM
*
*&
*
*&-----------------------------------------------------------------*
REPORT sapbc411d_cumulate_loccuram .
Solution SAPBC411S_SEL_SFLIGHT_SBOOK
&------------------------------------------------------------------*
& Report SAPBC411D_SEL_SFLIGHT_SBOOK *
&
*
&------------------------------------------------------------------*
REPORT sapbc411s_sel_sflight_sbook .
Solution SAPBC411S_SELECT_SUBQUERY
*&-----------------------------------------------------------------*
*& Report SAPBC411D_SELECT_SUBQUERY
*
*&
*
*&-----------------------------------------------------------------*
REPORT sapbc411d_select_subquery.
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.
* HAVING CLAUSE-----------------------------------------------------
REPORT sapbc411s_string_operation.
PARAMETERS: n TYPE i.
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.
© 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.
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)
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).
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.
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.
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.
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.
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.
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”.
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.