Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Advanced ABAP Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 488
At a glance
Powered by AI
The document provides an overview of an Advanced ABAP Programming course, outlining its objectives, contents, and development tools/processes.

The course goal is to teach advanced ABAP programming concepts and techniques.

The main topics that will be covered include the ABAP workbench, development process, program analysis, debugging, and more.

BC411 Advanced ABAP Programming

BC411










R/3 System Release 46B 24.06.2002

0

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


BC 411 Advanced ABAP Programming
Release 4.0 B
Material number: 5002 0252
August 1998




SAP AG
R
Copyright
Copyright 1998 SAP AG. All rights reserved.
Neither this training manual nor any part thereof may
be copied or reproduced in any form or by any means,
or translated into another language, without the prior
consent of SAP AG. The information contained in this
document is subject to change and supplement
without prior notice.
All rights reserved.


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.










SAP AG
R
R/3 Integration Model
R/3 R/3
Client/Server
ABAP
Client/Server
ABAP
CO
Controlling
CO
Controlling
AA
Asset
Accounting
AA
Asset
Accounting
PS
Project
System
PS
Project
System
WF
Workflow
WF
Workflow
IS
Industry
Solutions
IS
Industry
Solutions
MM
Materials
Mgmt
MM
Materials
Mgmt
HR
Human
Resources
HR
Human
Resources
SD
Sal es &
Distribution
SD
Sal es &
Distribution
PP
Production
Planning
PP
Production
Planning
QM
Quality
Mgmt
QM
Quality
Mgmt
FI
Financi al
Accounting
FI
Financi al
Accounting
PM
Plant
Maintenance
PM
Plant
Maintenance


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.











SAP AG
R
ABAP Workbench
Level 3
BC420 2 days
Interface Programming
for Data Transfer
BC430 2 days
ABAP Dictionary
BC405 5 days
Techniques of
List Processing
BC410 5 days
Transaction Processing
BC415 3 days
Communication
Interface Programming
in ABAP
BC460 3 days
SAPscript: Forms
Design and Text
Management in R/3
BC425 2 days
Enhancements and
Modifications
BC440 5 days
Developing Internet
Application Components
(IAC)
BC411 5 days
Advanced ABAP
Programming
Level 2
BC400 5 days
ABAP Workbench
Basics




SAP AG
R
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
R
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


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


SAP AG
R
Introduction: Contents
Course goal
Course objectives
Contents
Overview diagram
Overall business scenario



(C) SAP AG BC411 1-2
SAP AG
R
Course Goal
Programming in ABAP in the R/3 System
ABAP language constructions, with
particular emphasis on using them
correctly and in appropriate situations
This course teaches you about :



(C) SAP AG BC411 1-3
SAP AG
R
Course Objectives
Description of the development process and
using the development tools
Using types and field symbols
Understanding and using the different kinds of
internal tables
Understanding and using the syntax of ABAP
Objects
Programming exception and message handling
Using ABAP and Open SQL
Using appropriate modularization units and
dynamic programs



(C) SAP AG BC411 1-4
SAP AG
R
Contents I
Unit Introduction Unit Contexts
Unit Development process and Unit ABAP Open SQL
development tools
Unit Types Unit Exceptions and message handling
Unit Field symbols Unit Modularization units
Unit Internal tables Unit Generating dynamic programs
Unit Object-oriented programming
in ABAP
Unit ABAP Objects
Introduction



(C) SAP AG BC411 1-5
SAP AG
R
Contents II
Appendix A Further information about internal tables and extracts
Appendix B Accessing table lines directly (from Release 4.5A)
AppendixC Further information about ABAP Open SQL
AppendixD Further information about modul arization units
AppendixE String processing
AppendixF Bit processing
AppendixG Data clusters
Exercises
Solutions
Glossary
Appendices



(C) SAP AG BC411 1-6
SAP AG
R
Overview Diagram
Complex problems:
What ABAP constructions
can I use to solve the
problem?



(C) SAP AG BC411 1-7
SAP AG
R
Overall Business Scenario
This course contains no overall scenario
that is successively developed by the
participants


SAP AG
R
Development Process and Tools: Contents
Development process for an ABAP program
Static checks
Syntax check
Extended program check
Runtime errors
Debugger
Performance tools
ABAP runtime analysis
GET RUN TIME
SQL TRACE



(C) SAP AG BC411 2-2
SAP AG
R
Unit Objectives
At the end of this unit, you will be able to:
Explain the development process for an ABAP
program
Check the syntax of a program
Run an extended program check for a program
Anal yze a short dump
Use the most important functions of the Debugger
Determine the flow and runtime of a program using
runtime anal ysis
Measure runtime using the GET RUN TIME statement
Anal yze database access usi ng the main functions of
the SQL Trace tool



(C) SAP AG BC411 2-3
SAP AG
R
Development Process for an ABAP Program
TRDIR TRDIR
attributes attributes
Program
ABAP
Development
Source code Source code
Syntax check
Extended program check
Syntax check
Extended program check
Errors
Warnings Load
Generated form



(C) SAP AG BC411 2-4
SAP AG
R
Types of Program Analysis
Error
Error
Static analysis
Static analysis
Warning
Warning
Syntax check
Syntax check
Database access
Database access
Dynamic
analysis
Dynamic
analysis
Memory contents
Memory contents
General memory allocation
General memory allocation
Program interruption
Program interruption
Debugging
Debugging
Dump analysis
Dump analysis
Runtime error
Runtime error
Extended program check
Extended program check
Error
Error
Warning
Warning
Message
Message
SQL Trace
SQL Trace
Program flow
Program flow
Runtime measurement
Runtime measurement
Memory requirements
Memory requirements
ABAP runtime
analysis
ABAP runtime
analysis


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


(C) SAP AG BC411 2-5
SAP AG
R
Syntax Check
*& REPORT sapsynt axcheck.
I NCLUDE synt axcheckt op.
I NCLUDE synt axcheckf 01.
*& REPORT sapsynt axcheck.
I NCLUDE synt axcheckt op.
I NCLUDE synt axcheckf 01.
*I NCLUDE SYNTAXCHECKF01
PERFORM subpr og.
*For mRout i ne not def i ned
*i n pr ogr am.
.
*I NCLUDE SYNTAXCHECKF01
PERFORM subpr og.
*For mRout i ne not def i ned
*i n pr ogr am.
.
*& I NCLUDE SYNTAXCHECKTOP.
REPORT synt axcheck.
.
*& I NCLUDE SYNTAXCHECKTOP.
REPORT synt axcheck.
.
Syntax error
Syntax error in: SYNTAXCHECKF01 Line 5
PERFORM SUBPROGRAM.
The form " SUBPROGRAM" does not exist,
but there is a FORM with the similar name
" SUBPROG"
Edit Correct error


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





(C) SAP AG BC411 2-6
SAP AG
R
Syntax Check
*& I NCLUDE SAPBC411D_SYNTAXCHECKF01.
PERFORM subpr ogr am.
FORM subpr ogr am.
SELECT . . .
ENDSELECT.
ENDFORM.
PERFORM u_pgm.
*& I NCLUDE SAPBC411D_SYNTAXCHECKF01.
PERFORM subpr ogr am.
FORM subpr ogr am.
SELECT . . .
ENDSELECT.
ENDFORM.
PERFORM u_pgm.
Syntax warning:
Statement (PERFORM u_pgm) is not accessible.


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








(C) SAP AG BC411 2-7
SAP AG
R
Syntax Errors
Extended
program check
Extended
program check
Warnings from the syntax check Warnings from the syntax check
PERFORM/FORM interfaces PERFORM/FORM interfaces
CALL FUNCTION interfaces CALL FUNCTION interfaces
Screen consistency Screen consistency
STATUS and TITLEBAR STATUS and TITLEBAR
Strings Strings
Field attributes Field attributes
Conversions Conversions


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
FUNCTI ON f i el d, the static check cannot tell whether the value of field corresponds to a valid
function module name. However, if you write CALL FUNCTI ON ' J OHN_SMI TH' , the extended
program check will look to see if the function module ' J OHN_SMITH' exists.


(C) SAP AG BC411 2-8
SAP AG
R
Runtime Errors
Runtime errors
Runtime errors
What happened?
What happened?
What can you do?
What can you do?
Error analysis
Error analysis
System environment
System environment
How to correct the error
How to correct the error
Info: Where error occurred
Info: Where error occurred
Chosen variables
Chosen variables
Active calls/ events
Active calls/ events
...
...
Overview
Debugger
Internal errors
Internal errors
Installation and
environment/resource
errors
Installation and
environment/resource
errors
Errors in application
programs
Errors in application
programs
Short text
Short text


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



(C) SAP AG BC411 2-9
SAP AG
R
Dump Anal ysi s Dump Anal ysi s
Material
Management
Overview
Statistics
Display
Print
Keep
Release
Reorganization Reorganization
Short Dump Administration


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




(C) SAP AG BC411 2-10
SAP AG
R
Dynamic Analysis
Dynamic anal ysis
Debugging
SQL Trace
ABAP runtime
analysis


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



(C) SAP AG BC411 2-11
SAP AG
R
Debugging Mode
BREAK-POINT <value>.
BREAK-POINT <value>.
1. Program statement Repository Browser Repository Browser
Program
? ?
q

q
q

Goto System Help Edit


Test/Execute
SAPBC411SAP Training: BC411
Object type development class
Programs
Context_I_C_GEOGR_DISTANCE
Context_I_C_GEOGR_DISTANCE
BREAK-POINT <Value>.
BREAK-POINT <Value>.
1. Program statement ABAP Editor: Initial Screen ABAP Editor: Initial Screen
Program
q
q
Goto System Help Edit
Debugging
SAPBC411D_TEST
Program
Create
Execute
Sub-objects
Source code
Variants
Attributes
Documentation
/H
...
...
Utilities >
...
Debugging ...


There are four different ways of starting the Debugger:
- From the Repository Browser, by choosing Test/Execute.

- From the ABAP Editor by choosing Debugging.

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

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

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



(C) SAP AG BC411 2-12
SAP AG
R
The Most Important Debugging Functions
Single step
Continue
Breakpoint
Hexadecimal
display
Replace function
Processes the next line of the
program.
Continues processing until the
next breakpoint or the end of the
program occurs.
Displays a screen on which
you can set breakpoints.
Use this button to display
the field contents in
hexadecimal form.
Allows you to change the
contents of a field.
Processes the next line of the
program.
Continues processing until the
next breakpoint or the end of the
program occurs.
Displays a screen on which
you can set breakpoints.
Use this button to display
the field contents in
hexadecimal form.
Allows you to change the
contents of a field.


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



(C) SAP AG BC411 2-13
SAP AG
R
The Most Important Debugging Functions II
Up to fi ve watchpoints linked
with relational operators.
You can expand structured
fields by double-clicking.
You can display complex
internal tables and expand them
by double-clicking.
Up to fi ve watchpoints linked
with relational operators.
You can expand structured
fields by double-clicking.
You can display complex
internal tables and expand them
by double-clicking.
Pushbutton for
expanding
substructures
Displaying complex
internal tables
Watchpoint


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



(C) SAP AG BC411 2-14
SAP AG
R
Debugger: Overvi ew
SAP R/3
Debugging
? ? q

q q

Bezeichnungen
Goto Breakpoint Settings Development System Help
Main program Test
Source code of Test
start-of-selection
Fiel d names
carrid
Fiel d contents
Crew-Flight Table[2x272]
Fldate 19980810
Crew ********************************************
Select Carrid From Spfli
Crew_Wa-Function ='PILOT'. Crew_Wa-Flight ='0400'.
Move-Corresponding Crew_Wa To Flight_Table-Crew.
Append Flight_Table-Crew.
Break-point.
Form f.
Double-click
2 - 5
77
Watchpoint
Fields Table Watchpoint Calls
-
Fixed point arith.
SY-SUBRC= 0 SY-TABIX= 2 SY-DBCNT= 30
LH
Breakpoint
68 77


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


(C) SAP AG BC411 2-15
SAP AG
R
Expanding Substructures
Structured field
No
Length
Component name Type Length Contents
1 Carrid C 3 LH
2 Connid N 4
3 Crew h 8
4 Crew-Name C 30 Miller
4
5
6
7
Component name
272
FLIGHT_TABLE
Crew-Function
Crew-Flight
Crew-Flight-No1
C
h
N
20
4
Crew-Flight-No2
8 19980509 Fldate
0400
Pilot
0400
0402 N 4
D 8



To display a complex structure, choose Goto ->Structured field.
You can navigate deeper into the structure by double-clicking an individual component.
The system displays the length of the structured field, along with the name, type, length, and
contents of its components.


(C) SAP AG BC411 2-16
SAP AG
R
Breakpoints in Programs
BREAK-POINT <value>.
BREAK-POINT <value>.
1. ABAP statement
Set
Delete
Display breakpoint
Set
Delete
Display breakpoint
2. Editor function
BREAK-POINT <value>.
BREAK-POINT <value>.
2. Function Breakpoints
BREAKPOINTS anzeigen
setzen
lschen
BREAKPOINTS anzeigen
setzen
lschen
SAP R/3 SAP R/3
Program
? ?
q

q
q

Bezeichnungen
Goto System Help Edit
1 PROGRAM sapbc411d_debugger.
2 INCLUDE bc411d_debuggertop.
3 SELECT carrid connid FROM sflight INTO
4 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.
10
Stop


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



(C) SAP AG BC411 2-17
SAP AG
R
Breakpoints in the Debugger
Breakpoints
No Program Li ne Statement/Event/... Counter
2 SAPBC411D_DEBUG 10 start-of-selection
3 SAPBC411D_DEBUG 70 select
4
5
6
7
8
9
10
1 SAPBC411D_DEBUG 1 append Stop
Stop
Stop


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


(C) SAP AG BC411 2-18
SAP AG
R
Watchpoints
Watchpoints
No Program Fiel d name Comparsion fiel d/value
Logical operator between watchpoi nts
L Op Fiel d
1 SAPBC411D_DEBUG str-c
x
2 str-i
=
x
3 i
>
x
4 sy-tabix
=
x
5 str-c
<
x
Current contents of the last watchpoi nt reached:
SAPBC411D_DEBUG i 4
x sy-index
1
5
or and
SAPBC411D_DEBUG
SAPBC411D_DEBUG
SAPBC411D_DEBUG
SAPBC411D_DEBUG


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



(C) SAP AG BC411 2-19
SAP AG
R
Runtime Measurement
Runtime Anal ysis
GET RUN TIME FIELD <f>.


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


(C) SAP AG BC411 2-20
SAP AG
R
Runtime Analysis I
Runtime anal ysis
Runtime anal ysis
Report: RSDEMO00
Report: RSDEMO00
Measure
Measure
Anal ysis
Anal ysis
Start End
Performance
data in file
Dialog List
Analysis


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


(C) SAP AG BC411 2-21
SAP AG
R
Runtime Analysis II
Analysis screen
Group hit list
Overall
call hierarchy
Analysis screen
Group hit list
Detail selection
Call hierarchy
Subtree
Overall
hit list
Table hit
list
Runtime analysis


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


(C) SAP AG BC411 2-22
SAP AG
R
ABAP programs ABAP programs
Modularization Units Modularization Units
Program/Report Program/Report
Modules (screens) Modules (screens) MODULE MODULE
Subroutines Subroutines PERFORM PERFORM
Methods Methods CALL METHOD CALL METHOD
Events Events RAISE EVENT RAISE EVENT
Function modules Function modules CALL FUNCTION CALL FUNCTION
Contexts Contexts SUPPLY/DEMAND SUPPLY/DEMAND
Reports Reports SUBMIT SUBMIT
Measurable Functions I


ABAP program analysis is based on:

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




(C) SAP AG BC411 2-23
SAP AG
R
SAP SQL SAP SQL
Database/file access Database/file access
SELECT/INSERT/UPDATE/ SELECT/INSERT/UPDATE/
DELETE DELETE
Direct SQL interface Direct SQL interface EXEC SQL EXEC SQL
Data cluster Data cluster EXPORT/IMPORT EXPORT/IMPORT
Sequential files Sequential files
TRANSFER/READ TRANSFER/READ
DATASET DATASET
Extending Extending APPEND/COLLECT APPEND/COLLECT
Processing Processing LOOP LOOP
Sorting Sorting SORT SORT
Internal tables Internal tables
System times System times
Load/generate programs Load/generate programs
Measurable Functions II


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

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


(C) SAP AG BC411 2-24
SAP AG
R
PROGRAM SAPBC411D_...
SELECT
PERFORM
SORT
Gross and Net Times
Gross Net
.
.
.
.
.
.
.
.
.
.
.
.
.
.


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


(C) SAP AG BC411 2-25
SAP AG
R
The GET RUN TIME Statement
GET RUN TI ME FI ELD <f >.
PROGRAM xxx.
DATA: t 1 TYPE i ,
t 2 TYPE i ,
r un_t i me TYPE i .
GET RUN TI ME FI ELD t 1.
GET RUN TI ME FI ELD t 2.
r un_t i me = t 2 - t 1.
Statement block


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



(C) SAP AG BC411 2-26
SAP AG
R
Test Frame I
REPORT sapbc411d_t est f r ame.
TYPES:
BEGI N OF r esul t _l i ne,
t ext ( 60) TYPE c,
t i me TYPE i ,
END OF r esul t _l i ne.
DATA:
t 1 TYPE i ,
t 2 TYPE i ,
base_t i me TYPE i ,
r es_t i me( 8) TYPE p DECI MALS 1,
i TYPE i ,
r esul t TYPE r esul t _l i ne OCCURS 10 WI TH
HEADER LI NE.
PARAMETERS:
i n_cnt TYPE i DEFAULT 100,
out _cnt TYPE i DEFAULT 20.
* Speci f c dat a f or t he measur ement . . .
REPORT sapbc411d_t est f r ame.
TYPES:
BEGI N OF r esul t _l i ne,
t ext ( 60) TYPE c,
t i me TYPE i ,
END OF r esul t _l i ne.
DATA:
t 1 TYPE i ,
t 2 TYPE i ,
base_t i me TYPE i ,
r es_t i me( 8) TYPE p DECI MALS 1,
i TYPE i ,
r esul t TYPE r esul t _l i ne OCCURS 10 WI TH
HEADER LI NE.
PARAMETERS:
i n_cnt TYPE i DEFAULT 100,
out _cnt TYPE i DEFAULT 20.
* Speci f c dat a f or t he measur ement . . .


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


(C) SAP AG BC411 2-27
SAP AG
R
Test Frame II
* St ar t measur ement
PERFORM f i l l _r esul t USI NG:
Base t i me , "#EC NOTEXT
. . Var i ant 1. . . . . . . , "#EC NOTEXT
. . Var i ant 2. . . . . . . . "#EC NOTEXT
LOOP AT r esul t .
i = sy- t abi x.
r esul t - t i me = 99999999.
DO out _cnt TI MES.
GET RUN TI ME FI ELD t 1.
DO i n_cnt TI MES.
PERFORM i OF f 0 f 1 f 2.
ENDDO.
GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
I F t 2 < r esul t - t i me. r esul t - t i me = t 2.
ENDI F.
ENDDO.
* St ar t measur ement
PERFORM f i l l _r esul t USI NG:
Base t i me , "#EC NOTEXT
. . Var i ant 1. . . . . . . , "#EC NOTEXT
. . Var i ant 2. . . . . . . . "#EC NOTEXT
LOOP AT r esul t .
i = sy- t abi x.
r esul t - t i me = 99999999.
DO out _cnt TI MES.
GET RUN TI ME FI ELD t 1.
DO i n_cnt TI MES.
PERFORM i OF f 0 f 1 f 2.
ENDDO.
GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
I F t 2 < r esul t - t i me. r esul t - t i me = t 2.
ENDI F.
ENDDO.


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 t o c2 has a shorter runtime than the
measurement accuracy of 1s. In this case, you would run the statement several times and divide the
total runtime by the number of loop passes).
You use the outer loop to determine the number of test runs, from which you then take the minimum
runtime. This process should eliminate factors, such as changing work process, that can make
individual measurements inaccurate.


(C) SAP AG BC411 2-28
SAP AG
R
Test Frame III
I F i = 1.
base_t i me = r esul t - t i me.
ELSE.
SUBTRACT base_t i me FROM r esul t - t i me.
ENDI F.
MODI FY r esul t .
ENDLOOP.
LOOP AT r esul t .
t 1 = r esul t - t i me / i n_cnt .
WRI TE: / r esul t - t ext , r es_t i me.
ENDLOOP.
I F i = 1.
base_t i me = r esul t - t i me.
ELSE.
SUBTRACT base_t i me FROM r esul t - t i me.
ENDI F.
MODI FY r esul t .
ENDLOOP.
LOOP AT r esul t .
t 1 = r esul t - t i me / i n_cnt .
WRI TE: / r esul t - t ext , r es_t i me.
ENDLOOP.


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



(C) SAP AG BC411 2-29
SAP AG
R
Test Frame IV
*& FORM FI LL_RESULT
FORM f i l l _r esul t USI NG t ext .
r esul t - t ext = t ext .
APPEND r esul t .
ENDFORM.
*& FORM F0
FORM f 0.
. . .
ENDFORM.
*& FORM F1 Var i ant 1
FORM f 1.
ENDFORM.
Statements for variant 1
*& FORM F2 Var i ant 2
FORM f 2.
ENDFORM.
Statements for variant 2


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


(C) SAP AG BC411 2-30
SAP AG
R
Database Access
ABAP
Program
ABAP
Runtime analysis
Database
SQL Trace


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


(C) SAP AG BC411 2-31
SAP AG
R
SQL Trace
Appli cation server
Database I/O
S
Q
L

T
r
a
c
e


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



(C) SAP AG BC411 2-32
SAP AG
R
Trace Basic Li st
Debugging
? ? q

q q

Bezeichnungen
Goto Breakpoint Settings Development System Help
DDIC Info Explain SQL ABAP Display More Info
Transaction=SAPBC411 Client =000 User =Heilerm
Duration Object Oper Rec RC Statement
684 REEXECS 0 0 Free
10,998 REEXECS 1 0 Select Where "name" ='SAPBC411_... TRDIR
14,920 PREPARE Select Where "mandt" =? AND "carrid" SPFLI
461 DECLARE Select Where "mandt" =? AND "carrid" SPFLI
347 OPEN Select Where "mandt" ='400' AND "... SPFLI
191,329 FETCH 6 0 SPFLI
206 FETCH 6 0 SPFLI
300 FETCH 0 100 SPFLI
209 CLOSE 0 0 SPFLI
SQL Trace - Basic List


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


(C) SAP AG BC411 2-33
SAP AG
R
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
SQL Trace Function: Explain SQL


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


(C) SAP AG BC411 2-34
SAP AG
R
SELECT ... FROM SPFLI WHERE CARRID IN ITAB_CARRID.
SPFLI_______0
MANDT CARRID CONNID ROWID
---------------------------------------------------
001 AA 0017 1237
001 AA 0064 1235
001 AZ 0555 1234
001 AZ 0788 1236
Index for primary key
SPFLI
ROWID MANDT CARRID CONNID...
---------------------------------------------------
1234 001 AA 0017
1235 001 AA 0064
1236 001 AZ 0555
1237 001 AZ 0788
Table contents
Index Range Scan/Access by Rowid


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


(C) SAP AG BC411 2-35
SAP AG
R
Summary
In this unit, you have learned the typical steps invol ved
in program development, in particular how to check
programs using
Static check
Runtime check
and the most important functions for
Dynamic program checks:
Runtime anal ysis
The GET RUN TIME statement
SQL Trace
Debugger


SAP AG
R
Types: Contents
The ABAP type concept
ABAP Dictionary types and ABAP program types
Type compatibility and conversion
Type conversion and performance
Runtime type information



(C) SAP AG BC411 3-2
SAP AG
R
Unit Objectives
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
At the end of this unit, you will be able to explain:



(C) SAP AG BC411 3-3
SAP AG
R
Data Types
Predefined
Elementary
(Data element)
Structured type
(Structure)
Table type Class/Interface
Structured
User-defined
Data type
A
B
A
P

D
i
c
t
i
o
n
a
r
y
A
B
A
P

P
r
o
g
r
a
m


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



(C) SAP AG BC411 3-4
SAP AG
R
Predefined ABAP Types
Data type Description Initial value Default Permitted
length length
P
I
F
N
C
D
T
X
N
u
m
e
r
i
c
A
l
p
h
a
-
n
u
m
e
r
i
c
REF TO
Packed number
Integer
Floating point number
Numeric string Numeric string
Text Text
Date YYYYMMDD Date YYYYMMDD
Time HHMMSS Time HHMMSS
Hexadecimal Hexadecimal
Reference Reference
0
0
0.000
00...0 00...0
Space Space
00000000 00000000
000000 000000
X00 X00
- -
8
4
8
1 1
1 1
8 8
6 6
1 1
- -
1-16
4
8
1 1 - - max. max.
1 1 - - max. max.
8 8
6 6
1 1 - - max. max.
- -


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



(C) SAP AG BC411 3-5
SAP AG
R
Predefined Dictionary Types I
DEC
INT1
INT2
INT4
Description
Calculation/amount field
1 byte integer
2 byte integer
4 byte integer
Currency field
Currency key
Quantity
Unit key
Accuracy of QUAN field
Floating point number
CURR
CUKY
QUAN
UNIT
PREC
FLTP
Type Permitted length n
1-31, in tables 1-17
3
5
10
1-17
5
1-17
2-3
2
16
ABAP type
P((n+1)/2)
internal
internal
I
P((n+1)/2)
C(5)
P((n+1)/2)
C(n)
X(2)
F(8)


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
I NT1 1 byte integer, value between 0 and 255
I NT2 2 byte integer, value between -32767 and 32767
I NT3 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.
UNI T Unit key referenced by a type QUAN field.
PREC Accuracy of a QUAN field.
FLTP Floating point number.
NUMC Numeric text. May only contain digits.



(C) SAP AG BC411 3-6
SAP AG
R
Predefined Dictionary Types (2)
Description Permitted length n ABAP type
Numeric text 1-255 N(n)
Character 1-255 C(n)
Long Character 256-max C(n)
Date 8 D
Accounting period YYYYMM 6 N(6)
Time HHMMSS 6 T
Uninterpreted byte sequence 1-255 X
Long byte sequence 256-max X(n)
Client 3 C(3)
Language int. 1, ext. 2 C(1)
ACCP
TIMS
RAW
LRAW
CLNT
LANG
Type
DATS
LCHR
CHAR
NUMC


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.
TI MS Time
RAW Byte sequence. Fields with type RAW may only be up to 255 characters long in
tables. If you want to use longer RAW fields in tables, use the data type LRAW.
LRAW Byte sequence of any length longer than 256 bytes. Fields of this type must
occur
at the end of transparent tables and be preceded by a length field with type INT2
that is filled with the required length when the table is filled.
CLNT Client
LANG Language key. This is displayed as a two-character code, but stored in the
database as a single character. It is converted using the exit ISOLA.


(C) SAP AG BC411 3-7
SAP AG
R
Calculations Using Numeric Types
REPORT sapbc411d_ar i t hmet i c.
DATA: i nt 1 TYPE i , i nt 2 TYPE i ,
pack1 TYPE p, f l oat TYPE f .
i nt 1 = 1. i nt 2 = 3. pack1 = 3.
f l oat = ( i nt 1 / i nt 2 ) * pack1.
WRI TE f l oat . 1,0000000000000000E+00
ABAP performs calculations using either F, P, or I arithmetic. The
arithmetic used is determined by the following rule:
F before P before I F before P before I


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




(C) SAP AG BC411 3-8
SAP AG
R
Summary of Declarative Statements
Input parameter
PARAMETERS
Constant
CONSTANTS
TABLES
Table work area
Type
TYPES
SELECT- OPTI ONS
RANGES
Selection criteria
Elementary field, structure,
internal table
DATA


You should already know the following declarative statements:

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

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


(C) SAP AG BC411 3-9
SAP AG
R
Type Conversion
Two structured types are compatible when they have
exactly the same structure and their components are
compatible.
Two table types are compatible when their line types are compatible and their
key sequences, uniqueness attributes and table types are the same.
Non-compatible types can be converted if a conversion rul e exists.
Compatible types can be assi gned to each other without conversion.
Two elementary types are compatible when they
have exactly the same type and length (and, for
type P fields, the same number of decimal places).
Two 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.


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



(C) SAP AG BC411 3-10
SAP AG
R
Conversion Rules for Elementary Types
For MOVE, COMPUTE, and comparisons, there are conversion rules f For MOVE, COMPUTE, and comparisons, there are conversion rules f or all or all
type combinations except type combinations except
C CT to D and vice versa T to D and vice versa
C C for ABAP Objects (classes and interfaces) for ABAP Objects (classes and interfaces)
REPORT sapbc411d_per f or mance_conver si .
DATA: pack TYPE p DECI MALS 2 VALUE ' 100, 00' ,
char 5( 5) TYPE c VALUE ' 12, 34' ,
char 7( 7) TYPE c VALUE ' 6789, 00' .
MOVE char 5 TO char 5. " Types compat i bl e( cost 2 mi cr osec. )
MOVE char 5 TO char 7. " Type conver si on ( cost 3 mi cr osec. )
MOVE char 5 TO pack. " Type conver si on ( cost 11 mi cr osec. )
Conversion rules exist for MOVE, COMPUTE and comparisons, but no Conversion rules exist for MOVE, COMPUTE and comparisons, but not for t for
the assignment of actual parameters to formal parameters in FORM the assignment of actual parameters to formal parameters in FORMS, S,
FUNCTIONS, METHODS, and ABAP Objects events. FUNCTIONS, METHODS, and ABAP Objects events.


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



(C) SAP AG BC411 3-11
SAP AG
R
Conversion Rule for Structure types
C
PROGRAM SAPBC41D_CONVERSI ON_OF_RECORD.
DATA: BEGI N OF r ec1,
t ext 1( 3) TYPE C VALUE ' AAA' ,
t ext 2( 2) TYPE C VALUE ' BB' ,
pack TYPE P DECI MALS 2 VALUE ' 2. 26' ,
t ext 3( 10) TYPE C VALUE ' YY' ,
END OF r ec1,
BEGI N OF r ec2,
t ext 1( 5) TYPE C VALUE ' CCCCC' ,
pack TYPE P DECI MALS 2 VALUE ' 72. 34' ,
t ext 3 TYPE C VALUE ' Z' ,
END OF REC2.
MOVE REC1 TO REC2.
REC1
REC2
REC2
AAA BB 2.26 YY
CCCCC 72.34 Z
AAABB 2.26 Y


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


(C) SAP AG BC411 3-12
SAP AG
R
Information About an Object at Runtime
REPORT xyz.
TABLES: sf l i ght .
DATA: f l i ght i nf o_l i st LI KE bcxaa OCCURS 10,
l i ne_count TYPE I .
SELECT * FROM sf l i ght I NTO TABLE f l i ght i nf o_l i st .
DESCRI BE TABLE f l i ght i nf o_l i st LI NES l i ne_count .
DESCRI BE FI ELD <f > LENGTH <l en>
TYPE <t ype> [ COMPONENTS <n>]
OUTPUT- LENGTH <l en>
DECI MALS <n>.
DESCRI BE TABLE <i t ab> LI NES <l i nes> [ OCCURS <n>] .
CARRID CONNID ...
Internal table FLIGHTINFO_LIST
LINE_COUNT
4
AA
AA
AA
AA
0017
0017
0026
0026


The DESCRI BE 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 (DECI MALS).
The DESCRI BE 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 I NI TI AL SIZE addition in the
table definition.


(C) SAP AG BC411 3-13
SAP AG
R
Summary
You can create data types either locall y in a program or
systemwide in the ABAP Dicti onary.
ABAP has three numeric types (P,I,F), five non-numeric
types (N,C,D,T,X), and a reference type (REF TO).
Each ABAP Dictionary type is converted by the ABAP
runtime environment into a numeric or non-numeric ABAP
data type.
The ABAP runtime system has type compatibility rules for
MOVE, COMPUTE, comparisons of data objects, and the
assignment of actual parameters to formal paramters.
There are type conversion rul es for MOVE, COMPUTE, and
comparisons of data objects.


SAP AG
R
Field Symbols: Contents
Pointers and field symbols
Using field symbols
Defining and assigning field symbols



(C) SAP AG BC411 4-2
SAP AG
R
Unit Objectives
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
At the end of this unit, you will be able to



(C) SAP AG BC411 4-3
SAP AG
R
Pointers and Field Symbols
Field symbol <fs1> Data object f1
ASSIGN f1 TO <fs1>.
Pointer p1 Data object p1^
Pointer ABAP field symbol
Pointer p2 Data object p2^ Field symbol <fs2> Data object f2
ASSIGN f2 TO <fs2>.
4
5
4
5


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 ASSI GN f TO <f s>assigns the field f to field symbol <f s>. The field symbol
<f s>then "points" to the contents of field <f >at runtime. This means that all changes to the
contents of f are visible in <f s>and vice versa. You declare the field symbol <f s>using the
statement
FI ELD- SYMBOLS: <f s>.


(C) SAP AG BC411 4-4
SAP AG
R
Reference and Value Semantics
ASSIGN <fs1> TO <fs2>.
Pointer p1 Data object p1^
Pointer p2 Data object p2^
4
5
p1 = p2. = p2.
p1^ = p2^. p1^ = p2^.
< <fs1> = <fs2>. > = <fs2>.
Field symbol <fs1> Data object f1
4
5
Field symbol <fs2> Data object f2
Value semantics
Reference semantics


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 <f s1>to a field symbol <f s2>, <f s1>takes the
value of the data object to which <f s2>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 <f s1>to field symbol <f s2>.
Position in a data structure
Field symbols in ABAP are defined using the FI ELD- SYMBOLS statement. However, the
statement does not define any data type of the ABAP type concept. This means that you cannot use
field symbols for chained lists or trees. Instead, chained lists can be programmed very elegantly in
ABAP using internal tables.




(C) SAP AG BC411 4-5
SAP AG
R
Using Field Symbols - Overview
LH 0400 12/31/1997 ...
<fs>
A B C D E F G H I . . .
<fs>
<fs>
L H SFLIGHT-CARRID
field_name
S F L I G H T - C A R R I D ...
Dynamic offset and length for a string Dynamic offset and length for a string
Dynamic ASSIGN for any Dynamic ASSIGN for any
data object data object
Processing components of a Processing components of a
structure structure
Addressing fields whose name is Addressing fields whose name is
unknown until runtime unknown until runtime


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



(C) SAP AG BC411 4-6
SAP AG
R
Using Field Symbols (1)
0
15
15
15 15
17 17
17
REPORT sapbc411d_f i el d_symbol s. REPORT sapbc411d_f i el d_symbol s.
DATA count er TYPE i .
FI ELD- SYMBOLS <f s> LI KE count er .
count er = 15.
ASSI GN count er TO <f s>.
WRI TE : / count er , <f s>.
<f s> = 17.
WRI TE : / count er , <f s>.
FI ELD- SYMBOLS <f s> [ TYPE t yp | LI KE s] .
ASSI GN f i el d TO <f s>.


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



(C) SAP AG BC411 4-7
SAP AG
R
Using Field Symbols (2)
UNASSI GN <f s>.
I F <f s> I S ASSI GNED.
PROGRAM sapbc411d_f i el d_symbol s. PROGRAM sapbc411d_f i el d_symbol s.
UNASSI GN <f s>.
I F <f s> I S ASSI GNED.
WRI TE ' Fi el d symbol poi nt s t o a dat a obj ect ' ( 001) .
ELSE.
WRI TE ' Fi el d symbol poi nt s nowher e' ( 002) .
ENDI F.


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

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



(C) SAP AG BC411 4-8
SAP AG
R
Assigning Parts of Strings Dynamically
REPORT sapbc411d_dyn_st r i ng_assi gn.
DATA: t ext _l i ne( 30) VALUE ABCDEFGHI J KLMNOPQRSTUVWXYZ ,
shor t _t ext _l i ne( 5) ,
st ar t TYPE i ,
st r i ng_l engt h TYPE i .
FI ELD- SYMBOLS <f st r i ng>.
st ar t = 2. st r i ng_l engt h = 5.
MOVE t ext _l i ne+st ar t ( st r i ng_l engt h) TO shor t _t ext _l i ne.
ASSI GN t ext _l i ne+st ar t ( st r i ng_l engt h) TO <f st r i ng>.
WRI TE: / <f st r i ng>.
<f st r i ng> = ' 123456789' .
WRI TE: / <f st r i ng>.
WRI TE: / t ext _l i ne.
A B C D E F G H I . . .
<fstring>
CDEFG
12345
AB12345HI...
Text_line


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


(C) SAP AG BC411 4-9
SAP AG
R
Processing Indi vidual Characters in a String
REPORT sapbc411d_f s_st r i ng.
DATA: st r i ng( 15) TYPE c VALUE ' HUGO BOSS' ,
n TYPE i .
FI ELD- SYMBOLS <f s>.
n = STRLEN( st r i ng ) .
ASSI GN st r i ng( 1) TO <f s>.
DO n TI MES.
WRI TE: / <f s>.
I F sy- i ndex NE n.
ASSI GN <f s>+1 TO <f s>.
ENDI F.
ENDDO.
<fs>
H U G O B O S S string
...


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

DO n TI MES.
ASSI GN st r i ng+sy- i ndex( 1) TO <f s>.
ENDDO.
It is important to query whether sy-index is unequal to n, since in the last loop pass, the field symbol
<f s>will point to the next memory address following the string. This could be a value that lies
outside the segment boundaries (see also memory protection concept).


(C) SAP AG BC411 4-10
SAP AG
R
Dynamic Field Assignment
REPORT sapbc411d_dyn_assi gn.
TABLES sf l i ght .
DATA f i el d_name( 30) .
FI ELD- SYMBOLS <t ab_f i el d>.
f i el d_name = ' SFLI GHT- CARRI D' .
ASSI GN ( f i el d_name) TO <t ab_f i el d>.
I F sy- subr c EQ 0.
SELECT * FROM sf l i ght .
WRI TE: / <t ab_f i el d>.
.
.
<tab_field>
S F L I G H T - C A R R I D
L H
field_name
SFLIGHT-CARRID
LH


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 f i el d_name contains the name of the field to be
assigned to the field symbol <t ab_f i el d>. Note that dynamic ASSIGN statements are very
runtime-intensive.
You can assign an ABAP Dictionary field to the field symbol using the addition TABLE FI ELD.
The statement would then read (as in the above example)
ASSI GN TABLE FI ELD ( f i el d_name) TO <t ab_f i el d>.
This shortens the runtime required by the statement, since the system knows that it does not have to
search in the list of program fields.
After the ASSIGN statement, the return code field SY- SUBRC tells you whether a field was
assigned to the field symbol:
SY- SUBRC = 0: The field in parentheses contained a valid field name.
SY- SUBRC > 0: The field in parentheses did not contain a valid field name. The field symbol
continues to point to the data object to which it pointed before the ASSIGN statement.




(C) SAP AG BC411 4-11
SAP AG
R
Referring to Components of a Structure
PROGRAM sapbc411_assi gn_component .
TABLES sf l i ght .
FI ELD- SYMBOLS: <f s>.
SELECT * FROM sf l i ght .
PERFORM wr i t e USI NG sf l i ght .
ENDSELECT.
FORM wr i t e USI NG r ec.
DO.
ASSI GN COMPONENT sy- i ndex OF STRUCTURE r ec TO <f s>.
I F sy- subr c NE 0.
EXI T.
ENDI F.
WRI TE <f s>.
ENDDO.
ULI NE.
ENDFORM.
PROGRAM sapbc411_assi gn_component .
TABLES sf l i ght .
FI ELD- SYMBOLS: <f s>.
SELECT * FROM sf l i ght .
PERFORM wr i t e USI NG sf l i ght .
ENDSELECT.
FORM wr i t e USI NG r ec.
DO.
ASSI GN COMPONENT sy- i ndex OF STRUCTURE r ec TO <f s>.
I F sy- subr c NE 0.
EXI T.
ENDI F.
WRI TE <f s>.
ENDDO.
ULI NE.
ENDFORM.
ASSI GN COMPONENT OF STRUCTURE r ec TO <f s>.
sflight LH 0400 12/31/1997 ...
<fs>
f i el dname f i el dname
n n


You can never address a component of an untyped structure:
FORM r out i ne USI NG r ec.
* ASSI GN ( ' r ec- f ' ) TO <f s>. " Unabl e t o access component s of
unt yped * st r uct ur e
ENDFORM.
Instead, use ASSI GN COMPONENT f OF STRUCTURE r ec TO <f s>.
This variant of the ASSIGN statement allows you to access the components of any structure. The
corresponding components of the structure rec are assigned to the field symbol <f s>.
You can assign the components by their name or their index.
If comp has type C or is a structure that does not contain an internal table, it is regarded as a
component name. Otherwise, it is interpreted as the component number. The statement returns a
value of SY- SUBRC unequal to 0 if the specified component comp of structure rec could not be
assigned to the field symbol.
In the above example, the subroutine write displays all of the components of the structure rec passed
to it.



(C) SAP AG BC411 4-12
SAP AG
R
Changing the Field Type
PROGRAM sapbc411d_f s_t ype_change.
PARAMETERS: packed( 3) TYPE p DEFAULT ' 128' ,
DATA: l ast di gi t s( 2) TYPE c,
l en TYPE i .
FI ELD- SYMBOLS: <f s>.
ASSI GN packed t o <f s> TYPE ' X' .
MOVE <f s>+2( 1) TO l ast di gi t s.
WRI TE: / l ast di gi t +1( 1) .
ASSI GN f i el d TO <f s> [ TYPE t ype] [ DECI MALS n] .


If a field symbol is untyped, you can use the TYPE addition to assign the type <t ype>to the field
symbol <f s>. 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 <f s>. The type <t ype>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 <t ype>.




(C) SAP AG BC411 4-13
SAP AG
R
Memory Protection
Common
part 2
...
Table work area 2 Common
part 1
All local data Table work
area 1
All global data
Address space


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


(C) SAP AG BC411 4-14
SAP AG
R
Summary
Field symbols allow you to
Assign an alias to a data object
Set the offset and length for a string at
runtime
Set a pointer to a data object that you
determine at runtime (dynamic ASSIGN)
Adopt the type of a field at runtime or
change the type of a field symbol
Access components of a structure


SAP AG
R
Internal Tables: Contents
Definitive attributes of internal tables
Hierarchy of table types
Defining internal tables
Internal table operations
Internal tables with and without header lines



(C) SAP AG BC411 5-2
SAP AG
R
Unit Objectives
List the attributes that determine the type of an
internal table
Decide which type of internal table is the most
appropriate in a gi ven situation
Define an internal table
Work with an internal table
Explain the difference between internal tables
with and without header lines
At the end of this unit, you will be able to



(C) SAP AG BC411 5-3
SAP AG
R
Internal Tables
Predefined
(P,I,F,C,N,D,T,X,REF TO)
Elementary
Struct.Fld type Table type Class/Interface
Structured
User-defined
Data type
ABAP
Array Chained list
Dynamic
table
extension !!!


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


(C) SAP AG BC411 5-4
SAP AG
R
Uniqueness attribute Uniqueness attribute
Internal Table Attributes
AA 0017 2,572
LH 0400 6,162
QF 0005 10,000
Index access
LH 0400 6,162
5 5
Key access
UA 0007 UA 0007
Line type Line type
Key sequence Key sequence
Table type Table type
CARRID CONNID DISTANCE CARRID CONNID DISTANCE
SQ 0866 1,625
UA 0007 2,572


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




(C) SAP AG BC411 5-5
SAP AG
R
Table Types
Key access
Access costs linear increase logarithmic increase constant
with n entries (O(n)) (O(log(n)) (O(1))
Access using
Mainly index Mainly key Only key
Unique or not NON-UNIQUE UNIQUE | NON-UNIQUE UNIQUE
STANDARD TABLE SORTED TABLE
INDEX TABLE HASHED TABLE
ANY TABLE
n n
Table scan Binary
search
Hash
function


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 <i t ab>using the statement
DESCRI BE TABLE <i t ab> KI ND <k>.


(C) SAP AG BC411 5-6
SAP AG
R
Response Times ...
Example: Both tables have n entries
Standard table: Increases quadratically, O(n
2
)
double n runtime increases fourfold
Sorted table: Increases logarithmically, O(n log
2
n)
double n runtime increases by factor 2 +2/log
2
n
Hashed table: Increases constantly, O(n)
double n runtime doubles
LOOP AT Out er Tabl e I NTO Out er Wa.
. . .
READ TABLE I nner Tabl e I NTO I nner Wa WI TH TABLE KEY . . .
. . .
ENDLOOP.
LOOP AT Out er Tabl e I NTO Out er Wa.
. . .
READ TABLE I nner Tabl e I NTO I nner Wa WI TH TABLE KEY . . .
. . .
ENDLOOP.


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


(C) SAP AG BC411 5-7
SAP AG
R
Access Times
Loop costs for each internal table type
1
1
0
1
0
0
1
0
0
0
1
0
0
0
0
1
E
+
0
5
1
E
+
0
6
5 10 20 40 80 160 320 640 1280
Number of table entries: n
T
i
m
e

i
n

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


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


(C) SAP AG BC411 5-8
SAP AG
R
Defining Internal Tables
DATA: <i t ab> TYPE of <l i net ype>
WI TH [ UNI QUE | NON- UNI QUE]
[ I NI TI AL SI ZE <n>]
[ WI TH HEADER LI NE] .
TYPES: <i t abt ype> TYPE of <l i net ype>
[ WI TH [ UNI QUE | NON- UNI QUE] ]
[ I NI TI AL SI ZE <n>] .
<i t abki nd>
<keydef >
[ STANDARD] TABLE | SORTED TABLE | HASHED TABLE
addi t i onal l y, f or t ypes: I NDEX TABLE | ANY TABLE
KEY <f 1> . . . <f n> |
KEY TABLE LI NE |
DEFAULT KEY
<i t abki nd>
<keydef >
<keydef >
<i t abki nd>
AA 0017 2,572
LH 0400 6,162
QF 0005 10,000
LH 0400 6,162
CARRID CONNID DISTANCE CARRID CONNID DISTANCE
SQ 0866 1,625
UA 0007 2,572


The statement
TYPES <i t abt ype> TYPE <t abki nd> OF <l i net ype>
[ WI TH [ UNI QUE | NON- UNI QUE] <keydef >] [ I NI TI AL SI ZE <n>]
creates a data type with type <i t abt ype>, table type <t abki nd>, and line type <l i net ype>.
Normally, you also specify a user-defined key in the form <f 1> <f n>. 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 I NI TI AL SI ZE
<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 I NDEX TABLE and ANY TABLE. These types
are useful for specifying the types of parameters in subroutines.


(C) SAP AG BC411 5-9
SAP AG
R
Internal Tables in Memory (1)
Table header
Fixed size: 256 bytes
DATA: i t ab TYPE TABLE OF st r uc.
Dynamic data structure
Empty table occupies 256 bytes (header)



(C) SAP AG BC411 5-10
SAP AG
R
Internal Tables in Memory (2)
Table body(line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
Table header
Fixed size: 256 bytes
DATA: i t ab TYPE TABLE OF st r uc.
Dynamic data structure
An empty table occupies 256 bytes (header)
Maximum line length is 64K
APPEND wa TO i t ab. " 1. Ei nt r ag 1
m
2



(C) SAP AG BC411 5-11
SAP AG
R
Internal Tables in Memory (3)
1
Table body(line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
2
APPEND wa TO i t ab. " 1st ent r y
Table header
Fixed size: 256 bytes
DATA: i t ab TYPE TABLE OF st r uc.
APPEND wa TO i t ab. " 2nd ent r y
Dynamic data structure
Empty table occupies 256 bytes (header)
Maximum line length is 64K



(C) SAP AG BC411 5-12
SAP AG
R
Internal Tables in Memory (4)
1
Table body (line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
2
APPEND wa TO i t ab. " 1st ent r y
Table header
Fixed size: 256 bytes
DATA: i t ab TYPE TABLE OF st r uc.
APPEND wa TO i t ab. " 2nd ent r y
APPEND wa TO i t ab. " m+1t h ent r y
2nd page:
2m entries (e.g.32)
m+1
Dynamic data structure
Empty table occupies 256 bytes (header)
Maximum line length 64K



(C) SAP AG BC411 5-13
SAP AG
R
Internal Tables in Memory (5)
1
Table body(line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
2
APPEND wa TO i t ab. " 1st ent r y
Table header
Fixed size: 256 bytes
DATA: i t ab TYPE TABLE OF st r uc.
APPEND wa TO i t ab. " 2nd ent r y
APPEND wa TO i t ab. " m+1t h ent r y
2nd page:
2m entries (e.g.32)
m+1
Dynamic data structure
Empty table occupies 256 bytes (header)
Maximum line length is 64K
APPEND wa TO i t ab. " 3m+1t h ent r y
3m+1
3rd page:
M enrties (e.g.1024)



(C) SAP AG BC411 5-14
SAP AG
R
Internal Tables in Memory (6)
1
Table body (line width e.g. 8 bytes)
1st page:
m entries (e.g.16)
2
APPEND wa TO i t ab. " 1st ent r y
Table header
Fixed size: 256 bytes
DATA: i t ab TYPE TABLE OF st r uc.
APPEND wa TO i t ab. " 2nd ent r y
APPEND wa TO i t ab. " m+1t h ent r y
2nd page:
2m entries (e.g. 32)
m+1
Dynamic data structure
Empty table occupies 256 bytes (header)
Maximum line length is 64 KB
APPEND wa TO i t ab. " 3m+1t h ent r y
3m+1
3rd page:
M entries (e.g. 1024)
8-16 KB
4th page:
M entries
(e.g.1024)
8-16 KB
4m+1


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



(C) SAP AG BC411 5-15
SAP AG
R
Special Internal Table Operations
Internal table <itab>
Work area <wa>
CARRID CONNID
SORT <i t ab> BY <f i el d1> . . . <f i el dn>.
REFRESH <i t ab>.
FREE <i t ab>.
LOOP AT <i t ab>. ENDLOOP.
READ TABLE <i t ab> . . . .
APPEND . . . <i t ab>.
COLLECT . . . <i t ab>.
I NSERT . . . <i t ab>.
MODI FY <i t ab> . . . .
DELETE <i t ab> . . . .
AA
LH
0017
0400


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 <i t ab> ASSI GNI NG <f s> or READ TABLE <i t ab> ASSI GNI NG <f s>,
where <f s>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
I NSERT Inserts the work area in a particular line of the internal table
MODI FY Overwrites a particular line of the internal table with the contents of the work area
DELETE Deletes a particular line from the internal table
LOOP AT Places the lines of the internal table one by one in a work area
READ TABLE Places a single line of an internal table into a work area
SORT Sorts the internal table
REFRESH Deletes the internal table
FREE Deletes the internal table and releases all of the resources used by it




(C) SAP AG BC411 5-16
SAP AG
R
Operations on all Data Objects
TYPES: BEGI N OF l i ne_t ype,
f 1 TYPE c,
f 2 LI KE TABLE OF sf l i ght - car r i d,
END OF l i ne_t ype.
DATA: i t ab1 TYPE TABLE OF l i ne_t ype,
i t ab2 TYPE TABLE OF l i ne_t ype.
MOVE i t ab1 TO i t ab2.
I F i t ab1 = i t ab2.
WRI TE / ' Tabl es ar e t he same' .
ENDI F.
CLEAR: i t ab1, i t ab2.
MOVE <dat aobj ect 1> TO <dat aobj ect 2>.
I F <dat aobj ect 1> = <dat aobj ect 2>. . . . . ENDI F.
CLEAR <dat aobj ect >.
ASSI GN <dat aobj ect > TO <f s>.
EXPORT <dat aobj ect > TO MEMORY | DATABASE . . . .
I MPORT <dat aobj ect > TO MEMORY | DATABASE . . . .


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
I F Compares the contents of one data object with those of another data object
CLEAR Deletes the contents of a data object
ASSI GN Assigns a data object to a field symbol
EXPORT Writes a data object to a cluster database or ABAP memory
I MPORT 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, I F, CLEAR, and
I MPORT/ EXPORT operations. This also applies to the FREE and REFRESH statements, but not for
the SORT statement (no deep SORT).


(C) SAP AG BC411 5-17
SAP AG
R
Index Access Using Read
Internal table st and_t ab
Work area wa
f1 f2
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2,
END OF l i ne_t ype.
DATA: st and_t ab TYPE STANDARD TABLE OF l i ne_t ype WI TH KEY f 1,
wa TYPE l i ne_t ype.
READ TABLE st and_t ab I NDEX 2 I NTO wa.
2 2
b 1
a
b
1
1


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



(C) SAP AG BC411 5-18
SAP AG
R
Index Operations on Internal Tables
Read
Append
Insert
Change
Delete
Single record processing Mass processing
LOOP AT <i t ab>
[ FROM <n1>] [ TO <n2>]
[ I NTO <wa>] .
ENDLOOP.
READ TABLE <i t ab>
I NDEX <n>
[ I NTO <wa>] .
I NSERT [ <wa I NTO] <i t ab>
[ I NDEX <n>] .
MODI FY <i t ab> [ I NDEX <n>]
[ FROM <wa>] .
DELETE <i t ab>
[ I NDEX <n>] .
DELETE <i t ab>
FROM <n1> TO <n2>.
I NSERT LI NES OF <i t ab1>
[ FROM <n1>] [ TO <n2>]
I NTO <i t ab2> [ I NDEX <n3>] .
APPEND [ <wa> TO] <i t ab>. APPEND LI NES OF <i t ab1>
[ FROM <n1>] [ TO n2] TO <i t ab2>.
n n


Internal table operations can be classified as follows:
By their access method as index operations or key operations.
By the scope of their access as single record processing or mass processing. Single record
processing accesses one line in each operation, mass processing accesses n lines.
By the operation type, as Read, Append, Insert, Change, or Delete.
ABAP contains the following index operations: Note, again, that index operations are not allowed
on hashed tables.
READ TABLE <i t ab> I NDEX <n> I NTO <wa>.
Reads the contents of the <n>th line of <i t ab>into the work area <wa>.
APPEND <wa> TO <i t ab>.
Appends the contents of <wa>to the end of <i t ab>.
I NSERT <wa> I NTO <i t ab> I NDEX <n>.
Inserts the contents of <wa>into the table before line <n>.
MODI FY <i t ab> I NDEX <n> FROM <wa>.
Overwrites the <n>th line of <i t ab>with the contents of <wa>.
DELETE <i t ab> I NDEX <n>.
Deletes the <n>th line of <i t ab>.



(C) SAP AG BC411 5-19
SAP AG
R
Linear Index (1)
Table body(line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
Table header
Fixed size: 256 bytes
2nd page:
2m entries (e.g.32)
m+1
3m+1
3rd page:
M entries (e.g.1024)
8-16 KB
4th page:
M entries
(e.g.1024)
8-16 KB
DELETE i t ab I NDEX 2.
Linear index
1
4
5
3
2
1
2
1
2
3
4



(C) SAP AG BC411 5-20
SAP AG
R
Linear Index (2)
1
Table body(line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
2
Table header
Fixed size: 256 bytes
2nd page:
2m entries (e.g.32)
3rd page:
M entries (e.g.1024)
8-16 KB
4th page:
M entries
(e.g.1024)
8-16 KB
DELETE i t ab I NDEX 2.
DELETE i t ab I NDEX 51.
Linear index
1
4
5
3 51
50
52
2
m+1
3m+1
1
2
3
4



(C) SAP AG BC411 5-21
SAP AG
R
Linear Index (3)
1
Table body(line width, e.g. 8 bytes)
1st page:
m entries (e.g.16)
2
Table header
Fixed size: 256 bytes
2nd page:
2m entries (e.g.32)
3rd page:
M entries (e.g.1024)
8-16 KB
4th page:
M entries
(e.g.1024)
8-16 KB
DELETE i t ab I NDEX 2.
Linear index
1
4
5
3
DELETE i t ab I NDEX 51.
51
50
52
I NSERT wa I NTO i t ab
I NDEX 3.
2
3m+1
m+1
1
2
3
4


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


(C) SAP AG BC411 5-22
SAP AG
R
Accessing a Single Generic Entry with READ
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2,
END OF l i ne_t ype.
DATA: st and_t ab TYPE STANDARD TABLE OF l i ne_t ype WI TH KEY f 1,
wa t ype l i ne_t ype.
wa- f 1 = ' b' . wa- f 2 = ' 5' .
READ TABLE st and_t ab FROM wa I NTO wa. " implicity from wa
READ TABLE st and_t ab WI TH TABLE KEY f 1 = ' b' I NTO wa. " explicitly
Internal table st an_t ab
Work area wa
f1 f2
b 5
b 1
A
b
1
1


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
WI TH KEY <f 1> = <v1> . . . AND <f n> = <vn>or
WI TH TABLE KEY <f 1> = <v1> . . . <f n> = <vn>.
In the second case, <f 1> <f n>must be key fields of the table.
The READ variants " FROM <wa>" and " WI TH 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 WI TH KEY addition (note: no TABLE in
the addition). This is not internally optimized.
If you use WI TH KEY to access a hashed table, the cost is no longer constant, but linear.
The exception to the general rule for WI TH KEY is that the access is internally optimized for sorted
tables where the specified key is a left-justified extract of the beginning of the table key.






(C) SAP AG BC411 5-23
SAP AG
R
Generic Key Operations
Read
Insert
Cumulate
Change
Delete
Single record processing Mass processing
Implicit (from <wa>) explicit
I NSERT [ <wa> I NTO]
TABLE <i t ab>.
READ TABLE <i t ab>
[ I NTO <wa>]
WI TH [ TABLE] KEY
<k> = <v>.
LOOP AT <i t ab>
[ I NTO <wa>]
WHERE <condi t i on>.
READ TABLE <i t ab>
[ I NTO <i t ab_wa>]
FROM <wa>.
MODI FY TABLE <i t ab>
[ FROM <wa>] .
MODI FY <i t ab>
[ FROM <wa>]
WHERE <condi t i on>.
DELETE TABLE <i t ab>
[ FROM <wa>] .
DELETE TABLE <i t ab>
WI TH TABLE KEY
<k> = <v>.
DELETE <i t ab>
WHERE <condi t i on>.
I NSERT LI NES
OF <i t ab1>
I NTO TABLE <i t ab2>.
COLLECT [ <wa> I NTO]
<i t ab>.


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 WI TH [ TABLE] KEY addition.
If you try to insert a single duplicate entry into an internal table with unique key, the insertion fails,
and SY- SUBRC is set to 4. This allows you to filter out duplicates from a set of entries very easily.
If you try to insert duplicates during mass processing, a runtime error occurs.
This overview is further illustrated by examples on the following pages.



(C) SAP AG BC411 5-24
SAP AG
R
Operations on Standard Tables (Example)
REPORT sapbc411_st andar d_t ab.
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2,
END OF l i ne_t ype.
DATA: st and_t ab TYPE STANDARD TABLE OF l i ne_t ype WI TH KEY f 1,
wa TYPE l i ne_t ype.
wa- f 1 = ' a' . wa- f 2 = ' 1' . APPEND wa TO st and_t ab.
t abi x = sy- t abi x + 1. wa = ' c1' . I NSERT wa I NTO st and_t ab I NDEX t abi x.
wa- f 1 = ' b' . wa- f 2 = ' 1' . I NSERT wa I NTO TABLE st and_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 2' . I NSERT wa I NTO TABLE st and_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 2' . MODI FY TABLE st and_t ab FROM wa.
wa- f 1 = ' a' . DELETE TABLE st and_t ab FROM wa.
READ TABLE st and_t ab I NTO wa I NDEX 1. WRI TE wa- f 1, wa- f 2.
LOOP AT st and_t ab I NTO wa. WRI TE wa- f 1, wa- f 2. ENDLOOP.
SORT st and_t ab by f 2.
TYPES: <i t abt ype> TYPE [ STANDARD] TABLE of <l i net ype>
[ WI TH [ NON- UNI QUE] <keydef >]
[ I NI TI AL SI ZE <n>] .


The above example processes the following operations using the data objects st and_tab and wa:
Appends the contents of wa ( ' a1' ) to the end of st and_t ab. The index of the insertion point is
placed in SY- TABIX and is 1 in the example.
Inserts the contents of wa ( ' c1' ) in st and_tab at the position SY- TABI X + 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 st and_t ab. 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 st and_t ab. 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 st and_tab according to field f 2.


(C) SAP AG BC411 5-25
SAP AG
R
Internal Tables With and Without Header Line
CARRID CONNID
Internal table <itab>
Work area <wa>
CARRID CONNID
Internal table <itab>
Header line <itab>
APPEND <wa> TO <i t ab>.
I NSERT <wa> I NTO <i t ab> I NDEX <n>.
MODI FY <i t ab> I NDEX <n> FROM <wa>.
DELETE TABLE <i t ab> FROM <wa>.
READ TABLE <i t ab> I NDEX <n>
I NTO <wa>.
LOOP AT <i t ab> I NTO <wa>.
WRI TE <wa>- <f >.
ENDLOOP.
APPEND <i t ab>.
I NSERT <i t ab> I NDEX <n>.
MODI FY <i t ab> I NDEX <n>.
DELETE TABLE <i t ab>.
READ TABLE <i t ab> I NDEX <n>.
LOOP AT <i t ab>.
WRI TE <i t ab>- <f >.
ENDLOOP.
Short syntax Clear syntax
AA
LH
0017
0400
AA
LH
0017
0400


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,
I NSERT, MODI FY, COLLECT, DELETE, READ, LOOP) .
You can always address the body of an internal table itab using the syntax i t ab[], regardless of
whether itab has a header line or not.
Example:
DATA: i t ab1 TYPE TABLE OF i WI TH HEADER LI NE.
DATA: i t ab2 TYPE TABLE OF i WI TH HEADER LI NE.

i t ab1 = i t ab2 "Copies only the header lines.
i t ab1[ ] = i t ab2[ ] "Copies the contents of the entire table.





(C) SAP AG BC411 5-26
SAP AG
R
Declaring an Internal Table With Header Line
DATA: <i t ab> TYPE <i t abki nd> OF <l i net ype>
WI TH [ UNI QUE | NON- UNI QUE] <keydef >
[ I NI TI AL SI ZE <n>]
[ WI TH HEADER LI NE] .
REPORT sapbc411_st andar d_t ab.
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2,
END OF l i ne_t ype.
DATA: st and_t ab TYPE STANDARD TABLE OF l i ne_t ype
WI TH KEY f 1 WI TH HEADER LI NE,
wa TYPE l i ne_t ype.
st and_t ab = ' a1' . APPEND wa TO st and_t ab.
t abi x = sy- t abi x + 1.
st and_t ab = ' c1' . I NSERT wa I NTO st and_t ab I NDEX t abi x.
st and_t ab = ' b1' . I NSERT wa I NTO TABLE st and_t ab.
st and_t ab = ' b2' . I NSERT wa I NTO TABLE st and_t ab.
st and_t ab = ' b2' . MODI FY TABLE st and_t ab FROM wa.
st and_t ab = ' a1' . DELETE TABLE st and_t ab FROM wa.
READ TABLE st and_t ab I NDEX 1 I NTO wa. WRI TE wa- f 1, wa- f 2.
SORT st and_t ab.


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


(C) SAP AG BC411 5-27
SAP AG
R
Sorted Table (Example)
DATA: <i t abt ype> TYPE SORTED TABLE of <l i net ype>
[ WI TH [ UNI QUE | NON- UNI QUE] <keydef >]
[ I NI TI AL SI ZE <n>] [ WI TH HEADER LI NE] .
REPORT sapbc411_sor t ed_t ab.
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2,
END OF l i ne_t ype.
DATA: sor t ed_t ab TYPE SORTED TABLE OF l i ne_t ype
WI TH UNI QUE KEY f 1,
wa TYPE l i ne_t ype.
wa- f 1 = ' a' . wa- f 2 = ' 1' . I NSERT wa I NTO TABLE sor t ed_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 1' . I NSERT wa I NTO TABLE sor t ed_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 2' . I NSERT wa I NTO TABLE sor t ed_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 2' . MODI FY TABLE sor t ed_t ab FROM wa.
wa- f 1 = ' b' . DELETE TABLE sor t ed_t ab FROM wa.
READ TABLE sor t ed_t ab I NTO wa I NDEX 1. WRI TE wa- f 1, wa- f 2.
LOOP AT sor t ed_t ab I NTO wa. WRI TE wa- f 1, wa- f 2. ENDLOOP.


The above example processes the following operations using the data objects sor t ed_tab and wa:
Inserts the contents of wa ( ' a1' ) into sor t ed_t ab.
Inserts the contents of wa ( ' b1' ) into sor t ed_t ab.
Inserts the contents of wa ( ' b2' ) into sor t ed_t ab. This insertion would lead to a
duplicate key ( ' b' ). Since sor t ed_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 I NSERT INDEX and APPEND for sorted tables, since the system only checks
whether the sort sequence is violated or not. If your table entries are already correctly sorted before
you insert them in the table, you can use these statements to bypass the normal binary search for the
correct insertion point.
You cannot explicitly sort a sorted table using the SORT statement.


(C) SAP AG BC411 5-28
SAP AG
R
Partial Sequential Processing: Sorted Tables
REPORT sapbc411_par t seq_l oop.
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2, f 3, f 4,
END OF l i ne_t ype.
DATA: sor t ed_t ab TYPE SORTED TABLE OF l i ne_t ype
WI TH NON- UNI QUE KEY f 1 f 2 f 3,
wa TYPE l i ne_t ype.
*. . . Fi l l sor t ed_t ab wi t h non- uni que val ues . . .
LOOP AT sor t ed_t ab I NTO wa
WHERE f 1 = ' X' AND f 2 = ' Y' . "opt i mi zed
. . . .
ENDLOOP.
LOOP AT sor t ed_t ab I NTO wa
WHERE f 1 = ' X' AND f 3 = ' Z' . "not opt i mi zed
. . . .
ENDLOOP.


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 f 3. Since f2 is missing, this is not a genuine extract of
the beginning of the key.
The same applies to the READ statement for sorted tables.


(C) SAP AG BC411 5-29
SAP AG
R
Hashed Tables (Example)
TYPES: <i t abt ype> TYPE HASHED TABLE of <l i net ype>
[ WI TH UNI QUE <keydef >]
[ I NI TI AL SI ZE <n>] .
REPORT sapbc411_hashed_t ab.
TYPES: BEGI N OF l i ne_t ype,
f 1, f 2,
END OF l i ne_t ype.
DATA: hashed_t ab TYPE HASHED TABLE OF l i ne_t ype
WI TH UNI QUE KEY f 1,
wa TYPE l i ne_t ype.
wa- f 1 = ' a' . wa- f 2 = ' 1' . I NSERT wa I NTO TABLE hashed_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 1' . I NSERT wa I NTO TABLE hashed_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 2' . I NSERT wa I NTO TABLE hashed_t ab.
wa- f 1 = ' b' . wa- f 2 = ' 2' . MODI FY TABLE hashed_t ab FROM wa.
wa- f 1 = ' b' . DELETE TABLE hashed_t ab FROM wa.
LOOP AT hashed_t ab I NTO wa.
WRI TE wa- f 1, wa- f 2.
ENDLOOP.
SORT hashed_t ab.


The above example processes the following operations using the data objects hashed_tab and wa:
Inserts the contents of wa ( ' a1' ) into hashed_t ab.
Inserts the contents of wa ( ' b1' ) into hashed_t ab.
Inserts the contents of wa ( ' b2' ) into hashed t ab. 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, I NSERT . I NDEX) on hashed tables.



(C) SAP AG BC411 5-30
SAP AG
R
Filling an Internal Table with Cumulative Values
CARRID PRICE (TYPE P)
4
5
6
7
8
9
LH 100000 wa
AA 2090938 1
DL 933338 2
LH 1766669 3 1866669
COLLECT [ <wa> I NTO] <i t ab>. REPORT sapbc411d_col l ect _i t ab.
TYPES: BEGI N OF f l i ght i nf o_t ype,
car r i d LI KE sf l i ght - car r i d,
pr i ce LI KE sf l i ght - pr i ce,
END OF f l i ght i nf o_t ype.
DATA: f l i ght i nf o_l i st TYPE HASHED TABLE OF
f l i ght i nf o_t ype WI TH UNI QUE KEY car r i d
conni d,
wa TYPE f l i ght i nf o_t ype.
SELECT car r i d pr i ce FROM sf l i ght I NTO wa.
COLLECT wa I NTO f l i ght i nf o_l i st .
ENDSELECT.


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




(C) SAP AG BC411 5-31
SAP AG
R
Summary of Internal Table Operations
INSERT
COLLECT
MODIFY
DELETE
READ
LOOP
INSERT
APPEND
MODIFY
DELETE
READ
LOOP
SORT
Standard table Sorted table Hashed table
Same as append Inserts in correct sort order Same as append
n n
No index
operations on
hashed tables
Possible sort
order violation
See above
O(n) O(log n) O(1)
But LOOP always
uses a full table scan
O(1) O(1) O(1)
O(1) O(n) bis


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, I NSERT I NDEX, LOOP
FROMTO).
You can use SORT for standard tables and hashed tables. It has no positive effect in a sorted table,
and can lead to a syntax or runtime error if the attempted sort violates the key sequence.
You can use control level processing with all table types. Hashed and standard tables must be sorted
beforehand.


(C) SAP AG BC411 5-32
SAP AG
R
DATA: BEGI N OF <i t ab> OCCURS <n>,
<f 1>, . . . , <f n>,
END OF <i t ab>.
TYPES: BEGI N OF <l i ne_t ype>,
<f 1>, . . . , <f n>,
END OF <l i ne_t ype>.
DATA: <i t ab> TYPE <l i ne_t ype>
OCCURS <n>
WI TH HEADER LI NE.
TYPES: BEGI N OF <l i ne_t ype>,
<f 1>, . . . , <f n>,
END OF <l i ne_t ype>.
DATA: <i t ab> TYPE TABLE OF <l i ne_t ype>
WI TH HEADER LI NE.
Release 2.2
Release 3.0
Release 4.0
TYPES: BEGI N OF <l i ne_t ype>,
<f 1>, . . . , <f n>,
END OF <l i ne_t ype>.
DATA: <i t ab> TYPE STANDARD TABLE OF <l i ne_t ype>
WI TH DEFAULT KEY I NI TI AL SI ZE <n>
WI TH HEADER LI NE.
Standard Table Definitions (History)


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 BEGI N of <i t ab> OCCURS <n> and END OF <i t ab>. OCCURS <n>had two
meanings: Firstly, it specified the initial size of the table, secondly, it was the addition that identified
the data object as an internal table. The implicit key of this kind of internal table consisted of all
elementary non-numeric fields. The only attribute that determined the table type was the line type.
Caution: This syntax still occurs very frequently in ABAP programs. Remember that it defines a
standard table with header line and an implicitly-defined key.
Release 3.0 saw the introduction of the ABAP type concept. For internal tables, this meant that:
The line type could be defined separately and referenced in the definition of the internal table
itself.
You could define an internal table as a type.
From Release 3.0 onwards, it was also no longer necessary to work with a header line.
From Release 4.0, the type of an internal table consists of a freely-definable key, the uniqueness
attribute, and the table type, as well as the line type.


(C) SAP AG BC411 5-33
SAP AG
R
Summary
The attributes of an internal table that constitute its
type are the line type, key fiel d sequence,
uniqueness attribute, and table type.
Standard tables are particularl y suitable for index
acces. Sorted tables provide good performance if
you use a key, and also allow you to use an index.
Hashed tables provide excell ent performance if you
specify the entire key of an entry, but index access
is not allowed.
A header line is a work area belonging to an
internal table. You address it using the same name
as the body of the table.


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
R
Object-Oriented Programming with ABAP
Objects: Contents
What are objects?
Advantages of object-oriented
programming
From function groups to objects
Classes and objects
What is ABAP Objects?
Classes
Attributes
Reference variables and object instances
Defining and implementing methods
Defining and implementing interfaces
Triggering and handling events



(C) SAP AG BC411 6-2
SAP AG
R
Objectives
At the end of this unit, you will be able to:
Position ABAP Objects within the overall
structure of the ABAP language
Understand and use the basic techniques
of object-oriented programming using
ABAP Objects



(C) SAP AG BC411 6-3
SAP AG
R
What are Objects?
Function
Funct ion Function
Function Function Funct ion
Function
Function
Data Data Data Data
Data Data
Data Data
Data Data
Object
attributes
Data
Method
Method
Method
Data
Method
Method
Method
Functions and Data Real World: Objects Objects
Encapsulation Encapsulation
Abstraction Abstraction



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




(C) SAP AG BC411 6-4
SAP AG
R
Public
access
Pri vate
access
Object
attributes
Interface
Events
Public
attributes
Methods
Address
Customer
Passenger
list
Flight
BOOK
Objects
Ai rline
Flight number


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



(C) SAP AG BC411 6-5
SAP AG
R
Encapsulation
Pr ogr am: . . .
add 1 t o
Object: Flight Object: Flight
Method:
book
Attribute:
passenger
Pr ogr am: . . .
Read t abl e
No access No access
passenger
passenger


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


(C) SAP AG BC411 6-6
SAP AG
R
Advantages of Object-Oriented Programming
Encapsulation and interfaces
Easy to maintain, high quality
Generic programming and reusability
Integration of external object models
Distributed applications
Support for GUI and Business Workflow


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


(C) SAP AG BC411 6-7
SAP AG
R
From Function Groups to Objects I
External session
Data Data
...
Function Function
module module

Function group 1 1
Data Data
...
Function Function
module module

Function group 2
ABAP program with data
Internal session of an ABAP program


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


(C) SAP AG BC411 6-8
SAP AG
R
From Function Groups to Objects II
External session External session
Daten Daten
...
Schnitt Schnitt- -
stelle stelle

nth instance, class 1


Data Data
...
Interface Interface

1st instance, class 1


Daten Daten
...
Funktions Funktions- -
baustein baustein

nth instance, class n


Data Data
...
Function Function
module module

1st instance, class n


Internal session of an ABAP program
ABAP program with data


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 OBJ ECT. The individual runtime instances
represent unique objects. You address these using object references. Object references are a new
ABAP data type (REF TO).



(C) SAP AG BC411 6-9
SAP AG
R
D0815
1
2
D0815
1
2
Classes and Objects
Plane
Cargo plane Passenger pl ane
Pri vate plane Business pl ane
D4711
1
3
D4711
1
3
Name
Pilots
Capacity
Name
Pilots
Passengers
BB Broadway
2
30.000 kg
BB Broadway
2
30.000 kg
Name
Pilots
Crew
Passengers
AA Holl ywood
2
30,000 kg
AA Holl ywood
2
30,000 kg
BA Big Ben
2
5
200
BA Big Ben
2
5
200
LH Munich
2
3
80
LH Munich
2
3
80
Generalization
Instantiati on


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


(C) SAP AG BC411 6-10
SAP AG
R
What is ABAP Objects?
ABAP Objects is a fully compatible extension of the
exisiting ABAP language.
You can use 'conventional' ABAP statements within
ABAP Objects.
Equally, you can use ABAP Objects within
conventional ABAP programs.


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


(C) SAP AG BC411 6-11
SAP AG
R
Classes I
CLASS <cl ass> DEFI NI TI ON.
PUBLI C SECTI ON.
. . . Def i ni t i on of publ i c component s
PROTECTED SECTI ON.
. . . Def i ni t i on of pr ot ect ed component s
PRI VATE SECTI ON.
. . . Def i ni nt i on of pr i vat e component s
ENDCLASS.
CLASS <cl ass> I MPLEMENTATI ON.
. . . Met hod i mpl ement at i on
ENDCLASS.
CLASS <cl ass> DEFI NI TI ON.
PUBLI C SECTI ON.
. . . Def i ni t i on of publ i c component s
PROTECTED SECTI ON.
. . . Def i ni t i on of pr ot ect ed component s
PRI VATE SECTI ON.
. . . Def i ni nt i on of pr i vat e component s
ENDCLASS.
CLASS <cl ass> I MPLEMENTATI ON.
. . . Met hod i mpl ement at i on
ENDCLASS.


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


(C) SAP AG BC411 6-12
SAP AG
R
Classes II
All users
Class c1
Private
components
a3,
m3,
e3
Method
implementation
Subclasses of c1
Protected components
a2, m2, e2,
Public
components
a1,
m1,
e1

CLASS c1 DEFI NI TI ON.


PUBLI C SECTI ON.
DATA: a1
METHODS: m1
EVENTS: e1
PROTECTED SECTI ON.
DATA: a2
METHODS: m2
EVENTS: e2
PRI VATE SECTI ON.
DATA: a3
METHODS: m3
EVENTS: e3
ENDCLASS.
CLASS c1 I MPLEMENTATI ON.
METHOD m1. ENDMETHOD.
METHOD m2. ENDMETHOD.
METHOD m3. ENDMETHOD.
ENDCLASS.


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


(C) SAP AG BC411 6-13
SAP AG
R
Declaring Attributes
DATA <at t r > TYPE <t ype>
[ VALUE <val > ]
[ READ- ONLY ] .
DATA <at t r > TYPE <t ype>
[ VALUE <val > ]
[ READ- ONLY ] .
REPORT sapbc411d_f l i ght .
CLASS c_cust omer DEFI NI TI ON.
PUBLI C SECTI ON.
*- - I D can onl y be changed wi t hi n met hods of t hi s cl ass
DATA: i d TYPE i READ- ONLY,
name( 30) TYPE C VALUE ' DummyCust omer ' .
ENDCLASS.
REPORT sapbc411d_f l i ght .
CLASS c_cust omer DEFI NI TI ON.
PUBLI C SECTI ON.
*- - I D can onl y be changed wi t hi n met hods of t hi s cl ass
DATA: i d TYPE i READ- ONLY,
name( 30) TYPE C VALUE ' DummyCust omer ' .
ENDCLASS.


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



(C) SAP AG BC411 6-14
SAP AG
R
Static Attributes
CLASS- DATA <at t r > TYPE <t ype>
[ VALUE <val > ]
[ READ- ONLY ] .
CLASS- DATA <at t r > TYPE <t ype>
[ VALUE <val > ]
[ READ- ONLY ] .
REPORT sapbc411d_f l i ght .
CLASS ccust omer DEFI NI TI ON.
PUBLI C SECTI ON.
*- - I nst ance_count er can be changed by met hods of t hi s
*- - cl ass and f r omout si de t he cl ass
CLASS- DATA: i nst ance_count er TYPE i .
ENDCLASS.
REPORT sapbc411d_f l i ght .
CLASS ccust omer DEFI NI TI ON.
PUBLI C SECTI ON.
*- - I nst ance_count er can be changed by met hods of t hi s
*- - cl ass and f r omout si de t he cl ass
CLASS- DATA: i nst ance_count er TYPE i .
ENDCLASS.


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 cl ass,
you can access it using cl ass=>in programs in which the class class is declared. Once the class has
been instantiated into an object obj , you can use the normal object reference obj - >f to access the
class attribute.




(C) SAP AG BC411 6-15
SAP AG
R
References: Reference Variables
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
Main memory
Reference semantics
oflight _1 _1
oflight _2 _2
Reference variable
Reference variable


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 var i abl es ( of l i ght _1 and
of l i ght _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 <cl ass>for this purpose.
One of the advantages of the reference semantics is that the system does not have to copy object
components and methods when you assign one object/reference variable to another. Instead, it
merely copies the address of the new object.
Object references allow you to work with dynamic data structures such as detail lists, trees, graphs,
and so on without having to 'hammer out' their data structure to fit it into a table.
Object attributes can themselves contain reference variables.


(C) SAP AG BC411 6-16
SAP AG
R
References: Creating Objects
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght _1.
CREATE OBJ ECT of l i ght _2.
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght _1.
CREATE OBJ ECT of l i ght _2.
oflight_1 oflight_1
Main memory
oflight_2 oflight_2
Reference semantics
Reference variable Reference variable
Reference variable Reference variable
C_FLIGHT<1>
C_FLIGHT<2>


Once you have created a reference variable with reference to the class c_f l i ght , you can create
an instance of the class (an object) using the statement CREATE OBJ ECT <cr ef >. The reference
variable <cr ef >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
OBJ ECT statement creates a new object whose identity is defined by its unique object reference.
In the above diagram, instances are displayed as rounded rectangles. The above notation for
instances corresponds to the contents of the reference variables as displayed in the ABAP Debugger.


(C) SAP AG BC411 6-17
SAP AG
R
References: Assigning References
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght _1.
CREATE OBJ ECT of l i ght _2.
of l i ght _2 = of l i ght _1
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght _1.
CREATE OBJ ECT of l i ght _2.
of l i ght _2 = of l i ght _1
oflight_1 oflight_1
Main memory
oflight_2 oflight_2
Reference semantics
Reference variable Reference variable
Reference variable Reference variable
C_FLIGHT<1>
C_FLIGHT<2>


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 of l i ght _2 = of l i ght _1, both of the class references of l i ght _1 and
of l i ght _2 must have the same type, that is, they must both refer to the same class, or the class of
of l i ght _1 must be the predefined empty class OBJ ECT.
The class OBJ ECT 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 OBJ ECT can serve as
containers for passing references. However, you cannot use them to access objects.


(C) SAP AG BC411 6-18
SAP AG
R
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght _1.
CREATE OBJ ECT of l i ght _2.
of l i ght _2 = of l i ght _1
DATA: of l i ght _1 TYPE REF TO c_f l i ght ,
of l i ght _2 TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght _1.
CREATE OBJ ECT of l i ght _2.
of l i ght _2 = of l i ght _1
References: Garbage Collection
Main memory
oflight_1 oflight_1
oflight_2 oflight_2
Reference semantics
Reference variable Reference variable
Reference variable Reference variable
C_FLIGHT<1>
C_FLIGHT<2>
Garbage collection


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


(C) SAP AG BC411 6-19
SAP AG
R
Classes and Instances: Example
REPORT sapbc411d_f l i ght .
TYPES: t passenger ( 20) .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book . . .
PRI VATE SECTI ON.
DATA: passenger _l i st TYPE STANDARD TABLE OF t passenger .
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD book.
MOVE . . .
APPEND . . .
ENDMETHOD.
ENDCLASS.
START- OF- SELECTI ON.
DATA: of l i ght TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght .
REPORT sapbc411d_f l i ght .
TYPES: t passenger ( 20) .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book . . .
PRI VATE SECTI ON.
DATA: passenger _l i st TYPE STANDARD TABLE OF t passenger .
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD book.
MOVE . . .
APPEND . . .
ENDMETHOD.
ENDCLASS.
START- OF- SELECTI ON.
DATA: of l i ght TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght .


You define object references in the DATA or TYPES statement using the form
<r ef . var i abl e> TYPE REF TO <cl ass name>.
The CREATE OBJ ECT statement creates objects dynamically. The program requests main memory
space from the system to enable it to store the attributes and methods of the new object. The
reference to the object is stored in the reference variable.


(C) SAP AG BC411 6-20
SAP AG
R
Declaring Methods
METHODS <met h>
I MPORTI NG . . VALUE( <i >) | <i > TYPE t ype [ OPTI ONAL]
. .
EXPORTI NG . . VALUE( <e>) | <e> TYPE t ype [ OPTI ONAL] . .
CHANGI NG . . VALUE( <c>) | <c> TYPE t ype [ OPTI ONAL]
. . RETURNI NG VALUE( <r >)
EXCEPTI ONS . . <exc> . .
METHODS <met h>
I MPORTI NG . . VALUE( <i >) | <i > TYPE t ype [ OPTI ONAL]
. .
EXPORTI NG . . VALUE( <e>) | <e> TYPE t ype [ OPTI ONAL] . .
CHANGI NG . . VALUE( <c>) | <c> TYPE t ype [ OPTI ONAL]
. . RETURNI NG VALUE( <r >)
EXCEPTI ONS . . <exc> . .
REPORT sapbc411d_.
TYPES: t passenger ( 20) .
TABLES: sf l i ght .
DATA: begi n of wa, . . .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book I MPORTI NG passenger TYPE t passenger
car r i d LI KE sf l i ght - car r i d,
conni d LI KE sf l i ght - conni d,
f l dat e LI KE sf l i ght - f l dat e.
REPORT sapbc411d_.
TYPES: t passenger ( 20) .
TABLES: sf l i ght .
DATA: begi n of wa, . . .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book I MPORTI NG passenger TYPE t passenger
car r i d LI KE sf l i ght - car r i d,
conni d LI KE sf l i ght - conni d,
f l dat e LI KE sf l i ght - f l dat e.


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 I MPORTI NG,
EXPORTI NG, 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 (OPTI ONAL, 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 (RETURNI NG 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 (EXCEPTI ONS),
allowing the user to react to errors that occur during the method.



(C) SAP AG BC411 6-21
SAP AG
R
Implementing Methods
METHOD <met h>.
. . . I mpl ement at i on . . .
ENDMETHOD.
METHOD <met h>.
. . . I mpl ement at i on . . .
ENDMETHOD.
REPORT sapbc411d_ .
TYPES: t passenger ( 20) .
TABLES: sf l i ght .
DATA: begi n of wa, . . .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book I MPORTI NG passenger TYPE t passenger
car r i d LI KE sf l i ght - car r i d,
conni d LI KE sf l i ght - conni d,
f l dat e LI KE sf l i ght - f l dat e.
PRI VATE SECTI ON.
DATA: passenger _l i st TYPE STANDARD TABLE OF wa.
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD book.
MOVE car r i d TO wa- car r i d, . . .
APPEND wa TO passenger _l i st .
ENDMETHOD.
ENDCLASS.
REPORT sapbc411d_ .
TYPES: t passenger ( 20) .
TABLES: sf l i ght .
DATA: begi n of wa, . . .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book I MPORTI NG passenger TYPE t passenger
car r i d LI KE sf l i ght - car r i d,
conni d LI KE sf l i ght - conni d,
f l dat e LI KE sf l i ght - f l dat e.
PRI VATE SECTI ON.
DATA: passenger _l i st TYPE STANDARD TABLE OF wa.
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD book.
MOVE car r i d TO wa- car r i d, . . .
APPEND wa TO passenger _l i st .
ENDMETHOD.
ENDCLASS.


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


(C) SAP AG BC411 6-22
SAP AG
R
Calling Methods
CALL METHOD <met hod> EXPORTI NG <f or mal _e> = <act ual _e>
I MPORTI NG <f or mal _i > = <act ual _i >
CHANGI NG <f or mal _c> = <act ual _c>
RECEI VI NG r = h
EXCEPTI ONS <exc_i > = r c_i .
CALL METHOD <met hod> EXPORTI NG <f or mal _e> = <act ual _e>
I MPORTI NG <f or mal _i > = <act ual _i >
CHANGI NG <f or mal _c> = <act ual _c>
RECEI VI NG r = h
EXCEPTI ONS <exc_i > = r c_i .
REPORT sapbc411d_f l i ght .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book I MPORTI NG . . .
PRI VATE SECTI ON. . . .
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD book.
. . .
ENDMETHOD.
ENDCLASS.
DATA: of l i ght TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght .
CALL METHOD of l i ght - >book EXPORTI NG passenger = ' Pet er Mi l l er '
car r i d = ' LH'
conni d = ' 0400'
f l dat e = ' 19980202' .
REPORT sapbc411d_f l i ght .
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: book I MPORTI NG . . .
PRI VATE SECTI ON. . . .
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD book.
. . .
ENDMETHOD.
ENDCLASS.
DATA: of l i ght TYPE REF TO c_f l i ght .
CREATE OBJ ECT of l i ght .
CALL METHOD of l i ght - >book EXPORTI NG passenger = ' Pet er Mi l l er '
car r i d = ' LH'
conni d = ' 0400'
f l dat e = ' 19980202' .


You call methods using the above statement. The exact way in which you address the method
<met hod>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 <met hod>.
CALL METHOD <met hod> 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 <r ef >- ><met hod>where <r ef >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 <cl ass>=><met hod>where <cl ass>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:
<f or mal par amet er > = <act ual par amet er >following the corresponding addition.


(C) SAP AG BC411 6-23
SAP AG
R
Constructor
Classes can define a constructor, which is automatically called at the
CREATE OBJ ECT statement.
The name is always CONSTRUCTOR (reserved name).
The constructor can only have IMPORTING parameters.
CLASS c DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS CONSTRUCTOR
[ I MPORTI NG VALUE( ar g1) TYPE t ype ] .
ENDCLASS.
CLASS c DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS CONSTRUCTOR
[ I MPORTI NG VALUE( ar g1) TYPE t ype ] .
ENDCLASS.
PROGRAM .
DATA o1 TYPE REF TO
CREATE OBJ ECT o1 EXPORTI NG ar g1 = v1 ar g1 = v2.
PROGRAM .
DATA o1 TYPE REF TO
CREATE OBJ ECT o1 EXPORTI NG ar g1 = v1 ar g1 = v2.


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 OBJ ECT <obj >statement (see also the online documentation for the CREATE
statement).


(C) SAP AG BC411 6-24
SAP AG
R
Booking Booking_ _Mgr
Flight Hotel Rental Car
IBook
Interfaces
Interfaces define the interaction between objects
Polymorphism is independent of classes and
inheritance
Classes can implement more than one interface
Interface references provide uniform access


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 (I book) allows you to extend the classes flight, hotel, and
rental car, and implement the booking procedure in each of the different classes by addressing the
same interface.



(C) SAP AG BC411 6-25
SAP AG
R
Interfaces: Model
All users
Class c1
Private
components
a2,
m2,
e2
Method
implementation
Subclasses of c1
Protected components
a3, m3, e3,
Public
components
CLASS c1 DEFI NI TI ON.
PUBLI C SECTI ON.
I NTERFACES i 1
DATA a1
PROTECTED SECTI ON.
PRI VATE SECTI ON.
ENDCLASS.
CLASS c1 I MPLEMENTATI ON.
METHOD i 1~m1. ENDMETHOD.
ENDCLASS.
I NTERFACE i 1.
DATA: a1. . . .
METHOD: m1. . . .
ENDI NTERFACE.
i 1~a1.
i 1~m1.
a1, . . .


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
i 1~m1.
The right-hand side shows the structure of the class with the components in their respective visibility
sections, and the implementation of the methods. The interface components extend the public
components of the class. All users can address both the class-specific public components and the
interface components.


(C) SAP AG BC411 6-26
SAP AG
R
Defining Interfaces
I NTERFACE i _r eser vat i on.
METHODS: book I MPORTI NG passenger TYPE t passenger ,
cancel I MPORTI NG passenger TYPE t passenger
ENDI NTERFACE.
I NTERFACE i _r eser vat i on.
METHODS: book I MPORTI NG passenger TYPE t passenger ,
cancel I MPORTI NG passenger TYPE t passenger
ENDI NTERFACE.
I NTERFACE <i nt er f ace>.
. . . ( Def i ni t i on of i nt er f ace component s) . . .
ENDI NTERFACE.
I NTERFACE <i nt er f ace>.
. . . ( Def i ni t i on of i nt er f ace component s) . . .
ENDI NTERFACE.


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 <i nt er f ace>is always enclosed in the statements
I NTERFACE <i nt er f ace> ENDI NTERFACE. Interfaces are abstract descriptions of
attributes sharead by different classes. They contain the same components as classes (attributes,
method definitions, events, constants), but do not have an implementation part. Instead, interface
methods are implemented by the class that implements the interface.
The components of interfaces do not have to be explicitly assigned to a visibility section, since the
interface itself is assigned to a visibiltiy section of the class that implements it, and all of its
components automatically assume the same visibility.
Interfaces allow you to implement abstract functions. In the above example, the methods 'book' and
'cancel' could appear in both the classes 'flight' and 'hotel'. However, the actual implementation is
different in each class. While you need to know the departure city, arrival city, and flight time to
book or cancel a flight, you need the duration of a guest's stay to book or cancel a hotel room.
Interfaces allow you to define common components of different classes in one place. Classes that
implement interfaces must implement all of their methods.
The question now remains as to how interfaces are linked to objects. This is explained on the next
page.




(C) SAP AG BC411 6-27
SAP AG
R
Implementing Interfaces
METHOD <i nt er f ace~i met hod>.
. . . ( Met hod i mpl ement at i on) . . .
ENDI NTERFACE.
METHOD <i nt er f ace~i met hod>.
. . . ( Met hod i mpl ement at i on) . . .
ENDI NTERFACE.
I NTERFACE i _r eser vat i on.
METHODS: book I MPORTI NG passenger TYPE t passenger ,
cancel I MPORTI NG passenger TYPE t passenger
ENDI NTERFACE.
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
I NTERFACES: i _r eser vat i on.
. . .
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD i _r eser vat i on~book.
( Booki ng code speci f i c t o t hi s cl ass)
ENDMETHOD.
ENDCLASS.
I NTERFACE i _r eser vat i on.
METHODS: book I MPORTI NG passenger TYPE t passenger ,
cancel I MPORTI NG passenger TYPE t passenger
ENDI NTERFACE.
CLASS c_f l i ght DEFI NI TI ON.
PUBLI C SECTI ON.
I NTERFACES: i _r eser vat i on.
. . .
ENDCLASS.
CLASS c_f l i ght I MPLEMENTATI ON.
METHOD i _r eser vat i on~book.
( Booki ng code speci f i c t o t hi s cl ass)
ENDMETHOD.
ENDCLASS.


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 <i nt er f acemet hod~i met h>
ENDMETHOD for each interface method <i nt er f acemet hod>.



(C) SAP AG BC411 6-28
SAP AG
R
I NTERFACE i _r eser vat i on.
METHODS: book . . .
cancel . . .
ENDI NTERFACE.
. . . Kl assendef i ni t i on und - i mpl ement at i on . . .
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
START- OF- SELECTI ON.
DATA: i r es TYPE REF TO i _r eser vat i on.
DATA: of l i ght TYPE REF TO c_f l i ght ,
ohot el TYPE REF TO c_hot el .
CREATE OBJ ECT: of l i ght , ohot el .
i r es = of l i ght .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Ml l er '
i r es = ohot el .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Ml l er ' .
I NTERFACE i _r eser vat i on.
METHODS: book . . .
cancel . . .
ENDI NTERFACE.
. . . Kl assendef i ni t i on und - i mpl ement at i on . . .
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
START- OF- SELECTI ON.
DATA: i r es TYPE REF TO i _r eser vat i on.
DATA: of l i ght TYPE REF TO c_f l i ght ,
ohot el TYPE REF TO c_hot el .
CREATE OBJ ECT: of l i ght , ohot el .
i r es = of l i ght .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Ml l er '
i r es = ohot el .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Ml l er ' .
Generic Programming Using Interface
References


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 <i r ef >, a user can address all of the visible interface components
<i comp>of the obejct to which the reference is pointing using the form <i r ef >- <i comp>. 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 i r es = oflight means that ires now points to the same object as the
class reference in of l i ght . 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 i r es- >book. Similarly, you
can access an attribute defined in an interface using <i r ef _var i abl e>- ><at t r >.
Note: You can book both a flight and a hotel room by calling the method 'book'. The actual method
that is called depends on the target of the interface reference. You can thus program generically by
'redirecting' the reference variable.


(C) SAP AG BC411 6-29
SAP AG
R
Interfaces - Example
I NTERFACE i _r eser vat i on.
METHODS: book I MPORTI NG passenger TYPE t passenger ,
cancel I MPORTI NG passenger TYPE t passenger .
ENDI NTERFACE.
I NTERFACE i _r eser vat i on.
METHODS: book I MPORTI NG passenger TYPE t passenger ,
cancel I MPORTI NG passenger TYPE t passenger .
ENDI NTERFACE.
CLASS c_f l i ght DEFI NI TI ON.
. . .
I NTERFACES: i _r eser vat i on.
ENDCLASS.
CLASS cl ass_f l i ght I MPLEMENTATI ON.
. . .
METHOD i _r eser vat i on~book.
. . .
ENDMETHOD.
METHOD i _r eser vat i on~cancel .
. . .
ENDMETHOD.
ENDCLASS.
CLASS c_f l i ght DEFI NI TI ON.
. . .
I NTERFACES: i _r eser vat i on.
ENDCLASS.
CLASS cl ass_f l i ght I MPLEMENTATI ON.
. . .
METHOD i _r eser vat i on~book.
. . .
ENDMETHOD.
METHOD i _r eser vat i on~cancel .
. . .
ENDMETHOD.
ENDCLASS.
START- OF- SELECTI ON.
DATA: i r es TYPE REF TO i _r eser vat i on.
DATA: of l i ght TYPE REF TO c_f l i ght , ohot el TYPE REF TO c_hot el .
CREATE OBJ ECT: of l i ght , ohot el .
i r es = of l i ght .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Mi l l er ' .
i r es = ohot el .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Mi l l er ' .
START- OF- SELECTI ON.
DATA: i r es TYPE REF TO i _r eser vat i on.
DATA: of l i ght TYPE REF TO c_f l i ght , ohot el TYPE REF TO c_hot el .
CREATE OBJ ECT: of l i ght , ohot el .
i r es = of l i ght .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Mi l l er ' .
i r es = ohot el .
CALL METHOD i r es- >book EXPORTI NG passenger = ' Mi l l er ' .
CLASS c_hot el DEFI NI TI ON.
. . .
I NTERFACES: i _r eser vat i on.
ENDCLASS.
CLASS cl ass_hot el I MPLEMENTATI ON.
. . .
METHOD i _r eser vat i on~book.
. . .
ENDMETHOD.
METHOD i _r eser vat i on~cancel .
. . .
ENDMETHOD.
ENDCLASS.
CLASS c_hot el DEFI NI TI ON.
. . .
I NTERFACES: i _r eser vat i on.
ENDCLASS.
CLASS cl ass_hot el I MPLEMENTATI ON.
. . .
METHOD i _r eser vat i on~book.
. . .
ENDMETHOD.
METHOD i _r eser vat i on~cancel .
. . .
ENDMETHOD.
ENDCLASS.


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


(C) SAP AG BC411 6-30
SAP AG
R
Business pl ane
Business pl ane
Events
Controller
Controller
Passenger
Passenger
Pilot
Pilot
LH Munich
I F al t i t ude = 0.
RAI SE EVENT t ouch_Down.
ENDI F.
Mr Smith
Landed=1 Landed=1
Pilot Miller
Relax! Relax!
Mrs J ones
Applause! Applause!


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 J ones applauds.
Unlike 'normal' methods, where the caller controls the procedure and knows the method that has
been called, an object that triggers an event does not know who will handle it.



(C) SAP AG BC411 6-31
SAP AG
R
Events
Trigger
CLASS c1 DEFI NI TI ON.
PUBLI C SECTI ON.
EVENTS e1 EXPORTI NG VALUE ( p1)
TYPE i .
METHODS: m1.
PRI VATE SECTI ON.
DATA: a1 TYPE i .
ENDCLASS.
CLASS C1 I MPLEMENTATI ON.
METHOD m1.
a1 = . . .
RAI SE EVENT e1 EXPORTI NG p1 = a1
ENDMETHOD.
ENDCLASS.
CLASS c2 DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: m2 FOR EVENT e1 OF c1
I MPORTI NG p1.
PRI VATE SECTI ON.
DATA: a2 TYPE i .
ENDCLASS.
CLASS C1 I MPLEMENTATI ON.
METHOD m2.
a2 = p1.
. . .
ENDMETHOD.
ENDCLASS.
Handler


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




(C) SAP AG BC411 6-32
SAP AG
R
Defining Events
EVENTS name [ EXPORTI NG VALUE( ar g1) TYPE t ype ]
EVENTS name [ EXPORTI NG VALUE( ar g1) TYPE t ype ]
CLASS c_but t on DEFI NI TI ON.
PUBLI C SECTI ON.
EVENTS: e_cl i cked EXPORTI NG VALUE( doubl ecl i ck) TYPE I .
ENDCLASS.
CLASS c_but t on I MPLEMENTATI ON.
METHOD mouse_cl i ck.
RAI SE EVENT e_cl i cked EXPORTI NG doubl ecl i ck = 0.
ENDMETHOD.
ENDCLASS.
CLASS c_but t on DEFI NI TI ON.
PUBLI C SECTI ON.
EVENTS: e_cl i cked EXPORTI NG VALUE( doubl ecl i ck) TYPE I .
ENDCLASS.
CLASS c_but t on I MPLEMENTATI ON.
METHOD mouse_cl i ck.
RAI SE EVENT e_cl i cked EXPORTI NG doubl ecl i ck = 0.
ENDMETHOD.
ENDCLASS.


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 RAI SE 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 RAI SE EVENT statement. The interface of an event
handler methods contains a list of IMPORTING parameters with the same names as their
corresponding EXPORTING parameters. This is generated automatically from the interface of the
event.


(C) SAP AG BC411 6-33
SAP AG
R
Defining an Event Handler
METHODS name FOR EVENT e OF c| i
[ I MPORTI NG f or m_par ]
METHODS name FOR EVENT e OF c| i
[ I MPORTI NG f or m_par ]
CLASS c_wi ndow DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: okcl i cked FOR EVENT e_cl i cked OF c_but t on
I MPORTI NG doubl ecl i ck,
cancel cl i cked FOR EVENT e_cl i cked OF c_but t on
I MPORTI NG doubl ecl i ck,
ENDCLASS.
CLASS c_wi ndow DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: okcl i cked FOR EVENT e_cl i cked OF c_but t on
I MPORTI NG doubl ecl i ck,
cancel cl i cked FOR EVENT e_cl i cked OF c_but t on
I MPORTI NG doubl ecl i ck,
ENDCLASS.


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| i f > I MPORTI NG <f or m_par >
where <e>is an event declared in class <c>or interface <i f >.
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
RAI SE EVENT statement.
If a class declares an event handler method, it and its instances are, in principle, capable of handling
the event <e>that is triggered in an event.


(C) SAP AG BC411 6-34
SAP AG
R
Registering and Triggering Events
DATA: okbut t on TYPE REF TO c_but t on, " Obj ect t hat t r i gger s an event
cancel but t on TYPE REF TO c_but t on, " Obj ect t hat r eact s t o an event
h1, h2 TYPE REF TO c_wi ndow. " Obj ect t hat r eact s t o an event
CREATE OBJ ECT: okbut t on, cancel but t on, h1, h2.
SET HANDLER: h1- >okcl i cked FOR okbut t on, " Regi st er f or event
h2- >cancel cl i cked FOR cancel but t on.
CALL METHOD okbut t on- >mousecl i ck. " Tr i gger event
CALL METHOD cancel but t on- >mousecl i ck. " Tr i gger event
DATA: okbut t on TYPE REF TO c_but t on, " Obj ect t hat t r i gger s an event
cancel but t on TYPE REF TO c_but t on, " Obj ect t hat r eact s t o an event
h1, h2 TYPE REF TO c_wi ndow. " Obj ect t hat r eact s t o an event
CREATE OBJ ECT: okbut t on, cancel but t on, h1, h2.
SET HANDLER: h1- >okcl i cked FOR okbut t on, " Regi st er f or event
h2- >cancel cl i cked FOR cancel but t on.
CALL METHOD okbut t on- >mousecl i ck. " Tr i gger event
CALL METHOD cancel but t on- >mousecl i ck. " Tr i gger event
Registering a handler and triggering the event


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



(C) SAP AG BC411 6-35
SAP AG
R
Events: Handler Table
okbutton okbutton
Reference variable
Handler: h1
okclicked
h1 h1
Handler table
h1 okcl i cked
e1 ( Event )
Registered handling
object method
Sender:okbutton


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


(C) SAP AG BC411 6-36
SAP AG
R
Summary
In this unit, you have learned about
object-oriented programming with ABAP
Objects. Object orientation allows you to
create programs that are easier to
maintain and have a better structure.
ABAP Objects supports all of the
significant characteristics of object
orientation, such as encapsulation,
interfaces, and events.



(C) SAP AG BC411 6-37
SAP AG
R
Preview: Inheritance
Plane
Plane
Cargo plane
Cargo plane
Passenger plane
Passenger plane
Plane
Plane
name altitude
fuelMaximum fuelActual numberOfPilots
setName ascend refuel
Passenger plane
Passenger plane
name altitude
fuelMaximum fuelActual
numberOfPilots passengerMaximum
passengerActual
setName ascend refuel
loadPassenger loadBaggage
Cargo plane
Cargo plane
name altitude
fuelMaximum fuelActual
numberOfPilots loadMaximum loadActual
setName ascend refuel
loadCargo


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).


SAP AG
R
Contexts: Contents
Contexts
How to use contexts
Where to use contexts
Buffering contexts
Maintaining contexts



(C) SAP AG BC411 7-2
SAP AG
R
Unit Objectives
In this unit, you will learn
What a context is
Why you would want to use contexts
How contexts are buffered
How to use a context in an ABAP program
How to create and maintain contexts



(C) SAP AG BC411 7-3
SAP AG
R
What is a Context?
Little basic data Derived data:
Ex.:Table SGEOCITY
Ex.:Table SGEOCITY
City
Frankfurt
New York
Paris
Madrid
Country
D
USA
F
E
Value
5.00090E01
8.68000E01
6199.5164
Frankfurt Int.
Airport
LH0400,
AZ0788,
UA3504, ...
Derived by
Reading directly
Reading directly
Calculation
Reading another
table
...
Field
Latitude
Longitude
Distance
Airport
Flights
... ...
...


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


(C) SAP AG BC411 7-4
SAP AG
R
REPORT . . . .
* Cal cul at e geogr aphi cal di st ance
SELECT l ongi t ude l at i t ude FROM sgeoci t y
WHERE ci t y = ' FRANKFURT'
AND count r y = ' DE' .
pi = acos( - 1 ) .
x1 = l at i t ude1 * pi / 180.
y1 = l ongi t ude1 * pi / 180.
x2 = l at i t ude2 * pi / 180.
y2 = l ongi t ude1 * pi / 180.
yd = y2 - y1.
di st ance = 20000 / pi *
ACOS( SI N( x1 ) * SI N( x2 ) + COS( x1 )
* COS( x2 ) * COS( yd ) ) .
REPORT . . . .
* Cal cul at e geogr aphi cal di st ance
SELECT l ongi t ude l at i t ude FROM sgeoci t y
WHERE ci t y = ' FRANKFURT'
AND count r y = ' DE' .
pi = acos( - 1 ) .
x1 = l at i t ude1 * pi / 180.
y1 = l ongi t ude1 * pi / 180.
x2 = l at i t ude2 * pi / 180.
y2 = l ongi t ude1 * pi / 180.
yd = y2 - y1.
di st ance = 20000 / pi *
ACOS( SI N( x1 ) * SI N( x2 ) + COS( x1 )
* COS( x2 ) * COS( yd ) ) .
Set
buffer
Context buffer (main memory)
Read
buffer
REPORT yyy.
. . .
* Cal cul at e geogr aphi cal di st ance
REPORT zzz.
. . .
* Cal cul at e geogr aphi cal di st ance
REPORT xyx.
* Cal cul at e geogr aphi cal di st ance
Field Value Field Value
city Frankfurt city New York
country D country USA
latitude 5.0009E01 latitude
longitude 8.6800E01 longitude
distance (FRA-NY) 6199.5164
Using Contexts


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




(C) SAP AG BC411 7-5
SAP AG
R
Structure of a Context
Fields Modules
Function module
Function module
Context
Context
Table / View
Table / View


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



(C) SAP AG BC411 7-6
SAP AG
R
Testing Contexts
Context: DEMO_CITIES
Modules
Geogr. distance
Geogr. position of a city
Geogr. position of a city
Fields Values
CITY1
COUNTRY1
CITY2
COUNTRY2
LONGITUDE1
LATITUDE1
LONGITUDE2
LATITUDE2
DISTANCE
MX
ACAPULCO
Context: Testumgebung
Value unknown
Value calculable
Value known
Module inactive
Module can be activated
Module is active
Icon Meaning in fields Meaning in modules


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


(C) SAP AG BC411 7-7
SAP AG
R
Derivation Schema of a Context
Network graphic
COUNTRY1
CITY1
CITY2
COUNTRY2
LONG1/
LAT1
LONG2/
LAT2
Country 1
COUNTRY2
City 1
CITY1
City 2
CITY2
Country 2
COUNTRY1
Georgraphical pos.
SGEOCITY1
Geographical pos.
SGEOCITY2
Geographical pos.
DISTANCE


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


(C) SAP AG BC411 7-8
SAP AG
R
Reset every
hour on the
hour
Constant data
Distance 2303.7715
Longitude Latitude
7.070000E01 7.40000E01
New York USA
Frankfurt D
Distance 2303.7715
Longitude Latitude
5.00160E01 -8.566000E00
Buffering types
P Permanent
T Temporary
N No buffering
Buffering Contexts


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


(C) SAP AG BC411 7-9
SAP AG
R
Context Buffer and Context Instances
Presentation
Database
...
Roll area 1 Context buffer
Context
instance 1:
demo_travel_
instance
Roll area n
Application
Context
instance 2:
demo_travel_
instance
ABAP ABAP
DATA:
demo_t r avel _
i nst ance


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



(C) SAP AG BC411 7-10
SAP AG
R
CONTEXTS: <context>.
DATA: <instance> TYPE context_<context>.
REPORT xxx.
CONTEXTS: geogr _i nf or mat i on.
DATA: geogr _i nf or mat i on_i nst 1 TYPE cont ext _geogr _i nf or mat i on.
Creating a Context Instance


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
<cont ext >must exist in the Context Builder. The CONTEXTS statement implicitly creates a
special data type cont ext _<cont ext >. You can use this type in a DATA statement to create
context instances.
The system also creates a data type CONTEXT_T_<cont ext >- f for each field in the context. You
can use this data type to create corresponding fields. For an example, see the DEMAND statement.
You can work with several instances of the same context within a program.



(C) SAP AG BC411 7-11
SAP AG
R
Supplying a Context Instance with Key Values I
Presentation
Application
Database
Roll area 1 Context buffer
Context instance table
Entry Value Output fields
Frankfurt
New York
Cityfrom
Cityto
ABAP ABAP
SUPPLY


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.
I mportant note: The SUPPLY statement involves no database activity.




(C) SAP AG BC411 7-12
SAP AG
R
SUPPLY <key
1
> = <f
1
> . . . <key
n
> = <f
n
> TO CONTEXT <i nst ance>.
REPORT . . . .
CONTEXTS: geogr _i nf or mat i on.
DATA: geogr _i nf or mat i on_i nst 1 TYPE cont ext _geogr _i nf or mat i on.
SUPPLY ci t y = ' FRANKFURT'
count r y = ' DE'
ci t y_1 = ' NEWYORK'
count r y_1 = ' USA'
TO CONTEXT geogr _i nf or mat i on_i nst 1.
Supplying a Context Instance with Key Values II


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


(C) SAP AG BC411 7-13
SAP AG
R
Retrieving Data from a Context Instance I
Presentation
Database
3
Roll area Context buffer
Application
Entry Value Output fields
Frankfurt
New York
Cityfrom
Cityto
Context instance table
2
Frankfurt
New York
6193
Frankfurt
Athens
1794
DISTANCE
6193
1
ABAP ABAP
DEMAND


The following occurs in a DEMAND statement:

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

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

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

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


(C) SAP AG BC411 7-14
SAP AG
R
DEMAND: <val
1
> = <f
1
> . . . <val
n
> = <f
n
> FROM CONTEXT <i nst ance>
[ MESSAGES I NTO <i t ab>] .
REPORT sapbc411d_cont ext _geogr _i nf o.
CONTEXTS: geogr _i nf ox.
TYPES: cont ext _t yp TYPE cont ext _t _geogr _i nf ox.
DATA: ci t y_f r omTYPE cont ex_t yp- ci t y,
ci t y_t o TYPE cont ext _t yp- ci t y,
di st ance TYPE cont ext _t yp- di st ance.
DATA: geogr _i nf or mat i on_i nst TYPE cont ext _geogr _i nf or mat i on.
SUPPLY ci t y = ' FRANKFURT'
count r y = ' DE'
ci t y_1 = ' NEWYORK'
count r y_1 = ' US'
TO CONTEXT geogr _i nf or mat i on_i nst .
DEMAND ci t y = ci t y_f r om
ci t y_1 = ci t y_t o
di st ance = di st ance
FROM CONTEXT geogr _i nf or mat i on_i nst .
Wr i t e: / ci t y_f r om, ci t y_t o, di st ance.
Retrieving Data from a Context Instance II


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

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

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

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


(C) SAP AG BC411 7-15
SAP AG
R
REPORT sapbc411d_cont ext _geogr _di st an.
DATA: di st ance TYPE p.
. . .
CONTEXTS geogr _i nf or mat i on.
DATA: geogr _i nf or mat i on_i nst TYPE cont ext _geogr _i nf or mat i on.
SUPPLY ci t y = ' XX'
count r y = ' DE'
ci t y_1 = ' NEWYORK'
count r y_1 = ' USA'
TO CONTEXT geogr _i nf or mat i on_i nst .
DEMAND di st ance = di st ance
FROM CONTEXT geogr _i nf or mat i on_i nst .
WRI TE: di st ance.
E No entries found for key XX DE
Message Handling in Contexts: System
Message displayed by context by context


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 RAI SE.
Contexts as modules can always be traced back to tables or function modules.
If you want the system to be responsible for message handling, use the basic form of the DEMAND
statement without the MESSAGES addition.
For table modules, the system reacts as though there were a MESSAGE statement after the
DEMAND statement, containing the attributes (ID, number) specified for the module in the
Context Builder.
For function modules, the MESSAGE RAISING statement in the function module is
executed. If the function module only contains a RAISE statement, a runtime error occurs.



(C) SAP AG BC411 7-16
SAP AG
R
REPORT sapbc411d_cont ext _geogr _i nf o.
DATA: i t ab LI KE symsg OCCURS 0 WI TH HEADER LI NE.
CONTEXTS c_geogr _i nf or mat i on.
DATA: geogr _i nf or mat i on_i nst TYPE cont ext _c_geogr _i nf or mat i on.
DATA: di st ance TYPE cont ext _t _geogr _i nf or mat i on.
SUPPLY ci t y = ' XX'
count r y = ' DE'
ci t y1 = ' NEWYORK'
count r y1 = ' USA'
TO CONTEXT geogr _i nf or mat i on_i nst .
DEMAND di st ance = di st ance
FROM CONTEXT geogr _i nf or mat i on_i nst
MESSAGES I NTO i t ab.
WRI TE: / di st ance.
LOOP AT i t ab.
WRI TE: / i t ab- msgt y, i t ab- msgi d, i t ab- msgno,
i t ab- msgv1, i t ab- msgv2.
ENDLOOP
Message Handling in Contexts: Program
Messages displayed by system
E BCTRAIN 007 XX DE


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 SELECTI ON- SCREEN event for selection screens).
If there are messages in the message table following the DEMAND statement, SY- SUBRC is
unequal to 0.



(C) SAP AG BC411 7-17
SAP AG
R
REPORT . . . .
DATA: cont ext _name LI KE r s33f - f r mi d.
cont ext _name = ' DOCU_TEST1' .
. . .
CALL FUNCTI ON ' UPDATE_. . . ' I N UPDATE TASK
EXPORTI NG . . .
I MPORTI NG . . .
. . .
CALL FUNCTI ON ' CONTEXT_BUFFER_DELETE' I N UPDATE TASK
EXPORTI NG
cont ext _i d= cont ext _name
EXCEPTI ONS
OTHERS = 0.
. . .
COMMI T WORK.
Clearing the Context Buffer


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





(C) SAP AG BC411 7-18
SAP AG
R
Creating and Maintaining Contexts
Felder
Modules
Module SGEOCITY1
SGEOCITY- CITY
SGEOCITY- COUNTRY
SGEOCITY- CITY
SGEOCITY- COUNTRY
SGEOCITY- LONGITUDE
SGEOCITY- LATITUDE
SGEOCITY- LONGITUDE
SGEOCITY- LATITUDE
SPFLI-DISTANCE
CDEMOC
SGEOCITY
Geograp
CITY CITY1
COUNTRY1
City1
Ctry1
Long1
Lat1
Geograp
Fields
DISTANCE
SGEOCITY1
COUNTRY
LONGITUDE
LATITUDE
LATITUDE1
LONGITUDE1
Parameters I/O Field name Text
Name Type Table/mod. Text Name Reference field/type
CITY1
COUNTRY1
CITY2
COUNTRY2
LONGITUDE1
LATITUDE1
LONGITUDE2
LATITUDE2
Context: DEMO_CITIES
Context: DEMO_CITIES
DISTANCE
Geograp SGEOCITY SGEOCITY2


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




(C) SAP AG BC411 7-19
SAP AG
R
Summary I
In this unit you have learned that contexts are
ABAP Workbench objects that store the
relationships between data, but not the data itself.
You have learned that you can use contexts to:
Remove processing logic from application programs, in order
to
Reduce complexity
Make souce code reusable
Improve the performance of application programs thanks to
context buffering
You have learned how to create and maintain
contexts, and about the different buffering types
(permanent, temporary, none).



(C) SAP AG BC411 7-20
SAP AG
R
You have learned the statements used to declare
contexts in programs (CONTEXTS), to provide a
context instance with values (SUPPLY), and to
retrieve data from a context i nstance (DEMAND)
You know how messages are handled in contexts
You know how to create or maintain a context
Summary II


SAP AG
R
ABAP Open SQL: Inhalt
Performance of business transactions
R/3 and DBMS architecture
SQL
Efficient database programming in ABAP
ABAP Open SQL features
ABAP Open SQL programming rules



(C) SAP AG BC411 8-2
SAP AG
R
Unit Objectives
At the end of this unit, you will be able to
List the principal components of the R/3
System and DBMS architectures
Decide when it is appropriate to use Native
SQL
Understand and apply the most important
functions of ABAP Open SQL and the rules
for efficient database programming



(C) SAP AG BC411 8-3
SAP AG
R
SQL SQL
Business transaction Business transaction
performance performance
R/3 and DBMS architecture R/3 and DBMS architecture
Efficient ABAP Efficient ABAP
database programming database programming
ABAP Open SQL: Overview



(C) SAP AG BC411 8-4
SAP AG
R
General rule:
The performance of business transactions is
determined by their database access times.
database
application
GUI
Business Transaction Performance


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


(C) SAP AG BC411 8-5
SAP AG
R
SQL SQL
R/3 and DBMS architecture R/3 and DBMS architecture
Efficient ABAP Efficient ABAP
database programming database programming
ABAP Open SQL: Overview
Business transaction Business transaction
performance performance



(C) SAP AG BC411 8-6
SAP AG
R
R/3 Architecture
Central database
(saves all data and
application programs)
Application server
Communication
with user
Data transfer between database
and application server
Presentation server (workstation)
Database server
DBMS
processes
DB
cache
...
Local
data
WP


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



(C) SAP AG BC411 8-7
SAP AG
R
General DBMS Architecture
R/3 work process R/3 work process
DB work process DB work process
Operating system Operating system
Database files Database files
R/3 work process
DB work process
Network
communication
DB CPU
use
Database cache
Database
service
processes
DB memory
use
Physical I/O


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


(C) SAP AG BC411 8-8
SAP AG
R
The Optimizer
Rule based
Cost based
Execution plan


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



(C) SAP AG BC411 8-9
SAP AG
R
SQL SQL
R/3 and DBSM architecture R/3 and DBSM architecture
Efficient ABAP Efficient ABAP
database programming database programming
ABAP Open SQL: Overview
Business transaction Business transaction
performance performance



(C) SAP AG BC411 8-10
SAP AG
R
ABAP SQL
Open SQL Open Open SQL SQL
Native SQL Native Native SQL SQL
DB interface DB interface
Embedded Embedded SQL SQL
SQL SQL SQL
Database Database


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

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


(C) SAP AG BC411 8-11
SAP AG
R
From SQL Statement to Result Set
SELECT
clause
WHERE clause
FROM clause
Search area
Data to be transferred
Relevant data
- the search result -
One or more tables
Data to be searched - only
restricted when the
search uses an index
SELECT f i el d1 f i el d2 f i el d3 f i el d4
FROM ( t abl e I NNER J OI N t abl e ON
t abl e~f i el d1 = t abl e~f i el d1 )
WHERE . . . AND f i el d1 I N ( ' A' , ' B' , ' C' ) AND f i el d3 LI KE ' T%'


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


(C) SAP AG BC411 8-12
SAP AG
R
SQL SQL
R/3 and DBMS architecture R/3 and DBMS architecture
Efficient ABAP Efficient ABAP
database programming database programming
Efficient ABAP Database Programming
Business transaction Business transaction
performance performance



(C) SAP AG BC411 8-13
SAP AG
R
Fi ve Rules of Open SQL Programming
Five rules
DBMS-independent where possible



(C) SAP AG BC411 8-14
SAP AG
R
Basis for the Fi ve Rules
ORACLE
INFORMIX
ADABAS
DB2/400 (AS/400)
Microsoft SQL Server (MSS)
Not considered:
DB2/6000
DB2/MVS
ORACLE Parallel Server (OPS)


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


(C) SAP AG BC411 8-15
SAP AG
R
Rule 1
Keep the result set small


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



(C) SAP AG BC411 8-16
SAP AG
R
Exercise: Read all Flights for a Year
Turn to the Exercises appendix for a
description of the task



(C) SAP AG BC411 8-17
SAP AG
R
1. Keep the Result Set Small
Use a WHERE condition wherever possible
REPORT sapbc411s_f l i ght s_of _one_year
PARAMETERS: par am1( 4) .
DATA: BEGI N OF sear ch_st r i ng,
par am( 4) ,
r est val ue ' %' ,
END OF sear ch_st r i ng.
SELECT * FROM sf l i ght I NTO wa_sf l i ght .
CHECK sf l i ght - f l dat e( 4) = par am1.
WRI TE: / wa_sf l i ght - car r i d, wa_sf l i ght -
conni d, . . . ENDSELECT.
REPORT sapbc411s_f l i ght s_of _one_year
PARAMETERS: par am1( 4) .
DATA: BEGI N OF sear ch_st r i ng,
par am( 4) ,
r est val ue ' %' ,
END OF sear ch_st r i ng.
SELECT * FROM sf l i ght I NTO wa_sf l i ght .
CHECK sf l i ght - f l dat e( 4) = par am1.
WRI TE: / wa_sf l i ght - car r i d, wa_sf l i ght -
conni d, . . . ENDSELECT.
sear ch_st r i ng- par am= par am1.
SELECT * FROM sf l i ght I NTO wa_sf l i ght WHERE
f l dat e LI KE sear ch_st r i ng.
WRI TE: / wa_sf l i ght - car r i d, wa_sf l i ght -
conni d, . . .
ENDSELECT.
sear ch_st r i ng- par am= par am1.
SELECT * FROM sf l i ght I NTO wa_sf l i ght WHERE
f l dat e LI KE sear ch_st r i ng.
WRI TE: / wa_sf l i ght - car r i d, wa_sf l i ght -
conni d, . . .
ENDSELECT.
Instead, use
Performance difference:SELECT * ... CHECK. ENDSELECT. 300,000 ms (400 entries)
SELECT ... WHERE . 3,700 ms


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

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



(C) SAP AG BC411 8-18
SAP AG
R
Benefits of Rule 1
R/3 work process R/3 work process
DB work process DB work process
Operating system Operating system
Database files Database files
R/3 work process
DB work process
Network
communication
DB CPU
use
Database cache
Database
service
processes
DB memory
use
Physical I/O


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


(C) SAP AG BC411 8-19
SAP AG
R
Rule 2
Minimze the amount of data transferred
between the database and the application
server


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


(C) SAP AG BC411 8-20
SAP AG
R
Exercise: Reading the First 10 Flights
Turn to the Exercises appendix for a
description of the task



(C) SAP AG BC411 8-21
SAP AG
R
2. Minimize Data Transfer I
REPORT sapbc411d_r ead_10_f l i ght s.
SELECT car r i d conni d FROM sbook
WHERE car r i d = ' LH'
I NTO ( wa- car r i d, wa- conni d) .
I F sy- dbcnt > 10.
EXI T.
ENDI F.
WRI TE: / wa- car r i d, wa- conni d.
ENDSELECT.
REPORT sapbc411d_r ead_10_f l i ght s.
SELECT car r i d conni d FROM sbook
WHERE car r i d = ' LH'
I NTO ( wa- car r i d, wa- conni d) .
I F sy- dbcnt > 10.
EXI T.
ENDI F.
WRI TE: / wa- car r i d, wa- conni d.
ENDSELECT.
SELECT car r i d conni d FROM sbook I NTO wa
UP TO 10 ROWS WHERE car r i d = ' LH' .
WRI TE: / wa- car r i d, wa- conni d, . . .
ENDSELECT.
SELECT car r i d conni d FROM sbook I NTO wa
UP TO 10 ROWS WHERE car r i d = ' LH' .
WRI TE: / wa- car r i d, wa- conni d, . . .
ENDSELECT.
Performance difference: SELECT column... EXIT. ENDSELECT. 300,000 ms
SELECT column ... UP TO 10 ROWS. 34,000 ms
Use data selectively
Instead, use


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



(C) SAP AG BC411 8-22
SAP AG
R
2. Minimize Data Transfer
REPORT sapbc411d_sel ect _f i el dl i st .
TABLES: SBOOK.
SELECT * FROM sbook
WHERE car r i d ne ' BA' .
WRI TE: / wa- car r i d, wa- conni d
ENDSELECT.
REPORT sapbc411d_sel ect _f i el dl i st .
TABLES: SBOOK.
SELECT * FROM sbook
WHERE car r i d ne ' BA' .
WRI TE: / wa- car r i d, wa- conni d
ENDSELECT.
SELECT cust omi d cl ass FROM sbook
I NTO ( wa- car r i d, wa- conni d)
WHERE car r i d ne ' BA' .
WRI TE: / wa- cust omi d, wa- cl ass, . . .
ENDSELECT.
SELECT cust omi d cl ass FROM sbook
I NTO ( wa- car r i d, wa- conni d)
WHERE car r i d ne ' BA' .
WRI TE: / wa- cust omi d, wa- cl ass, . . .
ENDSELECT.
Performance difference: SELECT column... . ENDSELECT. 2.2 sec (21500 entries)
SELECT * ... ENDSELECT. 6.7 sec
Field list or SELECT * ?
Instead, use



(C) SAP AG BC411 8-23
SAP AG
R
Client/Server Architecture and ABAP Runtime I
SELECT * FROM SBOOK
Appl Appl . .
server server
Appl Appl . .
server server
Database Database
server server
REPORT XYZ
Data transfer from
DB server to appl. server
10000 SBOOK records of
97 bytes each require 30
transfers of 32K packets
from the database server
to the application server
Report result


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


(C) SAP AG BC411 8-24
SAP AG
R
Client/Server Architecture and ABAP Runtime II
SELECT COL1 FROM SBOOK
Appl. Appl.
server server
Appl. Appl.
server server
Database Database
server server
REPORT XYZ
Data transfer from DB
server to application server
10000 SBOOK entries of
97 bytes each requires 30
transfers of 32K packets
from the database server
to the application server
Report result


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 (CUSTOMI D) and flight class (CLASS), you only need to
transport 90,000 bytes (9 * 10,000), which only requires three packets. You thus save 27 packets of
32,000 bytes each (384,000 bytes) that no longer have to be transported.
Naturally, the real figures differ from those quoted here. The SQL Trace for this operation shows 22
and 4 transfers respectively. The difference is caused by the adminsitration information that also has
to be transported.
Note: The disadvantages of the SELECT list are that you cannot use it with generic functions, and
you have to adjust it if you change the definition of the table in the ABAP Dictionary.


(C) SAP AG BC411 8-25
SAP AG
R
2. Minimize Data Transfer II
Referencing table fields
Instead, use
Instead, use
REPORT sapbc411d_updat e_set .
DATA: wa_sf l i ght l i ke sf l i ght .
SELECT * I NTO wa_sf l i ght FROM sf l i ght
WHERE car r i d =' LH' .
wa_sf l i ght - seat socc = wa_sf l i ght - seat socc + 1.
UPDATE sf l i ght f r omwa_sf l i ght .
ENDSELECT.
REPORT sapbc411d_updat e_set .
DATA: wa_sf l i ght l i ke sf l i ght .
SELECT * I NTO wa_sf l i ght FROM sf l i ght
WHERE car r i d =' LH' .
wa_sf l i ght - seat socc = wa_sf l i ght - seat socc + 1.
UPDATE sf l i ght f r omwa_sf l i ght .
ENDSELECT.
REPORT sapbc411d_updat e_set .
UPDATE sf l i ght SET seat socc = seat socc + 1
WHERE car r i d = ' LH' .
REPORT sapbc411d_updat e_set .
UPDATE sf l i ght SET seat socc = seat socc + 1
WHERE car r i d = ' LH' .
Performance difference: SELECT * ... ENDSELECT. 500,000 ms (100 entries)
UPDATE ... SET ... 56,700 ms


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:
f i el d = val ue
f i el d = f i el d + val ue
f i el d = f i el d - val ue
where value is an ABAP field or a field from the same row of the database table.
You can only use the last two variants with numeric fields.



(C) SAP AG BC411 8-26
SAP AG
R
Exercise: Summation
Turn to the Exercises appendix for a
description of the task



(C) SAP AG BC411 8-27
SAP AG
R
COUNT, SUM, MAX, MIN, AVG
Use aggregate functions
REPORT sapbc411d_cumul at e_l occur am.
. . .
SUM = 0.
SELECT l occur amFROM sbook i nt o wa_sbook
WHERE f l dat e l i ke ' 1998%' .
SUM = SUM + wa_sbook- l occur am.
ENDSELECT.
WRI TE: / sum.
REPORT sapbc411d_cumul at e_l occur am.
. . .
SUM = 0.
SELECT l occur amFROM sbook i nt o wa_sbook
WHERE f l dat e l i ke ' 1998%' .
SUM = SUM + wa_sbook- l occur am.
ENDSELECT.
WRI TE: / sum.
Instead, use
Instead, use
SELECT sum( l occur am) I NTO ( sum) FROM sbook
WHERE f l dat e LI KE ' 1998%' .
WRI TE: / sum.
SELECT sum( l occur am) I NTO ( sum) FROM sbook
WHERE f l dat e LI KE ' 1998%' .
WRI TE: / sum.
Performance difference: SELECT ... sum = sum + ... ENDSELECT. 3.6 sec (21500 entries)
SELECT sum ( price ) INTO 1.1 sec
2. Minimize Data Transfer 4


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



(C) SAP AG BC411 8-28
SAP AG
R
2. Minimize Data Transfer 5
Database may approximate differently from the ABAP
runtime system
Databases use null values, ABAP does not
AVG (1, 3, 0, 0) =1
AVG (1, 3, null, null) =2
Use the correct data type for the target field
Use type 'F' (floating point) for the AVG function
For the SUM function, use a data type that can store numbers large
enough to avoid an arithmetic overflow
Aggregate functions III - Differences


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



(C) SAP AG BC411 8-29
SAP AG
R
Benefits of Rule 2
R/3 work process R/3 work process
DB work process DB work process
Operating system Operating system
Database files Database files
R/3 work process
DB work process
Network
communication
DB CPU
use
Database cache
Database
service
processes
DB memory
use
Physical I/O


The benefit of observing rule 2 is that:
Only the data required by the application is transferred over the network from the database to the
application server.


(C) SAP AG BC411 8-30
SAP AG
R
Rule 3
Minimize the number of
transfers between database
and application


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


(C) SAP AG BC411 8-31
SAP AG
R
3. Minimize the Number of Transfers 1
Use array operations - INSERT
REPORT . . .
LOOP AT i t ab.
I NSERT I NTO dbt ab VALUES i t ab.
ENDLOOP.
REPORT . . .
LOOP AT i t ab.
I NSERT I NTO dbt ab VALUES i t ab.
ENDLOOP.
REPORT . . .
I NSERT dbt ab FROM TABLE i t ab
ACCEPTI NG DUPLI CATE KEYS.
I F sy- subr c = 4.
. . . Er r or handl i ng . . .
ENDI F.
REPORT . . .
I NSERT dbt ab FROM TABLE i t ab
ACCEPTI NG DUPLI CATE KEYS.
I F sy- subr c = 4.
. . . Er r or handl i ng . . .
ENDI F.
Instead, use
Instead, use


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



(C) SAP AG BC411 8-32
SAP AG
R
Exercise: Reading from More than One Table
Turn to the Exercises appendix for a
description of the task



(C) SAP AG BC411 8-33
SAP AG
R
3. Minimize the Number of Transfers 2
Joins implemented as
views in the ABAP Dictionary
Joins in ABAP Open SQL
SELECT * FROM t1 WHERE ...
SELECT * FROM t2 WHERE ...
SELECT * FROM t3 WHERE ...
SELECT * FROM t4 WHERE ...
SELECT * FROM t5 WHERE ...
...
ENDSELECT.
ENDSELECT.
ENDSELECT.
SELECT * FROM t6 WHERE ...
SELECT * FROM t7 WHERE ...
SELECT * FROM t8 WHERE ...
...
ENDSELECT.
ENDSELECT.
ENDSELECT.
ENDSELECT.
ENDSELECT.
Use joins


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



(C) SAP AG BC411 8-34
SAP AG
R
3. Minimize the Number of Transfers 3
ABAP Dictionary view
REPORT sapbc411d_sel ect _vi ew.
SELECT * FROM sf l i ght .
WRI TE: / sf l i ght - car r i d, . . .
SELECT * FROM sbook WHERE car r i d = sf l i ght - car r i d
AND conni d = sf l i ght - conni d
AND f l dat e = sf l i ght - f l dat e.
I F SY_SUBRC NE 0.
WRI TE: sbook- booki d, . . .
ENDI F.
ENDSELECT.
ENDSELECT.
REPORT sapbc411d_sel ect _vi ew.
SELECT * FROM sf l i ght .
WRI TE: / sf l i ght - car r i d, . . .
SELECT * FROM sbook WHERE car r i d = sf l i ght - car r i d
AND conni d = sf l i ght - conni d
AND f l dat e = sf l i ght - f l dat e.
I F SY_SUBRC NE 0.
WRI TE: sbook- booki d, . . .
ENDI F.
ENDSELECT.
ENDSELECT.
SELECT * FROM sf l i ght sbookvi ew.
*Vi ew i n ABAP Di ct i onar y
WRI TE: / sf l i ght sbookvi ew- pr i ce,
sf l i ght sbookvi ew- payment sum, . . .
ENDSELECT.
SELECT * FROM sf l i ght sbookvi ew.
*Vi ew i n ABAP Di ct i onar y
WRI TE: / sf l i ght sbookvi ew- pr i ce,
sf l i ght sbookvi ew- payment sum, . . .
ENDSELECT.
Instead, use


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



(C) SAP AG BC411 8-35
SAP AG
R
REPORT sapbc411d_sel ect _vi ew.
SELECT f ~car r i d f ~conni d . . . I NTO ( sf l i ght - car r i d, . . . )
FROM sf l i ght AS f I NNER J OI N sbook AS b
ON f ~car r i d = b~car r i d
AND f ~conni d = b~conni d
AND f ~f l dat e = b~f l dat e.
WRI TE: / sf l i ght - pr i ce, sf l i ght - payment sum, . . .
ENDSELECT.
REPORT sapbc411d_sel ect _vi ew.
SELECT f ~car r i d f ~conni d . . . I NTO ( sf l i ght - car r i d, . . . )
FROM sf l i ght AS f I NNER J OI N sbook AS b
ON f ~car r i d = b~car r i d
AND f ~conni d = b~conni d
AND f ~f l dat e = b~f l dat e.
WRI TE: / sf l i ght - pr i ce, sf l i ght - payment sum, . . .
ENDSELECT.
Inner join in the FROM clause
SELECT <f i el dl i st > I NTO <t ar get >
FROM <dbt ab1> [ AS <al i as1>]
I NNER J OI N <dbt ab2> [ AS <al i as2>]
ON <al i as1>~<dbt ab1- f i el d1> = <al i as2>~<dbt ab2- f i el d1>
AND <al i as1>~<dbt ab1- f i el d2> = <al i as2>~<dbt ab2- f i el d2>
AND . . .
WHERE . . .
. . .
ENDSELECT.
3. Minimize the Number of Transfers 4


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



(C) SAP AG BC411 8-36
SAP AG
R
Inner join
AA
LH
LH
QF
...
SFLIGHT:
CARRID CONNID ... DISTANCE CARRID CONNID ... DISTANCE
SBOOK:
CARRID CONNID ... BOOKID CARRID CONNID ... BOOKID
Join condition
AA 0017 2,572 AA 0017 1
AA 0017 2,572 AA 0017 2
AA 0017 2,572 AA ... ... ...
Join result table in the database Join result table in the database
CARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID
QF 0598 1,689 QF 0598 10
00170
40004
02
0598
...
2,572
6,658
3,162
1,689
...
AA
AA
AA
QF
...
00170
017
...
0598
...
1
2
...
10
...
3. Minimize the Number of Transfers 5
Note:
The result set contains
no entries for airline
LH.


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 J OIN for pool or cluster tables.
Inner joins always bypass the table buffer and read directly from the database. For this reason, it is
better to use a view from the ABAP Dictionary when accessing tables that are mostly only read.



(C) SAP AG BC411 8-37
SAP AG
R
3. Minimize the Number of Transfers 6
Left outer join in the FROM clause
REPORT sapbc411d_sel ect _vi ew.
. . .
SELECT f ~car r i d f ~conni d . . . I NTO ( sf l i ght - car r i d, . . . )
FROM sf l i ght AS f LEFT OUTER J OI N sbook AS b
ON f ~car r i d = b~car r i d
AND f ~conni d = b~conni d
AND f ~f l dat e = b~f l dat e
WHERE f ~f l dat e = ' 19981119' .
WRI TE: / sf l i ght - pr i ce, sf l i ght - payment sum, . . .
ENDSELECT.
REPORT sapbc411d_sel ect _vi ew.
. . .
SELECT f ~car r i d f ~conni d . . . I NTO ( sf l i ght - car r i d, . . . )
FROM sf l i ght AS f LEFT OUTER J OI N sbook AS b
ON f ~car r i d = b~car r i d
AND f ~conni d = b~conni d
AND f ~f l dat e = b~f l dat e
WHERE f ~f l dat e = ' 19981119' .
WRI TE: / sf l i ght - pr i ce, sf l i ght - payment sum, . . .
ENDSELECT.
SELECT <f 1>. . . <f n> I NTO <wa>
FROM <dbt ab1> [ AS <al i as1>]
LEFT [ OUTER] J OI N <dbt ab2> [ AS <al i as2>]
ON <al i as1>~<dbt ab1- f i el d1> = <al i as2>~<dbt ab2- f i el d1>
AND <al i as1>~<dbt ab1- f i el d2> = <al i as2>~<dbt ab2- f i el d2>
AND . . .
WHERE . . .
. . . "Do somet hi ng
ENDSELECT.


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



(C) SAP AG BC411 8-38
SAP AG
R
AA
LH
LH
QF
...
SFLIGHT: SFLIGHT:
CARRID CONNID ... DISTANCE CARRID CONNID ... DISTANCE
SBOOK: SBOOK:
CARRID CONNID ... BOOKID CARRID CONNID ... BOOKID
Join condition
AA 0017 ... 2,572 AA 0017 ... 1
AA 0017 ... 2,572 AA 0017 ... 2
AA 0017 ... 2,572 AA ... ... ...
Join result table in the database Join result table in the database
CARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID
LH 0400 ... 6,658 NULL NULL ... NULL
00170
40004
02
0598
...
2,572
6,658
3,162
1,689
...
AA
AA
AA
QF
...
00170
017
...
0598
...
1
2
...
10
...
Left outer join
3. Minimize the Number of Transfers 7
Note:
The result set
always contains
the entire outer
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.


(C) SAP AG BC411 8-39
SAP AG
R
Exercise: Reading Maximum and Minimum Values
Turn to the Exercises appendix for a
description of the task



(C) SAP AG BC411 8-40
SAP AG
R
SELECT car r i d conni d f l dat e seat socc
I NTO ( f - car r i d, f - conni d, f - f l dat e, f - seat socc)
FROM sf l i ght AS f
WHERE seat socc I N
( SELECT MAX( seat socc ) FROM sf l i ght
WHERE car r i d = f ~car r i d AND CONNI D = f ~conni d
ORDER BY car r i d conni d f l dat e. )
WRI TE: sf l i ght - car r i d, sf l i ght - conni d, . . .
ENDSELECT.
SELECT car r i d conni d f l dat e seat socc
I NTO ( f - car r i d, f - conni d, f - f l dat e, f - seat socc)
FROM sf l i ght AS f
WHERE seat socc I N
( SELECT MAX( seat socc ) FROM sf l i ght
WHERE car r i d = f ~car r i d AND CONNI D = f ~conni d
ORDER BY car r i d conni d f l dat e. )
WRI TE: sf l i ght - car r i d, sf l i ght - conni d, . . .
ENDSELECT.
REPORT sapbc411s_sel ect _subquer y.
DATA: f LI KE sf l i ght , f 1 LI KE sf l i ght .
SELECT car r i d conni d f l dat e max( seat socc ) FROM sf l i ght
I NTO ( f - car r i d, f - conni d, f - f l dat e, f - seat socc)
GROUP BY by car r i d conni d
ORDER BY car r i d conni d.
SELECT car r i d conni d f l dat e FROM sf l i ght
I NTO ( f 1- car r i d, f 1- conni d, f 1- f l dat e)
WHERE car r i d = f - car r i d
AND conni d = f - conni d
AND seat socc = f - seat socc.
WRI TE: / f 1- car r i d, f 1- conni d, f 1- f l dat e, f - seat socc.
ENDSELECT.
ENDSELECT.
REPORT sapbc411s_sel ect _subquer y.
DATA: f LI KE sf l i ght , f 1 LI KE sf l i ght .
SELECT car r i d conni d f l dat e max( seat socc ) FROM sf l i ght
I NTO ( f - car r i d, f - conni d, f - f l dat e, f - seat socc)
GROUP BY by car r i d conni d
ORDER BY car r i d conni d.
SELECT car r i d conni d f l dat e FROM sf l i ght
I NTO ( f 1- car r i d, f 1- conni d, f 1- f l dat e)
WHERE car r i d = f - car r i d
AND conni d = f - conni d
AND seat socc = f - seat socc.
WRI TE: / f 1- car r i d, f 1- conni d, f 1- f l dat e, f - seat socc.
ENDSELECT.
ENDSELECT.
Subquery in the WHERE clause
3. Minimize the Number of Transfers 8


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 f i el d]. A dynamic WHERE
condition or dynamic specification of the table name are not supported in Release 4.0B.



(C) SAP AG BC411 8-41
SAP AG
R
Exercise: Reading Grouped Data with
Conditions
Turn to the Exercises appendix for a
description of the task



(C) SAP AG BC411 8-42
SAP AG
R
3. Minimize the Number of Transfers 9
Having Clause
SELECT conni d f l dat e count ( *) AVG( l uggwei ght )
I NTO ( conni d, f l dat e, avg) FROM sbook
WHERE car r i d = ' LH' AND f l dat e > ' 19981201'
GROUP BY conni d f l dat e
HAVI NG AVG( l uggwei ght ) > 20.
. . .
ENDSELECT.
REPORT sapbc411s_sel ect _havi ng.
SELECT conni d f l dat e count ( *) AVG( l uggwei ght )
I NTO ( conni d, f l dat e, count , avg) FROM sbook
GROUP BY conni d f l dat e WHERE car r i d = ' LH'
AND f l dat e > ' 19981201'
CHECK avg > 20.
. . .
ENDSELECT.


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



(C) SAP AG BC411 8-43
SAP AG
R
Benefits of Rule 3
R/3 work process R/3 work process
DB work process DB work process
Operating system Operating system
Database files Database files
R/3 work process
DB work process
Network
communication
DB CPU
use
Database cache
Database
service
processes
DB memory
use
Physical I/O


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


(C) SAP AG BC411 8-44
SAP AG
R
Rule 4
Minimize the search overhead



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


(C) SAP AG BC411 8-45
SAP AG
R
Tabelle Index A
Block 2
Block 3
Block 1
Satz 4
Satz 2
Satz 5
Satz 1
Satz 6
Satz 7
Satz 3
Index B
4. Minimize the Search Overhead 1
Tables and Indexes


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

The following terms are important when considering runtime:
Full table scan - The database reads every database entry to check which need to be selected.
Index range scan - The database only checks a part of the index.
Index unique scan - The database reads a single entry using the index.



(C) SAP AG BC411 8-46
SAP AG
R
4. Minimize the Search Overhead 2
SELECT * FROM sbook
WHERE car r i d = ' AA'
AND conni d = ' 0017'
AND f l dat e = ' 19981205' .
. . . Pr ocessi ng. . .
ENDSELECT.
SELECT * FROM sbook
WHERE car r i d = ' AA'
AND conni d = ' 0017'
AND f l dat e = ' 19981205' .
. . . Pr ocessi ng. . .
ENDSELECT.
General rule I
Use the 'EQ' operator as much as possible


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



(C) SAP AG BC411 8-47
SAP AG
R
4. Minimize the Search Overhead 3
REPORT sapbc411d_sel ect _many_eq.
SELECT car r i d conni d f l dat e booki d
cust t ype or der dat e FROM sbook
i nt o . . .
WHERE car r i d = ' LH'
AND f l dat e = ' 19981119'
AND or der dat e = ' 19981118' .
. . . Pr ocessi ng . . .
ENDSELECT.
REPORT sapbc411d_sel ect _many_eq.
SELECT car r i d conni d f l dat e booki d
cust t ype or der dat e FROM sbook
i nt o . . .
WHERE car r i d = ' LH'
AND f l dat e = ' 19981119'
AND or der dat e = ' 19981118' .
. . . Pr ocessi ng . . .
ENDSELECT.
SELECT f ~car r i d f ~conni d f ~f l dat e b~booki d
b~cust t ype b~or der dat e I NTO ( car r i d, conni d,
f l dat e, booki d, cust t ype) FROM sf l i ght AS f
I NNER J OI N sbook as b
ON f ~car r i d = b~car r i d
AND f ~conni d = b~conni d
AND f ~f l dat e = b~f l dat e
WHERE f ~car r i d = ' LH'
AND f l dat e = ' 19981119' AND or der dat e = ' 19981118' .
. . . Pr ocessi ng . . .
ENDSELECT.
SELECT f ~car r i d f ~conni d f ~f l dat e b~booki d
b~cust t ype b~or der dat e I NTO ( car r i d, conni d,
f l dat e, booki d, cust t ype) FROM sf l i ght AS f
I NNER J OI N sbook as b
ON f ~car r i d = b~car r i d
AND f ~conni d = b~conni d
AND f ~f l dat e = b~f l dat e
WHERE f ~car r i d = ' LH'
AND f l dat e = ' 19981119' AND or der dat e = ' 19981118' .
. . . Pr ocessi ng . . .
ENDSELECT.
SBOOK key:
mandt
carrid
connid
fldate
bookid
Use 'EQ' as often as possible


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


(C) SAP AG BC411 8-48
SAP AG
R
4. Minimize the Search Overhead 4
1 2 3 4
Key of table
SBOOK
Primary
index
Mand Mand Carrid Carrid Connid Connid Fldate Fldate
Mand Mand Carrid Carrid Connid Connid Fldate Fldate
Secondary
index
Carrid Carrid Fldate Fldate Orderdate Orderdate


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, CARRI D, and FLDATE in the WHERE condition, a primary index search will only
use the fields MANDT and CARRI D, since you have not specified the field CONNI D.
If, on the other hand, you have created a secondary index with the above structure, a cost-based
optimizer would use it, recognizing that the ORDERDATE field is far more selective.


(C) SAP AG BC411 8-49
SAP AG
R
4. Minimize the Search Overhead 5
f 0 = x1 AND ( f 1 = y1 OR
f 1 = y2 OR
f 1 = y3) .
f 0 = x1 AND ( f 1 = y1 OR
f 1 = y2 OR
f 1 = y3) .
Replace inner OR with an IN expression
f 0 = x1 AND f 1 I N ( y1, y2, y3) .
f 0 = x1 AND f 1 I N ( y1, y2, y3) .
General rule II


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


(C) SAP AG BC411 8-50
SAP AG
R
4. Minimize the Search Overhead 6
Selective fields at the beginning
non-selective: MANDT, BUKRS
very selective: BUCHUNGSNUMMER, BELNR, MATNR, KUNNR,
Small indexes
Avoid overlap (Disjunctive indexes)
Up to 3 indexes per table is OK
Avoid complex WHERE conditions with IN or OR
conditions for index fields
NOT conditions in the SELECT statement cannot be
processed using the index
Check how the system uses your indexes
Index design


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


(C) SAP AG BC411 8-51
SAP AG
R
4. Minimize the Search Overhead 7
Application
server
Database
server
Cursor cache
Data block
buffer
AA0017 NewYork San
AA0064 San Francisco
LH0400 Frankfurt New
Shared SQL
Pool
SELECT C1 FROM SPFLI
SELECT C3 FROM SBOOK
SELECT C2 FROM LIPS
SELECT * FROM MARA
Oracle: global
memory area
Second
access
AA0017 New York San Fran
AA0064 San Francisco New
LH0400 Frankfurt New York
Cursor cache
First
access


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


(C) SAP AG BC411 8-52
SAP AG
R
4. Minimize the Search Overhead 8
DB memory
use
DB CPU
use
R/3 work process R/3 work process
DB work process DB work process
Operating system Operating system
Database files Database files
R/3 work process
DB work process
Network
Communication
Database cache
Database
service
processes
Physical I/O


The benefits of observing rule 4 are that:
You cause fewer I/O operations in the database
You minimize the memory used in the database
You minimize the CPU use of the database


(C) SAP AG BC411 8-53
SAP AG
R
Rule 5
Reduce the
database load


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


(C) SAP AG BC411 8-54
SAP AG
R
5. Reduce the Database Load 1
Buffer tables
Avoid reading data repetitively
Check for SELECT before changes
ORDER BY vs. SORT
Logical databases
==> improves Scalability


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


(C) SAP AG BC411 8-55
SAP AG
R
What is table buffering?
When should you buffer tables?
What must you bear in mind when programming SQL
access to buffered tables?
- ABAP Open SQL & table buffering
5. Reduce the Database Load 2



(C) SAP AG BC411 8-56
SAP AG
R
Appl.
server
Database
server
SELECT col1 .......... FROM T001
PROGRAM XYZ
RESULT
Table buffer
2
1
3
4
5
Read data from
database if it is
not already in the
table buffer
Table buffering - concept
5. Reduce the Database Load 3
Data transfer from
database server to
application server and
table buffer


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

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


(C) SAP AG BC411 8-57
SAP AG
R
Why buffer tables?
Appl.
server
Database
server
SELECT SINGLE col1 .. FROM T001
PROGRAM XYZ
Table buffer
8 8 - - 600 ms 600 ms
0.2 0.2 - - 1 ms 1 ms
5. Reduce the Database Load 4


Buffering tables considerably reduces the time required to access data.
Example: It takes 8 - 600 milliseconds to read a single entry of table T001 from the database. By
contrast, it takes between 0.2 and 1 millisecond to read the same entry from the table buffer.


(C) SAP AG BC411 8-58
SAP AG
R
key1 key2 key3 Daten
key1 key2 key3 Daten
key1 key2 key3 Daten
key1 key2 key3 Daten
Resident buffering
(100%)
Generic buffering
1 key field
Generic buffering
2 key fields
Partial buffering
(single entry)
001
001
001
001
002
002
002
002
002
002
003
003
003
003
003
003
003
003
001
001
001
001
002
002
002
002
002
002
002
002
003
003
003
003
003
003
003
003
003
003
003
001
001
001
001
001
002
002
002
002
002
002
002
002
002
002
003
003
003
003
003
003
003
003
003
003
003
003
003
A
A
B
B
A
A
B
B
B
C
D
C
A
A
A
B
B
C
C
C
D
D
D
A
A
B
B
B
A
A
A
A
B
B
B
C
D
C
A
A
A
B
B
C
C
C
C
D
D
D
D
4
2
3
1
5
1
3
6
8
1
2
3
0
5
3
2
3
6
2
4
2
3
5
8
1
2
3
4
Buffering types
5. Reduce the Database Load 5


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



(C) SAP AG BC411 8-59
SAP AG
R
Application server A
Communication system
Database management system
Database is
up to date
Local buffer is
up to date
...
DDLOG
UPDATE T001...
Database
R/3 DB interface
Table buffer
Buffer Synchronization I
5. Reduce the Database Load 6


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



(C) SAP AG BC411 8-60
SAP AG
R
5. Reduce the Database Load 7
Synchronizing the buffer II
Application server A
Table buffer
Communication system
Database management system
Applciation server B
Buffer is
NOT
up-to-date
Database is
up-to-date
Local buffer is
up-to-date
...
DDLOG
UPDATE T001...
Database
Table buffer
R/3 DB interface
DDLOG
INSERT DDLOG INSERT DDLOG


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


(C) SAP AG BC411 8-61
SAP AG
R
Application server A Application server B
Buffer
invalid
Database is
up-to-date
Local buffer is
up-to-date
...
SELECT DDLOG SELECT DDLOG
Buffer synchronized
every 1-2 minutes
R/3 DB interface R/3 DB interface
5. Reduce the Database Load 8
Synchronizing the buffer III
Table buffer
Table buffer
DDLOG
Database DDLOG
Database management system
Communication system


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



(C) SAP AG BC411 8-62
SAP AG
R
key1 key2 key3 Data
key1 key2 key3 Data
key1 key2 key3 DAta
key1 key2 key3 Data
Resident buffering
(100%)
Generic buffering
1 key field
Generic buffering
2 key fields
Partial buffering
(single entry)
001
001
001
001
002
002
002
002
002
002
003
003
003
003
003
003
003
003
001
001
001
001
002
002
002
002
002
002
002
001
001
001
001
001
002
002
002
002
002
002
002
002
002
When is the buffer invalid?
All changes
invalidate the buffer
Changes invalidate
the corresponding
generic area
Changes using a
work area invalidate
the individual entry.
Other changes
invalidate the
entire table.
5. Reduce the Database Load 9
A
A
B
B
A
A
B
B
B
C
C


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 dbt ab. ').


(C) SAP AG BC411 8-63
SAP AG
R
When should you buffer tables?
You should buffer a table if
You frequently read from it
It is relatively small
(few entries, or few, short columns)
You mostly only read from it
You rarely change it (a few times a day or month)
Candidates for buffering
Control and Customizing tables
'Small' master data tables
(100 material master records ->few changes)
5. Reduce the Database Load 10


The most important question to address is: Can a table be buffered?
The answer is yes if you process the table mostly in read-only mode, it is relatively small, and if it is
not critical when the data is not updated immediately on all application servers. This is a logical, not
a technical decision.



(C) SAP AG BC411 8-64
SAP AG
R
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)
5. Reduce the Database Load 11


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



(C) SAP AG BC411 8-65
SAP AG
R
SQL statements that bypass the buffer
SELECT ... BYPASSING BUFFER
SELECT ... DISTINCT
SELECT ... COUNT, SUM, AVG, MIN, MAX
SELECT ... ORDER BY f1 ... fn
SELECT ... GROUP BY / HAVING
SELECT ... FOR UPDATE
SELECT ... JOIN
WHERE cl ause with IS NULL expression
WHERE cl ause with subquery
Native SQL statements (EXEC SQL. ... ENDEXEC)
5. Reduce the Database Load 12


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


(C) SAP AG BC411 8-66
SAP AG
R
5. Reduce the Database Load 13
Avoid repeatedly reading data
It causes unnecessary database load
It may produce different results each time
Reading data repetitively


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


(C) SAP AG BC411 8-67
SAP AG
R
5. Reduce the Database Load 14
ORDER BY
... Does not necessarily mean that a certain index will be used in the
database
Often causes a large database overhead
Do you really need the data in a particular order?
ORDER BY or SORT?


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



(C) SAP AG BC411 8-68
SAP AG
R
5. Reduce the Database Load 15
Predefined, optimized database access
Simplified list creation
Centrally optimized
But: Use the 'correct' logical database!
Logical databases


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


(C) SAP AG BC411 8-69
SAP AG
R
5. Reduce the Database Load 16
DB memory
use
DB CPU
use
R/3 work process R/3 work process
DB work process DB work process
Operating system Operating system
Database files Database files
R/3 work process
DB work process
Network
communication
Database cache
Database
service
processes
Physical I/O


The benefits of observing rule 5 are that you:
Cause fewer I/O operations in the database
Minimize the memory use in the database
Minimize the CPU use in the database
Reduce the network communication
The consequence of all of this is that the database load is reduced .





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



(C) SAP AG BC411 8-71
SAP AG
R
ABAP Tuning Checklist - II
Does the program contain SELECT statements without
a WHERE clause for tables that grow constantly
(BSEG, MKPF, VBAK) ?
Program design is wrong
Are SELECT statements for master data buffered?
Does the program use SELECT APPEND ITAB
ENDSELECT to fill internal tables
Change the program to fill the internal table using SELECT INTO
TABLE.
Does the program use SELECT ORDER BY
statements?
Unless there is a suitable index with the same fields as the order by
clause, read the data into an internal table and sort it there.



(C) SAP AG BC411 8-72
SAP AG
R
ABAP Tuning Checklist - III
Does the program contain calculations?
Examine whether you can transfer calculations using aggregate
functions (MIN, MAX, SUM, AVG, COUNT) in the database.



(C) SAP AG BC411 8-73
SAP AG
R
Summary I
In this unit, you have learned the five
rules for more efficient database
programming.
Rule 1
Keep the result set small
Rule 2
Minimize the amount of data
transferred
Rule 3
Minimize the number of data
transfers



(C) SAP AG BC411 8-74
SAP AG
R
Rule 4
Minimize the search
overhead
Rule 5
Reduce the database load
Summary II



(C) SAP AG BC411 8-75
SAP AG
R
By observing these rules, you can
minimize the following:
The network communication between the
database and application server
The memory use on the database server
The CPU use on the database server
The number of physical accesses to database
files.
Summary III


SAP AG
R
Exceptions and Message Handling: Contents
Defining exceptions in function modules and methods
Exception handling



(C) SAP AG BC411 9-2
SAP AG
R
Unit Objectives
Trigger exceptions in function modules and
methods
Catch exceptions in ABAP programs
At the end of this unit, you will be able to



(C) SAP AG BC411 9-3
SAP AG
R
Exceptions
Exceptions
PLANE_OVERLOAD
Z_FREESEAT
.
.
.
I F SEATSOCC > SEATSMAX.
* RAI SE pl ane_over l oad.
MESSAGE . . . RAI SI NG
pl ane_over l oad.
ENDI F.
Call
Function module/method
.
.
.
CALL FUNCTI ON / CALL METHOD
EXPORTI NG . . .
I MPORTI NG . . .
EXCEPTI ONS . . .
Pl ane_over l oad = 01 01
er r or _message = 02 02
ot her s = 03 03 .
CASE sy sy- - subr c subr c.
WHEN 1.
.
.
.
ENDCASE.


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 RAI SI NG the system displays the
message and does not trigger a runtime error.
You can address the general exception ERROR_MESSAGE for any function module or method call.
This is the exception that is triggered when an error message occurs in the function module or
method; it catches all E and A type messages (in batch input programs, these errors are logged), but
ignores I, W, and S messages. You can use the OTHERS exception to catch any exceptions that you
have not specifically queried.



(C) SAP AG BC411 9-4
SAP AG
R
Catching Runtime Errors
REPORT sapbc411d_cat ch.
DATA: char ( 5) TYPE c VALUE ' 12A34' , pack TYPE p.
CATCH SYSTEM- EXCEPTI ONS conver si on_er r or s = 5 ot her s = 6.
pack = char .
ENDCATCH.
I F sy- subr c = 5.
WRI TE ' Conver si on er r or ' .
ELSEI F sy- subr c = 6.
WRI TE ' Ot her cat chabl e r unt i me er r or ' .
ENDI F.
CATCH SYSTEM- EXCEPTI ONS <excpt 1> = <r c1> . . . <excpt n> = <r cn>.
. . .
ENDCATCH.


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 (I F, 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 <r cn>, assigned to the system exception <excpt n>is placed in the system field
SY-SUBRC. If there is more than one expression <excpt n>=<r cn>, the <r cn>of the first
expression is returned. This is particularly important if you specify two different ERROR classes
that contain the same runtime error.
CATCH ENDCATCH may occur anywhere where IF . ENDIF may also occur, that is, it may
not span more than one event block.



(C) SAP AG BC411 9-5
SAP AG
R
CATCH SYSTEM- EXCEPTI ONS = <r c>.
. . .
ENDCATCH.
<excpt >
System Exceptions
Error class Error class
Individual Individual
runtime error runtime error
OTHERS OTHERS
ar i t hmet i c_er r or s
conver si on_er r or s
...
bcd_zer o_di vi de
convt _t o_number
...
All catchable runtime
errors


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



(C) SAP AG BC411 9-6
SAP AG
R
Nested CATCH ENDCATCH Structures
CATCH SYSTEM- EXCEPTI ONS
comput e_i nt _zer odi vi de = 1
ar i t hmet i c_er r or s = 2.
.
.
CATCH SYSTEM- EXCEPTI ONS
f i l e_access_er r or s = 5.
.
DO 10 TI MES.
COMPUTE i = 1 / 0.
ENDDO.
.
ENDCATCH.
.
.
ENDCATCH.
Sets
sy-subrc
Continues
processing


You can nest CATCHENDCATCH structures to any depth. If a system exception occurs within a
CATCHENDCATCH blocks, the system jumps to the ENDCATCH statement.
In the above example, the exception ar i t hmet i c_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 ar i t hmet i c_errors exists in the outer block. The
system therefore carries on processing at the ENDCATCH statement of the outer block.


(C) SAP AG BC411 9-7
SAP AG
R
Summary
You can trigger exceptions in function modules and
methods using RAISE <excpt> or
MESSAGE RAISING <excpt>. The first variant
leads to a runtime error if the calling program does
not handle the exception.
You can also catch system exceptions and
exceptions of function modules and methods
globall y and handle them usi ng CATCH
ENDCATCH blocks.


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



(C) SAP AG BC411 10-2
SAP AG
R
Unit Objectives
At the end of this unit, you will be able to
Explain how the memory model works
Explain parameter passing techniques
Identify how data is visible within different
modularization units
Compare the different modularization
techniques



(C) SAP AG BC411 10-3
SAP AG
R
Modularization Units
Task
structuring
Task
structuring
Internal subroutine Internal subroutine
External subroutine External subroutine
Function module Function module
Method Method
Screen (CALL SCREEN) Screen (CALL SCREEN)
Module Module
Event Event
List (LEAVE TO LIST PROCESSING) List (LEAVE TO LIST PROCESSING)
Selection screen (CALL SELECTION SCREEN) Selection screen (CALL SELECTION SCREEN)
Transaction Transaction
Report (SUBMIT) Report (SUBMIT)
Dialog module (obsolete) Dialog module (obsolete)
Context Context
Source code
structuring
Source code
structuring
Macro Macro
Include program Include program


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


(C) SAP AG BC411 10-4
SAP AG
R
Memory Areas: Logical Model I
R/3 R/3 instance 1 instance 1
R/3 database
R
/
3

i
n
s
t
a
n
c
e

n
R
/
3

i
n
s
t
a
n
c
e

n
System areas System areas
User 1
User 2 User n ...
Lock table
SAP System


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



(C) SAP AG BC411 10-5
SAP AG
R
Memory Areas: Logical Model II
U
s
e
r

1
:

R
/
3

t
e
r
m
i
n
a
l

s
e
s
s
i
o
n

n
U
s
e
r

1
:

R
/
3

t
e
r
m
i
n
a
l

s
e
s
s
i
o
n

n
System areas System areas
User 1: R/3 terminal session 1 User 1: R/3 terminal session 1
External session 1
Program 1
A
B
A
P

m
e
m
o
r
y
Program 2
Internal session 1
Internal session n
External session n
Program 1
A
B
A
P

m
e
m
o
r
y
Program 2
Internal session 1
Internal session n
...
1 1
2 2
2 2
SAP Memory (SET /GET parameters)


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 FUNCTI ON DESTI NATI ON).
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 TRANSACTI ON, CALL DI ALOG, and SUBMIT creates a new
internal session. For example, if you enter /nSE38 in your first window, the system executes the
statement CALL TRANSACTION ' SE38' , and generates an internal session.
You can use SAP memory and ABAP memory to pass data between programs.
SAP memory is a user-specific memory area for storing field values. Its contents are retained for the
duration of your terminal session, and can be used in all sessions. All external sessions can access
SAP memory. It is therefore not so useful for passing data between internal sessions.
For further information about ABAP memory, refer to the Data clusters appendix.


(C) SAP AG BC411 10-6
SAP AG
R
Visibility Area of a Program
U
s
e
r

1
:

R
/
3

s
e
s
s
i
o
n

n
System areas System areas
User 1: R/3 session 1
External session 1
Program 1
A
B
A
P

m
e
m
o
r
y
Internal session 1
External
session n
...
Lock table Lock table
R/3 Database R/3 Database
SAP memory
Visibility
area of the
program


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



(C) SAP AG BC411 10-7
SAP AG
R
Internal Session
System area System area
Program <pgm>
Ext. subroutine 1
Current list system Current list system
Roll area
Ext. subroutine 2
Function group 1/
class definition
Ext. subroutine 1
Ext. subroutine 2
Function group n/
class definition
Ext. subroutine 1
Ext. subroutine 2
Main program
group
Additional
program group 1
Additional
program group 2
1
1
CALL FUNCTION / CALL METHOD
1
Internal session


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 FUNCTI ON) 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 f or m(pr og) or PERFORM form IN
PROGRAM prog), the corresponding program (if it has not already been loaded) is loaded into the
same program group as the calling program. If, on the other hand, the subroutine is in a function
group or class definition that has not yet been loaded, the system creates a new program group as it
would in a CALL FUNCTION or CALL METHOD statement.


(C) SAP AG BC411 10-8
SAP AG
R
Table Work Areas / Common Parts
Common part C1 Common part C1
Main program
PROGRAM /
FUNCTION POOL
Table work area Table work area
Roll area
Additional program 1
<prog>
Additional program 2
<prog>
Program group
Common part C2 Common part C2


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


(C) SAP AG BC411 10-9
SAP AG
R
The Dangers of Working with Common Data
Areas, Call Hierarchies I
. . .
TABLES: SPFLI .
PERFORM
TEST01( PROG2) .
CALL FUNCTI ON
' TEST_FB'
. . .
CALL METHOD o1- >m1
. . .
TABLES: SPFLI .
PERFORM
TEST01( PROG2) .
CALL FUNCTI ON
' TEST_FB'
. . .
CALL METHOD o1- >m1
PROG1
ABAP
. . .
TABLES: SPFLI .
FORM TEST01.
CALL SCREEN 0100.
ENDFORM.
. . .
TABLES: SPFLI .
FORM TEST01.
CALL SCREEN 0100.
ENDFORM.
PROG2
ABAP
. . .
TABLES: SPFLI .
FUNCTI ON TEST_FB.
PERFORM
TEST01( PROG2) .
ENDFUNCTI ON.
CLASS I MPLEMENTATI ON.
METHOD: m1 . . .
ENDMETHOD.
ENDCLASS.
. . .
TABLES: SPFLI .
FUNCTI ON TEST_FB.
PERFORM
TEST01( PROG2) .
ENDFUNCTI ON.
CLASS I MPLEMENTATI ON.
METHOD: m1 . . .
ENDMETHOD.
ENDCLASS.
ABAP
SPFLI
PROG1_0100
1 1 1
2 2 2
SPFLI SPFLI SPFLI SPFLI
F Group/ Class


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



(C) SAP AG BC411 10-10
SAP AG
R
The Dangers of Working with Common Data
Areas, Call Hierarchies II
. . .
TABLES: SPFLI .
CALL FUNCTI ON
' TEST_FB'
.
.
PERFORM
TEST01( PROG2) .
. . .
TABLES: SPFLI .
CALL FUNCTI ON
' TEST_FB'
.
.
PERFORM
TEST01( PROG2) .
PROG1
ABAP
. . .
TABLES: SPFLI .
FORM TEST01.
CALL SCREEN 0100.
ENDFORM.
. . .
TABLES: SPFLI .
FORM TEST01.
CALL SCREEN 0100.
ENDFORM.
PROG2
ABAP
. . .
TABLES: SPFLI .
FUNCTI ON TEST_FB.
PERFORM
TEST01( PROG2) .
ENDFUNCTI ON.
. . .
TABLES: SPFLI .
FUNCTI ON TEST_FB.
PERFORM
TEST01( PROG2) .
ENDFUNCTI ON.
ABAP
SPFLI
FGROUP_0100
1 1 1
SPFLI SPFLI SPFLI SPFLI
.
.
.
F group / Class
2 2 2


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


(C) SAP AG BC411 10-11
SAP AG
R
Subroutines, Function Modules, and Methods
Each
has an
explicit
interface
Task
structuring
Task
structuring
Internal subroutine Internal subroutine
External subroutine External subroutine
Function module Function module
Method Method


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


(C) SAP AG BC411 10-12
SAP AG
R
Calling a Function Module, Method,
or External Subroutine
External session 1 -> Window 1
External session 1 -> Window 1
SAP Memory (User-specific, not session-specific)
SAP Memory (User-specific, not session-specific)
Internal session 1
Main program
of TA/program
Function Function
group 1 group 1
External
PERFORM 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
Internal session 2
Main program
of called
TA/program
Function Function
group 1 group 1
Function
group 3
Function
group 2
CALL
METHOD 1


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 TRANSACTI ON, for example), the system creates
new global data for function group 1. This means that the global data for function modules called in
the second session is different to that used by function modules in the first internal session.
The system behaves in the same way if an external subroutine or a method of an instance is called in
a further internal session. The system always creates new global data in the new session.


(C) SAP AG BC411 10-13
SAP AG
R
PROGRAM / REPORT / FUNCTION POOL / CLASS POOL
PROGRAM / REPORT / FUNCTION POOL / CLASS POOL
Local data
Statements
Global data
Read
USING
VALUE
CHANG.
VALUE
USING
CHANGING TABLES
Main
program
Inter-
face
Subroutine
Write
Interfaces in Subroutines


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
st at i cs.
The STATICS statement allows you to declare data within a procedure (f or m, function modul e, or
met hod) 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 f or ms, function modul es,
and met hods.
You can create a local copy of a global field or table work area using the GLOBAL statement. When
you leave the subroutine, the system restores the old values of the LOCAL objects.


(C) SAP AG BC411 10-14
SAP AG
R
Methods for Passing Parameters
Form in subroutine (FORM)
Form in subroutine (FORM)
By value
USING VALUE
CHANGING VALUE
By reference
USING/TABLES
CHANGING/TABLES
Read
Write
Form in calling program (PERFORM)
Form in calling program (PERFORM)
By value
USING
CHANGING
By reference
USING/TABLES
CHANGING/TABLES
Read
Write
Cost No parameters 1
One parameter 1.3
1.7
2.1
Two parameters 1.5
2.3
2.9
Three parameters 1.7
2.9
3.7
Cost No parameters 1
One parameter 1.3
1.7
2.1
Two parameters 1.5
2.3
2.9
Three parameters 1.7
2.9
3.7
1 1
2 2
3 3
1 1
2 2
3 3
1 1
2 2
3 3
1 1 By reference
2 2 By value
3 3 By value, returning value


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


(C) SAP AG BC411 10-15
SAP AG
R
FUNCTION POOL/ CLASS POOL
FUNCTION POOL/ CLASS POOL
Local data
Statements
Global data
IMPORTING EXPORTING TABLES CHANGING
Main program/
class definition
Interface
Function module/
method
EXCEP-
TIONS
Interfaces in Function Modules / Methods


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



(C) SAP AG BC411 10-16
SAP AG
R
Screens, Modules, and Events
Task
structuring
Task
structuring
Screen Screen
Module Module
Event Event


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


(C) SAP AG BC411 10-17
SAP AG
R
Interfaces of Screens, Modules, and Events
PROGRAM/FUNCTION POOL/CLASS POOL
PROGRAM/FUNCTION POOL/CLASS POOL
Flow logic
I/O fields
Global data
Statements
Statements
Module
Event
Screen
Same
names
No local
data


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 <t abl e>) are implemented internally as
subroutines. Data declarations within these events therefore only declare local fields.



(C) SAP AG BC411 10-18
SAP AG
R
Screen/List/Selection Screen
Screen Screen (CALL SCREEN) (CALL SCREEN)
List List (LEAVE TO LIST (LEAVE TO LIST- -PROCESSING) PROCESSING)
Sel. screen Sel. screen (CALL SELECTION (CALL SELECTION- -SCREEN) SCREEN)
Task
structuring
Task
structuring



(C) SAP AG BC411 10-19
SAP AG
R
CALL SCREEN
External session 1 -> Window 1
External session 1 -> Window 1
SAP Memory (User-specific, not
session-specific)
SAP Memory (User-specific, not
session-specific)
Internal session 1
A
B
A
P

M
e
m
o
r
y

s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
S
c
r
e
e
n

s
t
a
c
k
screen 1
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
Main
program
of TA/
report
Function
group 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
S
c
r
e
e
n

s
t
a
c
k
screen 2
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l
screen 1
SAP Memory (User-specific, not
session-specific)
SAP Memory (User-specific, not
session-specific)
Main
program
of TA/
report
Function
group 1


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


(C) SAP AG BC411 10-20
SAP AG
R
Implicit Exit / LEAVE SCREEN
External session 1 -> Window 1
External session 1 -> Window 1
SAP Memory (user-specific, not
session-specific)
SAP Memory (user-specific, not
session-specific)
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
S
c
r
e
e
n

s
t
a
c
k
screen 1
External session 1 -> Window 1
External session 1 -> Window 1
Main
program
of TA/
report
Function
group 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
S
c
r
e
e
n

s
t
a
c
k
screen 1
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l
screen 2
SAP Memory (user-specific, not
session-specific)
SAP Memory (user-specific, not
session-specific)
Main
program
of TA/
report
Function
group 1


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


(C) SAP AG BC411 10-21
SAP AG
R
List System
Basic list
List level 0
Detail list
List level 1
Detail list
List level 2
... ...
... ... ... ... ... ...
.
.
.
.
.
.
.


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



(C) SAP AG BC411 10-22
SAP AG
R
Several List Systems
List system 1 List system 2
Called screen Called screen
LEAVE TO
LIST-PROCESSING
CALL SCREEN
LEAVE TO
LIST-PROCESSING
Not
necessarily
displayed
Starting screen Starting screen


One list system may be assigned to each screen.
You create a new system when you call a new screen and use the LEAVE TO LI ST-
PROCESSING statement.



(C) SAP AG BC411 10-23
SAP AG
R
Several List Systems - Example I
. . .
TOP- OF- PAGE. . . .
. . .
CALL FUNCTI ON
' WRI TE_TEXT'
.
.
CALL FUNCTI ON
' CALL_SCREEN_AND_WRI TE'
. . .
TOP- OF- PAGE. . . .
. . .
CALL FUNCTI ON
' WRI TE_TEXT'
.
.
CALL FUNCTI ON
' CALL_SCREEN_AND_WRI TE'
SAPBC411D_CALL_FM_WRITE
.
.
.
FUNCTI ON WRI TE_LI ST.
. . .
WRI TE: t ext .
ENDFUNCTI ON.
TOP- OF- PAGE. . . .
FUNCTI ON WRI TE_LI ST.
. . .
WRI TE: t ext .
ENDFUNCTI ON.
TOP- OF- PAGE. . . .
Function group 1
List system
(SAPBC411D_CALL_FM_WRITE)
1 1


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



(C) SAP AG BC411 10-24
SAP AG
R
Several List Systems - Example II
. . .
TOP- OF- PAGE. . . .
. . .
CALL FUNCTI ON
' WRI TE_TEXT'
.
.
CALL FUNCTI ON
' CALL_SCREEN_AND_WRI TE'
. . .
TOP- OF- PAGE. . . .
. . .
CALL FUNCTI ON
' WRI TE_TEXT'
.
.
CALL FUNCTI ON
' CALL_SCREEN_AND_WRI TE'
.
.
.
List System
(function group 2)
FUNCTI ON cal l _scr een_and_wr i t e.
. . .
CALL SCREEN 200. " Cr eat e new l i st
" syst em
PROCESS BEFORE OUTPUT.
MODULE suppr ess_di al og.
PROCESS AFTER I NPUT.
MODULE l eave_t o_l i st .
MODULE back.
MODULE suppr ess_di al og OUTPUT.
SUPPRESS DI ALOG.
ENDMODULE.
MODULE LEAVE_TO_LI ST I NPUT.
LEAVE TO LI ST- PROCESSI NG.
WRI TE: . . .
ENDMODULE.
MODULE BACK.
LEAVE TO SCREEN 0.
ENDMODULE.
TOP- OF- PAGE. . . .
FUNCTI ON cal l _scr een_and_wr i t e.
. . .
CALL SCREEN 200. " Cr eat e new l i st
" syst em
PROCESS BEFORE OUTPUT.
MODULE suppr ess_di al og.
PROCESS AFTER I NPUT.
MODULE l eave_t o_l i st .
MODULE back.
MODULE suppr ess_di al og OUTPUT.
SUPPRESS DI ALOG.
ENDMODULE.
MODULE LEAVE_TO_LI ST I NPUT.
LEAVE TO LI ST- PROCESSI NG.
WRI TE: . . .
ENDMODULE.
MODULE BACK.
LEAVE TO SCREEN 0.
ENDMODULE.
TOP- OF- PAGE. . . .
2 2 2
( (SAPLFKT2_0200)
Function group 2
SAPBC411D_CALL_FM_WRITE


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


(C) SAP AG BC411 10-25
SAP AG
R
LEAVE TO SCREEN
External session 1 -> Window 1
External session 1 -> Window 1
SAP Memory (user-specific
not session-sepecific)
SAP Memory (user-specific
not session-sepecific)
Internal session 1
Main
program
of TA/
report
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
S
c
r
e
e
n

s
t
a
c
k
screen 1
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
S
c
r
e
e
n

s
t
a
c
k
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l
screen 2
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
screen 1
screen 3
Main
program
of TA/
report
Function
group 1
Function
group 1


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


(C) SAP AG BC411 10-26
SAP AG
R
CALL SELECTION-SCREEN
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
Main
program
of TA/
report
Function
group 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
screen 1
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l
screen 1
screen 2
Main
program
of TA/
report
Function
group 1
SAP Memory (user-specific
not session-specific)
SAP Memory (user-specific
not session-specific)
SAP Memory (user-specific
not session-specific)
SAP Memory (user-specific
not session-specific)
S
c
r
e
e
n

s
t
a
c
k
S
c
r
e
e
n

s
t
a
c
k


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


(C) SAP AG BC411 10-27
SAP AG
R
Transaction / Program
Transaction (LEAVE TO / CALL TRANSACTION Transaction (LEAVE TO / CALL TRANSACTION
Program (SUBMIT ) Program (SUBMIT )
Task
structuring
Task
structuring



(C) SAP AG BC411 10-28
SAP AG
R
CALL TRANSACTION TA01 /
SUBMIT PROG01 AND RETURN
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
Main program
of calling
transaction
or program
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
Main program of
calling
transaction or
program
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
New internal session 2
Main program
of called TA01
or
program PROG01
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)


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 TRANSACTI ON, SUBMI T, CALL DI ALOG) creates its own
internal session.


(C) SAP AG BC411 10-29
SAP AG
R
Implicit Exit / LEAVE PROGRAM
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
Main program
of transactoin
or program
PROG01
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
Internal session 2
Main program of
ended TA01
or program PROG01
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
Main
program
B
e
f
o
r
e

e
x
i
t
i
n
g
A
f
t
e
r

e
x
i
t
i
n
g


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


(C) SAP AG BC411 10-30
SAP AG
R
External session 1 -> Window 1
External session 1 -> Window 1
LEAVE TO TRANSACTION TA01
Internal session 3
Main program
of calling
program
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
External session 1 -> Window 1
External session 1 -> Window 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
New internal session 1
Main
program
of TA01
Internal session 1
Internal session 2
Main program 2
Main program 1
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
SAP Memory (user-specific,
not session-specific)
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l


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


(C) SAP AG BC411 10-31
SAP AG
R
SUBMIT PROG01
External session 1 -> Window 1
External session 1 -> Window 1
Internal session 2
Main program
of calling
program
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
External session 1 -> Window 1
External session 1 -> Window 1
A
B
A
P

M
e
m
o
r
y

(
s
e
s
s
i
o
n
-
s
p
e
c
i
f
i
c
)
New internal session 2
Main program
of
program
PROG01
Internal session 1
Main
program 1
Internal session 1
Main program 1
SAP Memory (user-specific, not
session-specific)
SAP Memory (user-specific, not
session-specific)
SAP Memory (user-specific, not
session-specific)
SAP Memory (user-specific, not
session-specific)
B
e
f
o
r
e

c
a
l
l
A
f
t
e
r

c
a
l
l


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


(C) SAP AG BC411 10-32
SAP AG
R
Context
Task
structuring
Task
structuring
Context (SUPPLY/DEMAND) Context (SUPPLY/DEMAND)


Refer to the Contexts unit.



(C) SAP AG BC411 10-33
SAP AG
R
Structuring Source Code
Include programs Include programs
Macros Macros
Source code
structuring
Source code
structuring


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


(C) SAP AG BC411 10-34
SAP AG
R
Include Programs
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Modul e pool SAPBC411D_TEST_TRANSACTI ON *
*& *
I NCLUDE bc411d_t est _t r ansact i ont op.
I NCLUDE bc411d_t est _t r ansact i oni 01.
I NCLUDE bc411d_t est _t r ansact i ono01.
I NCLUDE bc411d_t est _t r ansact i onf 01.
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Modul e pool SAPBC411D_TEST_TRANSACTI ON *
*& *
I NCLUDE bc411d_t est _t r ansact i ont op.
I NCLUDE bc411d_t est _t r ansact i oni 01.
I NCLUDE bc411d_t est _t r ansact i ono01.
I NCLUDE bc411d_t est _t r ansact i onf 01.
I NCLUDE pr og.


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



(C) SAP AG BC411 10-35
SAP AG
R
Macros
DATA: RESULT TYPE I ,
N1 TYPE I VALUE 5,
N2 TYPE I VALUE 6.
DEFI NE OPERATI ON.
RESULT = &1 &2 &3.
OUTPUT &1 &2 &3 RESULT.
END- OF- DEFI NI TI ON.
DEFI NE OUTPUT.
WRI TE: / ' The r esul t of &1 &2 &3 i s' , &4.
END- OF- DEFI NI TI ON.
OPERATI ON 4 + 3 .
OPERATI ON 2 ** 7.
DATA: RESULT TYPE I ,
N1 TYPE I VALUE 5,
N2 TYPE I VALUE 6.
DEFI NE OPERATI ON.
RESULT = &1 &2 &3.
OUTPUT &1 &2 &3 RESULT.
END- OF- DEFI NI TI ON.
DEFI NE OUTPUT.
WRI TE: / ' The r esul t of &1 &2 &3 i s' , &4.
END- OF- DEFI NI TI ON.
OPERATI ON 4 + 3 .
OPERATI ON 2 ** 7.
DEFINE <macro>.
<statements>
END-OF-DEFINITION
Output:
The result of 4 + 3 is 7
The result of 2 ** 7 is 128


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


(C) SAP AG BC411 10-36
SAP AG
R
Summary
In this unit, you have learned
How the different modularization units fit into the
memory model
How you can pass parameters in ABAP
What data is visible within modularization units
How to evaluate the different modularization units,
based on comparison criteria


SAP AG
R
Dynamic Program Generation: Contents
Dynamic ABAP Programming
Generating temporary and persistent programs at
runtime



(C) SAP AG BC411 11-2
SAP AG
R
Unit Objectives
Generate programs at runtime
Store generated programs temporarily in a
subroutine
Store generated programs permanently in
the R/3 Repository
At the end of this unit, you will be able to



(C) SAP AG BC411 11-3
SAP AG
R
Dynamic ABAP Programming
Dynamic statements
Field symbols
Generating programs from programs
t abname = ' SFLI GHT' .
SELECT * FROM ( t abname) .
Program Program
(subrountine) 2 (subrountine) 2
GENERATE
<f>
Program 1 Program 1


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, WRI TE 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 ASSI GN, dynamic type specification, ASSIGN COMPONENT)
Program generation from within a program
You can store ABAP code in an internal table and generate it into a program at runtime.




(C) SAP AG BC411 11-4
SAP AG
R
Dynamic Programming - Examples
TABLES: SFLI GHT
DATA: f m_name( 30) TYPE c VALUE ' POPUP_TO_CONFI RM_STEP' ,
scr een_no( 4) TYPE n VALUE ' 0100' ,
t ab_name( 30) TYPE c VALUE ' SFLI GHT' ,
upr o_name( 30) TYPE c VALUE ' MY_FORM' ,
pr og_name( 30) TYPE c VALUE ' sapbc411d_demo' ,
CALL FUNCTI ON ' POPUP_TO_CONFI RM_STEP' .
CALL FUNCTI ON f m_name.
CALL SCREEN ' 0100' .
CALL SCREEN scr een_no.
SELECT * FROM sf l i ght .
SELECT * FROM ( t ab_name) .
PERFORM my_f or mI N PROGRAM sapbc411d_demo.
PERFORM ( upr o_name) I N PROGRAM ( pr og_name) .
TABLES: SFLI GHT
DATA: f m_name( 30) TYPE c VALUE ' POPUP_TO_CONFI RM_STEP' ,
scr een_no( 4) TYPE n VALUE ' 0100' ,
t ab_name( 30) TYPE c VALUE ' SFLI GHT' ,
upr o_name( 30) TYPE c VALUE ' MY_FORM' ,
pr og_name( 30) TYPE c VALUE ' sapbc411d_demo' ,
CALL FUNCTI ON ' POPUP_TO_CONFI RM_STEP' .
CALL FUNCTI ON f m_name.
CALL SCREEN ' 0100' .
CALL SCREEN scr een_no.
SELECT * FROM sf l i ght .
SELECT * FROM ( t ab_name) .
PERFORM my_f or mI N PROGRAM sapbc411d_demo.
PERFORM ( upr o_name) I N PROGRAM ( pr og_name) .


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



(C) SAP AG BC411 11-5
SAP AG
R
Specifying Names at Runtime
SQL
SELECT ( <i t ab1>)
FROM ( <c>) I NTO . . .
WHERE ( <i t ab2>) .
Sorting and control level processing
in internal tables
SORT <i t ab> BY ( <c>) .
AT NEW( <c>) .
AT END OF ( <c>) .
Report
SUBMI T ( <c>) .
Subroutine calls
PERFORM ( <c>) I N PROGRAM ( <c>) .
Parentheses Parentheses
Function modules
CALL FUNCTI ON <f m>.
Authorization checks
AUTHORI TY- CHECK
OBJ ECT <obj > I D <name>
FI ELD <f i el d>.
Screen
CALL SCREEN <scr >.
Transaction
CALL TRANSACTI ON <t c>.
Message
MESSAGE I D <i d> TYPE <m_t ype>
NUMBER <no>.
Variable instead of text literal Variable instead of text literal


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


(C) SAP AG BC411 11-6
SAP AG
R
Generating Programs from Within Progams
Subroutine pool Subroutine pool
GENERATE SUBROUTI NE POOL GENERATE SUBROUTI NE POOL
REPORT zt est .
FORM di spl ay.
WRI TE ' Gener at ed pr ogr am' .
ENDFORM.
<itab> <itab>
REPORT zt est .
WRI TE ' Gener at ed pr ogr am' .
<itab> <itab>
I NSERT REPORT I NSERT REPORT
ext er nal PERFORM ext er nal PERFORM
SUBMI T SUBMI T
ABAP
Repository Repository
Generating temporary programs Generating persistent programs


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


(C) SAP AG BC411 11-7
SAP AG
R
Generating Temporary Programs
REPORT sapbc411d_subr out i ne_pool .
TYPES: edi t or _l i ne_t ype( 72) TYPE c.
DATA: sour ce_t abl e TYPE STANDARD TABLE OF edi t or _l i ne_t ype
WI TH KEY TABLE LI NE WI TH HEADER LI NE,
pr ogr am_name LI KE sy- cpr og.
APPEND: ' REPORT t est . ' TO sour ce_t abl e,
' FORM di spl ay. ' TO sour ce_t abl e,
' WRI TE ' ' I amt empor ar y' ' . ' TO sour ce_t abl e,
' ENDFORM. ' TO sour ce_t abl e.
GENERATE SUBROUTI NE POOL sour ce_t abl e NAME pr ogr am_name.
PERFORM di spl ay I N PROGRAM ( pr ogr am_name) .
GENERATE SUBROUTI NE POOL <i t ab> NAME <pr ogr am>.
PERFORM <f or m_name> i n pr ogr am<pr ogr am>.


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


(C) SAP AG BC411 11-8
SAP AG
R
Generating Persistent Programs
TYPES: edi t or _l i ne_t ype( 72) TYPE c.
DATA: sour ce_t abl e TYPE STANDARD TABLE OF edi t or _l i ne_t ype
WI TH KEY TABLE LI NE WI TH HEADER LI NE,
pr ogr am_name LI KE sy- cpr og.
APPEND: ' REPORT zgenpr og. ' TO sour ce_t abl e,
' WRI TE ' ' I ' mper si st ent ' ' . ' TO sour ce_t abl e.
I NSERT REPORT ' ZGENPROG' FROM sour ce_t abl e.
SUBMI T zgenpr og AND RETURN.
I NSERT REPORT <pr ogr am> FROM <i t ab>.
SUBMI T <pr ogr am> [ AND RETURN] .


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



(C) SAP AG BC411 11-9
SAP AG
R
Summary
You can program dynamicall y in ABAP using
dynamic statements, field symbols, and program
generation.
Generating programs from other programs is a very
powerful form of dynamic programming. You can
keep your generated coding either temporaril y or
permanentl y.


SAP AG 1999
This section contains supplementary materi al
to be used for reference
This materi al is not part of the standard course
Therefore, the instructor might not cover this
during the course presentation
Appendix



(C) SAP AG BC411 12-2
SAP AG
R
Further Information about Internal Tables and
Extracts
Internal Tables and Extracts
Accessing Table Entries Directly (Release 4.5A)



(C) SAP AG BC411 12-3
SAP AG
R
Internal Tables and Extracts (1)
AT FI RST. . ENDAT.
AT NEWf 1. . ENDAT.
AT NEWf 2. . ENDAT.
AT END OF f 2. . ENDAT.
AT END OF f 1. . ENDAT.
AT LAST. . ENDAT.
ENDLOOP.
<St at ement s>
<St at ement s>
<St at ement s>
<St at ement s>
<St at ement s>
<St at ement s>
<Si ngl e ent r y pr ocessi ng>
TYPES: BEGI N OF l i ne_t ype.
f 1, f 2, f 3.
END OF l i ne_t ype.
DATA: i t ab TYPE STANDARD TABLE
OF l i ne_t ype
WI TH KEY f 1
WI TH HEADER LI NE.
GET dbt ab. APPEND dbt ab TO i t ab.
END- OF- SELECTI ON.
SORT i t ab BY f 1.
LOOP AT i t ab.
FI ELD- GROUPS: header , f g.
I NSERT: f 1 I NTO header ,
f 2, f 3 I NTO f g.
GET dbt ab. EXTRACT f g.
END- OF- SELECTI ON.
SORT BY f 1.
LOOP.
I nt er nal t abl e I nt er nal t abl e Ext r act Ext r act


There are two steps in defining the record type of an extract dataset:
Declare the required record type (FI ELD- 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 I NTO ).
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
FI RST, 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 <f i el d>or a higher-level field in
the hierarchy changes its contents. Note that AT FI RST, AT NEW, AT END OF, and AT LAST are
control structures, and not events. This means that the sequence in which they occur is decisive for
the program flow.
The extract dataset or internal table must be sorted by group criteria.


(C) SAP AG BC411 12-4
SAP AG
R
Internal Tables and Extracts (2)
I nt er nal t abl e I nt er nal t abl e Ext r act Ext r act
Several internal tables
Control level sums at beginning of
a control level (AT FIRST, AT NEW
f)
Many operations (insert, change,
delete, single entry access,)
Changes possible at any time
Single line type per internal table
Line type is static
Control level processing only
according to the sequence of fields
in the table structure
SUM operation has high costs
Onl y one EXTRACT dataset
Control level sums only at the end
of a control level (AT END OF f, AT
LAST)
Few operations (only append, sort,
and sequential processing)
Extract cannot be extended after
SORT or LOOP
More than one line type possible
Line type is dynamic (INSERT is
not a declarative statement)
Control level processing according
to the sort sequence (regardless of
the sequence of fields in the
header)
(SUM(f)) optimized


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


(C) SAP AG BC411 12-5
SAP AG
R
Internal Tables and Extracts (3)
I nt er nal t abl e I nt er nal t abl e Ext r act Ext r act
LOOP AT i t ab.
AT END OF i t ab- car r i d.
SUM. WRI TE i t ab- seat smax.
ENDAT.
AT LAST.
SUM. WRI TE i t ab- seat smax.
ENDAT.
ENDLOOP.
LOOP.
AT END OF i t ab- car r i d.
WRI TE SUM( i t ab- seat smax) .
ENDAT.
AT LAST.
WRI TE SUM( i t ab- seat smax) .
ENDAT.
ENDLOOP.
CARRID SEATSMAX
AA 140
Internal table itab
Work area itab
LH 320
LH 270
SQ 340
590 LH *********
...
...
...
...
CARRID SEATSMAX
AA 140
Extract
LH 320
LH 270
SQ 340
...
...
...
...
590
SUM(itab-seatsmax)


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(<numf i el d>) and CNT(<header f i el d>) within
the AT END OF ENDAT and AT LAST ENDAT processing blocks:
SUM(<numf i el d>) calculates the sum for each group. The required work fields are generated
automatically, and initialized with zero each time the control level changes.
CNT(<header f i el d>) 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
R
Accessing Table Entries Directly (Release 4.5)
Contents
Aim: To be able to access internal tables without copying
Reading and writing table entries without copying to and from a work
area
Means: ASSIGNING addition in READ and LOOP
INTO wa addition can usually be replaced with the ASSIGNING
addition
LOOP AT itab ... ASSIGNING <fs>...
Corresponds to a LOOP with READ ASSIGNING as its first
statement
After the loop, the field symbol corresponds to the last line of the
table
Control levels and LOOP ... ASSIGNING
No copying to output area
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.


(C) SAP AG BC411 13-2
SAP AG
R
Structure of Deep Tables
* Bot t om- up al gor i t hm
* Ent r i es: 50 ( out er t abl e)
10 ( i nner t abl e)
* Li ne wi dt h: 500 ( out er )
4 ( i nner )
DO 50 TI MES.
CLEAR wa.
DO 10 TI MES.
APPEND n TO wa- i nt t ab.
ADD 1 TO n.
ENDDO.
APPEND wa TO i t ab.
ENDDO.
* Top- down al gor i t hm
* Ent r i es: 50 ( out er t abl e)
10 ( i nner t abl e)
* Li ne wi dt h: 500 ( out er )
4 ( i nner )
DO 50 TI MES.
APPEND I NI TI AL LI NE TO i t ab.
ENDDO.
LOOP AT i t ab ASSI GNI NG <f s>.
DO 10 TI MES.
APPEND n TO <f s>- i nt t ab.
ADD 1 TO n.
ENDDO.
ENDLOOP.


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


(C) SAP AG BC411 13-3
SAP AG
R
Accessing Table Entries Directly (Release 4.5A)
Aim: To be able to access internal tabes without copying
Reading and writing table entries without copying to and from a work
area
Means: ASSIGNING addition in READ and LOOP
INTO wa addition can usually be replaced with the ASSIGNING
addition
LOOP AT itab ... ASSIGNING <fs>...
Corresponds to a LOOP with READ ASSIGNING as its first
statement
After the loop, the field symbol corresponds to the last line of the
table
Control levels and LOOP ... ASSIGNING
No copying to output area
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.


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



(C) SAP AG BC411 14-2
SAP AG
R
Rule 3: Minimize the Number of Transfers 1
FOR ALL ENTRIES IN
REPORT sapbc411d_sel ect _vi ew.
SELECT * FROM sf l i ght I NTO TABLE sf l i ght _i t ab.
SELECT car r i d . . . I NTO CORRESPONDI NG FI ELDS OF sbook
FROM sbook
FOR ALL ENTRI ES I N sf l i ght _i t ab
WHERE car r i d = sf l i ght _i t ab- car r i d
AND conni d = sf l i ght _i t ab- conni d
AND f l dat e = sf l i ght _i t ab- f l dat e.
WRI TE: / . . .
ENDSELECT.
REPORT sapbc411d_sel ect _vi ew.
SELECT * FROM sf l i ght I NTO TABLE sf l i ght _i t ab.
SELECT car r i d . . . I NTO CORRESPONDI NG FI ELDS OF sbook
FROM sbook
FOR ALL ENTRI ES I N sf l i ght _i t ab
WHERE car r i d = sf l i ght _i t ab- car r i d
AND conni d = sf l i ght _i t ab- conni d
AND f l dat e = sf l i ght _i t ab- f l dat e.
WRI TE: / . . .
ENDSELECT.


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



(C) SAP AG BC411 14-3
SAP AG
R
Rule 3: Minimize the Number of Transfers 2
Explicit cursor
REPORT sapbc411d_sel ect _vi ew.
. . .
OPEN CURSOR c1 FOR SELECT * FROM sf l i ght WHERE cond1 ORDER BY PRI MARY KEY.
OPEN CURSOR c2 FOR SELECT * FROM sbook WHERE cond2 ORDER BY PRI MARY KEY.
DO.
FETCH NEXT CURSOR c1 I NTO sf l i ght .
I F sy- subr c <> 0. EXI T. ENDI F.
I F sy- i ndex = 1.
FETCH NEXT CURSOR c2 I NTO sbook.
ENDI F.
WHI LE sy- subr c = 0 AND sf l i ght - car r i d = sbook- car r i d
AND . . .
. . . t ue et was. . .
FETCH NEXT CURSOR c2 I NTO sbook.
ENDWHI LE
I F sy- subr c <> 0. EXI T. ENDI F.
ENDDO. CLOSE CURSOR: c1, c2.
REPORT sapbc411d_sel ect _vi ew.
. . .
OPEN CURSOR c1 FOR SELECT * FROM sf l i ght WHERE cond1 ORDER BY PRI MARY KEY.
OPEN CURSOR c2 FOR SELECT * FROM sbook WHERE cond2 ORDER BY PRI MARY KEY.
DO.
FETCH NEXT CURSOR c1 I NTO sf l i ght .
I F sy- subr c <> 0. EXI T. ENDI F.
I F sy- i ndex = 1.
FETCH NEXT CURSOR c2 I NTO sbook.
ENDI F.
WHI LE sy- subr c = 0 AND sf l i ght - car r i d = sbook- car r i d
AND . . .
. . . t ue et was. . .
FETCH NEXT CURSOR c2 I NTO sbook.
ENDWHI LE
I F sy- subr c <> 0. EXI T. ENDI F.
ENDDO. CLOSE CURSOR: c1, c2.
OPEN CURSOR <cur sor > FOR
SELECT * FROM <dbt ab> WHERE <cond> ORDER BY PRI MARY KEY.
FETCH NEXT CURSOR <cur sor > I NTO <dbt ab>.
OPEN CURSOR <cur sor > FOR
SELECT * FROM <dbt ab> WHERE <cond> ORDER BY PRI MARY KEY.
FETCH NEXT CURSOR <cur sor > I NTO <dbt ab>.


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



(C) SAP AG BC411 14-4
SAP AG
R
Rule 4: Minimize the Search Overhead
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)
General rule
SELECT * FROM sf l i ght WHERE
car r i d = ' LH' AND ( conni d = ' 0400' OR
f l dat e = ' 19981129' )
ENDSELECT.
SELECT * FROM sf l i ght WHERE
car r i d = ' LH' AND ( conni d = ' 0400' OR
f l dat e = ' 19981129' )
ENDSELECT.
SELECT * FROM sf l i ght WHERE
( car r i d = ' LH' AND conni d = ' 0400' )
OR ( car r i d = ' LH' AND f l dat e = ' 19981129' )
ENDSELECT.
SELECT * FROM sf l i ght WHERE
( car r i d = ' LH' AND conni d = ' 0400' )
OR ( car r i d = ' LH' AND f l dat e = ' 19981129' )
ENDSELECT.


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


(C) SAP AG BC411 14-5
SAP AG
R
Rule 4: Minimize the Search Overhead
SELECT * FROM sbook
WHERE NOT ( cancel l ed = ' X' OR car r i d NE ' LH' )
. . . Pr ocessi ng . . .
ENDSELECT.
SELECT * FROM sbook
WHERE NOT ( cancel l ed = ' X' OR car r i d NE ' LH' )
. . . Pr ocessi ng . . .
ENDSELECT.
No index support
But: Rule 1 still applies!
Caution when using the NOT operator
SELECT * FROM sbook
WHERE car r i d = ' LH' AND cancel l ed NE ' X'
. . . Pr ocessi ng . . .
ENDSELECT.
SELECT * FROM sbook
WHERE car r i d = ' LH' AND cancel l ed NE ' X'
. . . Pr ocessi ng . . .
ENDSELECT.


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



(C) SAP AG BC411 14-6
SAP AG
R
SELECT before changes
SELECT * FROM dbt ab WHERE . . .
I F sy- subr c = 0.
UPDATE dbt ab . . .
ELSE.
I NSERT dbt ab . . .
ENDI F.
SELECT * FROM dbt ab WHERE . . .
I F sy- subr c = 0.
UPDATE dbt ab . . .
ELSE.
I NSERT dbt ab . . .
ENDI F.
I NSERT dbt ab . . .
I F sy- subr c <> 0.
UPDATE . . .
ENDI F.
I NSERT dbt ab . . .
I F sy- subr c <> 0.
UPDATE . . .
ENDI F.
Instead, use
Instead, use
Rule 5: Reduce the Database Load 1


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



(C) SAP AG BC411 14-7
SAP AG
R
Rule 5: Reduce the Database Load
Fr equent way of pr ocessi ng l ar ge
amount s of dat a
st ar t = space.
DO.
SELECT * UP TO 1000 ROWS FROM t 1
WHERE key > st ar t
ORDER BY PRI MARY KEY.
. . . Pr ocess ent r y f r omt 1
( - - > i nser t , updat e, del et e)
ENDSELECT.
I F sy- subr c = 0.
COMMI T WORK.
st ar t = t 1- key.
ELSE. EXI T. ENDI F.
ENDDO.
Fr equent way of pr ocessi ng l ar ge
amount s of dat a
st ar t = space.
DO.
SELECT * UP TO 1000 ROWS FROM t 1
WHERE key > st ar t
ORDER BY PRI MARY KEY.
. . . Pr ocess ent r y f r omt 1
( - - > i nser t , updat e, del et e)
ENDSELECT.
I F sy- subr c = 0.
COMMI T WORK.
st ar t = t 1- key.
ELSE. EXI T. ENDI F.
ENDDO.
Restart logic
Ver wenden Si e besser :
OPEN CURSOR . . . WI TH HOLD . . . FOR
SELECT * FROM . . .
Ver wenden Si e besser :
OPEN CURSOR . . . WI TH HOLD . . . FOR
SELECT * FROM . . .
Instead, use
Instead, use


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


SAP AG
R
Further Information About Modularization Units:
Contents
Comparison criteria



(C) SAP AG BC411 15-2
SAP AG
R
Position in Elementary Modularization Units
Position in Elementary Modularization Units
Subroutine
Subroutine
Function module
Function module
Screen
Screen
Module
Module
Event
Event
Interface
Interface
Position in Memory Model
Position in Memory Model
Data types
Data types
Parameter specification
Parameter specification
Checks
Checks
Default values
Default values
Changes to interface
Changes to interface
Passing method
Passing method
Comparison Criteria I
Method
Method


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


(C) SAP AG BC411 15-3
SAP AG
R
Comparison Criteria II
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Local memory
Local memory
Dialogs
Dialogs
Calls
Calls
Calling unit
Calling unit
Call type
Call type
Cost
* Runtime
* Memory occupied
Cost
* Runtime
* Memory occupied


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


(C) SAP AG BC411 15-4
SAP AG
R
Comparison Criteria III
Administration Function
Administration Function
Documentation
Documentation
Catalog
Catalog
Directory of calling programs
Directory of calling programs
Test framework
Test framework
Reusability / Use
Reusability / Use


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


(C) SAP AG BC411 15-5
SAP AG
R
Internal Subroutine I
Interface
Interface
Passing methods Value
Value and return
Address
Checks Type check where types specified
Parameter specification Position in call
Data types All data types
Default values No
Changes to interface Calls need to be updated
Passing methods Value
Value and return
Address
Checks Type check where types specified
Parameter specification Position in call
Data types All data types
Default values No
Changes to interface Calls need to be updated
Part of a main program (main or additional program group)
Main program and subroutines have common data areas
Part of a main program (main or additional program group)
Main program and subroutines have common data areas
Position in memory model
Position in memory model
Subroutine
Subroutine
Position in elementary modularization units
Position in elementary modularization units


Internal subroutines are called within the same main program.
When you pass a data type, the actual parameter is used in place of the formal parameter. The
system checks whether the type of the actual parameter is compatible with that of the formal
parameter (refer to the Types unit).


(C) SAP AG BC411 15-6
SAP AG
R
Internal Subroutine II
Calling unit Program
Call type Static or dynamic
Cost/runtime Factor 1 (depends on number of parameters)
Memory occupied Main program
Calling unit Program
Call type Static or dynamic
Cost/runtime Factor 1 (depends on number of parameters)
Memory occupied Main program
Call
Call
Dialogs
Dialogs
Possibly selected fields from the main program
Possibly selected fields from the main program
Local memory
Local memory
Data passing (other than interface)
Data passing (other than interface)
Global data of main program
Global data of main program
Shared data areas
Shared data areas
Own dialogs Screens always belong to main
program of the program group
User interface/
Input possibilities
Own dialogs Screens always belong to main
program of the program group
User interface/
Input possibilities


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


(C) SAP AG BC411 15-7
SAP AG
R
Internal Subroutine III
Program structure
Repeatedly-used statements (local)
Program structure
Repeatedly-used statements (local)
Reusablilty / Use
Reusablilty / Use
Administration Functions
Administration Functions
Documentation Main program
Catalog Yes
Directory of
calling programs
Test framework No
Documentation Main program
Catalog Yes
Directory of
calling programs
Test framework No


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



(C) SAP AG BC411 15-8
SAP AG
R
External Subroutine I
Interface
Interface
Passing methods Value
Value and return
Address
Checks Type check where types specified
Parameter specification Position in call
Data types All data types
Default values No
Changes to interface Calls need to be updated
Passing methods Value
Value and return
Address
Checks Type check where types specified
Parameter specification Position in call
Data types All data types
Default values No
Changes to interface Calls need to be updated
Subroutine
Subroutine
Position in elementary modularization units
Position in elementary modularization units
Position in memory model
Position in memory model
Part of a main program (main or additional program)
Call may load a new program
Programs in a program group have shared data and
table work areas
Part of a main program (main or additional program)
Call may load a new program
Programs in a program group have shared data and
table work areas


External subroutines are called from another main program.
When you pass data types, the actual parameter must be fully compatible with the formal parameter.
If you do not pass a type, the actual parameter must be at least as long as the formal parameter.


(C) SAP AG BC411 15-9
SAP AG
R
External Subroutine II
Calling unit Program
Call type Static or dynamic
Cost/runtime Factor 6, a new program may be loaded when
Memory occupied the routine is called
Calling unit Program
Call type Static or dynamic
Cost/runtime Factor 6, a new program may be loaded when
Memory occupied the routine is called
Call
Call
Yes - global data of the main program
Yes - global data of the main program
Local memory
Local memory
Table work areas
COMMON areas
Global data of the main program
Table work areas
COMMON areas
Global data of the main program
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Dialogs
Dialogs
Own dialogs No - screens belong to the main program
of the program group
User interface/
Input possibilities
Own dialogs No - screens belong to the main program
of the program group
User interface/
Input possibilities


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


(C) SAP AG BC411 15-10
SAP AG
R
External Subroutine III
Shared subroutines in an application
(subroutine pool)
Shared subroutines in an application
(subroutine pool)
Reusability / Use
Reusability / Use
Administration functions
Administration functions
Documentation Subroutine pool
Catalog No
Directory of Repository Infosystem,
Calling programs Where-used list
Test framework No
Documentation Subroutine pool
Catalog No
Directory of Repository Infosystem,
Calling programs Where-used list
Test framework No


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


(C) SAP AG BC411 15-11
SAP AG
R
Function Module I
Interface
Interface
Passing methods Value/address (IMPORTING)
Value/address (EXPORTING)
Value/address (CHANGING)
Address (TABLES)
Checks Type checks (reference fields)
Length checks (ref. fields/structures)
Parameter specification Keyword-oriented
Data types All data types
Default values Yes
Changes to interface May require changes to calls
Passing methods Value/address (IMPORTING)
Value/address (EXPORTING)
Value/address (CHANGING)
Address (TABLES)
Checks Type checks (reference fields)
Length checks (ref. fields/structures)
Parameter specification Keyword-oriented
Data types All data types
Default values Yes
Changes to interface May require changes to calls
Function module
Function module
Position in elementary modularization units
Position in elementary modularization units
Position in memory model
Position in memory model
Part of a main program (function group)
Call may generate a new program group
Program groups share an internal session
Part of a main program (function group)
Call may generate a new program group
Program groups share an internal session


You can specify whether the EXPORTING, IMPORTING, and CHANGING parameters should be
passed by value or reference.
If you enter a default value for an IMPORTING parameter, it is optional when you call the function
module. EXPORTING parameters are optional by default. If you change the interface of a function
module, you only need to adapt calls if you add, change, or delete IMPORTING parameters that
have no default value or table parameters.


(C) SAP AG BC411 15-12
SAP AG
R
Function Module II
Calling unit Program
Call type Dynamic, usually by specifying a literal
Cost/runtime Factor 12, a new program may be loaded
memory occupied when the function is called
Calling unit Program
Call type Dynamic, usually by specifying a literal
Cost/runtime Factor 12, a new program may be loaded
memory occupied when the function is called
Call
Call
Yes - global data in the function group
Yes - global data in the function group
Local memory
Local memory
Output list
Output list
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Dialogs
Dialogs
Own dialogs Yes. Screens belong to the main program
(function group) of the program group
User interface/
Input possibilities
Own dialogs Yes. Screens belong to the main program
(function group) of the program group
User interface/
Input possibilities


The cost of the first function call in a function group are higher than for subsequent calls, since the
whole function group is loaded in the first call.


(C) SAP AG BC411 15-13
SAP AG
R
Function Module III
Administration function
Administration function
Documentation Yes
Catalog Yes
Directory of Repository Infosystem,
calling programs Where-used list in
Function Builder
Test framework Yes
Documentation Yes
Catalog Yes
Directory of Repository Infosystem,
calling programs Where-used list in
Function Builder
Test framework Yes
Application-specific or cross-application
Advantages: - Administration functions
- Exception handling
Application-specific or cross-application
Advantages: - Administration functions
- Exception handling
Reusability / Use
Reusability / Use


You can use the where-used list in the Function Builder or the Repository Information System to
display a list of where the function module is called.


(C) SAP AG BC411 15-14
SAP AG
R
Screen, CALL SCREEN, CALL SELECTION-
SCREEN I
Interface
Interface
Passing methods Input/output fields, automatic field
transport where screen fields and
ABAP fields have the same names
Checks
Parameter specification
Data types
Default values
Changes to interface
Passing methods Input/output fields, automatic field
transport where screen fields and
ABAP fields have the same names
Checks
Parameter specification
Data types
Default values
Changes to interface
Screens always belong to the main program of the
current program group
The called screen is loaded into the current roll area
Screens always belong to the main program of the
current program group
The called screen is loaded into the current roll area
Position in memory model
Position in memory model
Screen
Screen
Position in elementary modularization units
Position in elementary modularization units


The CALL SCREEN and CALL SELECTION-SCREEN statements allow you to process a part of a
dialog. Screens are always assigned to the main program of a program group. This program must
always contain the screen modules. If you use CALL SCREEN or CALL SELECTION-SCREEN
within an additional program group, this group becomes the program group responsible for the
screen. Selection screens called using CALL SELECTION-SCREEN must be defined using
SELECTION-SCREEN BEGIN/END OF SCREEN <nnnn>(or be the standard selection screen of a
program). Another difference is that the system is responsible for returning from a selection screen
(not the ABAP program, as with CALL SCREEN).


(C) SAP AG BC411 15-15
SAP AG
R
Screen, CALL SCREEN, CALL SELECTION-
SCREEN II
Calling unit Program
Call type Static or dynamic
Cost/runtime 148
Memory occupied Loaded into roll area
Calling unit Program
Call type Static or dynamic
Cost/runtime 148
Memory occupied Loaded into roll area
Call
Call
Yes - global data of the ABAP program
Yes - global data of the ABAP program
Local memory
Local memory
Global data of the ABAP program
Global data of the ABAP program
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Dialogs
Dialogs
Own dialogs
User interface/
input possibilities
Own dialogs
User interface/
input possibilities
SPA/GPA memory
SPA/GPA memory


The called screen is loaded into the current roll area.


(C) SAP AG BC411 15-16
SAP AG
R
Screen, CALL SCREEN, CALL SELECTION-
SCREEN III
Administration functions
Administration functions
Documentation Screen documentation
Catalog Screen Painter
Directory of
calling programs No
Test framework Yes
Documentation Screen documentation
Catalog Screen Painter
Directory of
calling programs No
Test framework Yes
Local screen chain
Dialog box on a screen
Customer modifications (Adding extra fields)
Dialogs from function modules
Local screen chain
Dialog box on a screen
Customer modifications (Adding extra fields)
Dialogs from function modules
Reusability / Use
Reusability / Use


The called screen is loaded into the current roll area.


(C) SAP AG BC411 15-17
SAP AG
R
Module I
Position in the memory model
Position in the memory model
Modules are part of the main program
Main program and modules have shared data area
Modules are part of the main program
Main program and modules have shared data area
Module
Module
Position in elementary modularization units
Position in elementary modularization units
Interface
Interface
Passing methods Automatic field transport between
screen and ABAP fields with the
same names
Checks
Parameter specification
Data types
Default values
Changes to interface
Passing methods Automatic field transport between
screen and ABAP fields with the
same names
Checks
Parameter specification
Data types
Default values
Changes to interface


You call modules from the flow logic of a screen.


(C) SAP AG BC411 15-18
SAP AG
R
Module II
Calling unit Screen
Call type Static
Cost/runtime
Memory occupied Main program
Calling unit Screen
Call type Static
Cost/runtime
Memory occupied Main program
Call
Call
Yes - possibly selected fields of main program
Yes - possibly selected fields of main program
Local memory
Local memory
Yes - global data of the main program
Yes - global data of the main program
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Dialogs
Dialogs
Own dialogs
User interface/
Input possibilities
Own dialogs
User interface/
Input possibilities


Modules do not have any local data. They always access the global data of the main program
(module pool).



(C) SAP AG BC411 15-19
SAP AG
R
Module III
Within a module pool
Can be called from any screen
Within a module pool
Can be called from any screen
Reusability / Use
Reusability / Use
Administration functions
Administration functions
Documentation Main program (module pool)
Catalog No
Directory of Repository Infosystem,
calling programs Where-used list in
Repository Browser
Test framework No
Documentation Main program (module pool)
Catalog No
Directory of Repository Infosystem,
calling programs Where-used list in
Repository Browser
Test framework No


You can call a module from any screen in the module pool.


(C) SAP AG BC411 15-20
SAP AG
R
Event I
Position in the memory model
Position in the memory model
Events always belong to the main program of an active
program group
The main program and the events have a shared data
area
Events always belong to the main program of an active
program group
The main program and the events have a shared data
area
Event
Event
Position in elementary modularization units
Position in elementary modularization units
Interface
Interface
Passing methods
Checks
Parameter specification
Data types
Default values
Changes to interface
Passing methods
Checks
Parameter specification
Data types
Default values
Changes to interface


Events are triggered by the ABAP runtime system. There is a processing block assigned to each
event. Events for reading data from logical databases must occur in the main program of the main
program group.


(C) SAP AG BC411 15-21
SAP AG
R
Event II
Yes - possibly selected fields of the main program
Yes - possibly selected fields of the main program
Local memory
Local memory
Yes - global data of the main program
Yes - global data of the main program
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Dialogs
Dialogs
Own dialogs
User interface/
Input possibilities
Own dialogs
User interface/
Input possibilities
Calling unit ABAP runtime system
Call type
Cost/runtime
Memory occupied Main program
Calling unit ABAP runtime system
Call type
Cost/runtime
Memory occupied Main program
Call
Call


Events have no local data. They always use the global data of the main program.


(C) SAP AG BC411 15-22
SAP AG
R
Event III
Logical databases
Interactive programming
Page layout
Logical databases
Interactive programming
Page layout
Reusability / Use
Reusability / Use
Administration functions
Administration functions
Documentation Main program
Catalog No
Directory of Where-used list in
calling programs Repository Browser
Test framework No
Documentation Main program
Catalog No
Directory of Where-used list in
calling programs Repository Browser
Test framework No



(C) SAP AG BC411 15-23
SAP AG
R
Dialog Module I
Screen - program - module
Screen - program - module
Position in elementary modularization units
Position in elementary modularization units
Position in memory module
Position in memory module
Standalone program
Call creates a new internal session
Several internal sessions share one external session with
one shared ABAP memory
Standalone program
Call creates a new internal session
Several internal sessions share one external session with
one shared ABAP memory
Interface
Interface
Passing methods Name-oriented, value of
SY-SUBRC passed automatically
Checks None
Parameter specification EXPORTING/IMPORTING/USING itab
Data types All data types except object references
Default values No
Changes to interface Some adjustment of calls required
Passing methods Name-oriented, value of
SY-SUBRC passed automatically
Checks None
Parameter specification EXPORTING/IMPORTING/USING itab
Data types All data types except object references
Default values No
Changes to interface Some adjustment of calls required


When you call a dialog module, the system opens a new internal session (roll area). A dialog module
consists of a module pool and its associated screnes. The name of the module pool and the number
of the initial screen are stored in table TDCT.
When you call the dialog module, you name the objects that you want to pass to it (EXPORTING)
and the objects that you want the dialog module to return (IMPORTING). Data is transferred by the
ABAP runtime system using global ABAP memory. The data transfer is fieldname-oriented.
Since CALL DIALOG opens a new internal session, you cannot pass references. References can
only point to data objects in the same roll area.


(C) SAP AG BC411 15-24
SAP AG
R
Dialog Module II
Calling program Program
Call type Dynamic, usually as a literal
Cost/runtime Factor 8000
Memory occupied Own roll area
Calling program Program
Call type Dynamic, usually as a literal
Cost/runtime Factor 8000
Memory occupied Own roll area
Call
Call
No
No
Local memory
Local memory
No
No
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
SPA/GPA memory
Global ABAP memory
SPA/GPA memory
Global ABAP memory
Dialogs
Dialogs
Own dialogs Yes
User interface/ USING <tab>
Input possibilities
Own dialogs Yes
User interface/ USING <tab>
Input possibilities


As well as specifying the data objects that you want to transfer when you call the dialog module, you
can also pass data between the calling program and the module using SPA/GPA memory or ABAP
memory.
The USING <tab>parameter allows you to pass an internal table containing input values for screen
fields.
Since data is always passed to and from dialog modules by value, calling a dialog module can be
very expensive if you need to pass large table work areas or internal tables.
You can use the global ABAP memory as a local memory.


(C) SAP AG BC411 15-25
SAP AG
R
Dialog Module III
Administration Functions
Administration Functions
Documentation Program documentation
Catalog Table TDCT
Repository Infosystem
Directory of Where-used list
calling programs in Repository Browser
Test framework No
Documentation Program documentation
Catalog Table TDCT
Repository Infosystem
Directory of Where-used list
calling programs in Repository Browser
Test framework No
Reusable subdialogs
Rarely-used functions removed to their own roll area
Large amounts of memory must be available
temporarily (internal tables)
Call can be expensive (passing internal tables)
Reusable subdialogs
Rarely-used functions removed to their own roll area
Large amounts of memory must be available
temporarily (internal tables)
Call can be expensive (passing internal tables)
Reusability / Use
Reusability / Use


Table TDCT contains a list of all dialog modules.


(C) SAP AG BC411 15-26
SAP AG
R
Transaction I
Screen - program - module
Screen - program - module
Position in elementary modularization units
Position in elementary modularization units
Position in the memory model
Position in the memory model
Standalone program
Call creates a new internal session
Several internal sessions share one external session
Standalone program
Call creates a new internal session
Several internal sessions share one external session
Interface
Interface
Passing methods
Checks
Parameter specification
Data types
Default values
Changes to interface Requires some changes to calls
Passing methods
Checks
Parameter specification
Data types
Default values
Changes to interface Requires some changes to calls


When you call a transaction using CALL TRANSACTION, the system opens a new internal session
(roll area). If you have an internal session n where n >=0, LEAVE TO TRANSACTION closes all
open internal sessions 0 n and runs the new transaction in session 0.
Each transaction is assigned to a module pool with screens. The difference between transactions and
dialog modules is in the call. Transations can be called directly by the user as well as from a
program (CALL mode). Dialog modules, on the other hand, can only be called from a program. The
system field SY-CALLD indicates whether a program has been activated in CALL mode.
The interface of a transaction is made up of the input/output fields of its screens.


(C) SAP AG BC411 15-27
SAP AG
R
Transaction II
No
No
Local memory
Local memory
No
No
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
SPA/GPA memory
Global ABAP memory
SPA/GPA memory
Global ABAP memory
Calling unit Program
Call type Dynamic
Cost/runtime 8000
Memory occupied Own roll area
Calling unit Program
Call type Dynamic
Cost/runtime 8000
Memory occupied Own roll area
Call
Call
Dialogs
Dialogs
Own dialogs Yes
User interfaces/ a) SPA/GPA values and
AND SKIP FIRST SCREEN addition
Input possibilities b) USING <tab>
Own dialogs Yes
User interfaces/ a) SPA/GPA values and
AND SKIP FIRST SCREEN addition
Input possibilities b) USING <tab>


You can pass data to a transaction either indirectly, using SPA/GPA memory, or directly using an
internal table (USING <tab>), in which you save the input values for screen fields.


(C) SAP AG BC411 15-28
SAP AG
R
Transaction III
Administration functions
Administration functions
Documentation Transaction documentation
Catalog Table TSTC,
Repository Infosystem
Directory of Where-used list in
calling programs Repository Browser
Test framework No
Documentation Transaction documentation
Catalog Table TSTC,
Repository Infosystem
Directory of Where-used list in
calling programs Repository Browser
Test framework No
Uses an existing transaction
Customer modifications, simple variants,
call original transaction
Uses an existing transaction
Customer modifications, simple variants,
call original transaction
Reusability / Use
Reusability / Use


Table TSTC contains all transactions.


(C) SAP AG BC411 15-29
SAP AG
R
Program, SUBMIT I
Selection screen - program- event
Selection screen - program- event
Position in elementary modularization units
Position in elementary modularization units
Position in memory model
Position in memory model
Standalone program
Call generates a new internal session
Several internal sessions share an external session with
shared ABAP memory
Standalone program
Call generates a new internal session
Several internal sessions share an external session with
shared ABAP memory
Interface
Interface
Passing methods Value (for selection screen
fields)
Checks Selection screen
Parameter specification Keyword-oriented
Data types Selection tables, single values
Default values Yes - report
Changes to interface Some changes to calls required
Passing methods Value (for selection screen
fields)
Checks Selection screen
Parameter specification Keyword-oriented
Data types Selection tables, single values
Default values Yes - report
Changes to interface Some changes to calls required


When you start a report using the SUBMIT AND RETURN statement, the system opens a new
internal session (roll area). When the program ends, the new session n+1 is closed and the system
carries on processing in session n-1 (as long as n >0). If you use SUBMIT without RETURN, the
existing session containing the calling program is replaced by a new internal session in which the
new report is then run.
The interface of the program consists of the selection screen fields. These can be selection tables or
single values, which you can pass in the WITH addition.
Unlike other modularization units, the report that you call cannot pass values back to the calling
program.


(C) SAP AG BC411 15-30
SAP AG
R
Program, SUBMIT II
No
No
Local memory
Local memory
No
No
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
SPA/GPA memory
Global ABAP memory
SPA/GPA memory
Global ABAP memory
Calling unit Program
Call type Static or dynamic
Cost/runtime 10 000
Memory occupied Own roll area
Calling unit Program
Call type Static or dynamic
Cost/runtime 10 000
Memory occupied Own roll area
Call
Call
Dialogs
Dialogs
Own dialogs Yes
User interface/ Filling the selection screen
Input possibilities
Own dialogs Yes
User interface/ Filling the selection screen
Input possibilities


You can pass data such as table work areas or internal tables to and from the called program using
the global ABAP memory.


(C) SAP AG BC411 15-31
SAP AG
R
Program, SUBMIT III
Administration functions
Administration functions
Documentation Program documentation
Catalog ABAP development
Directory of ABAP Dictionary
calling programs Repository Information System
Test framework No
Documentation Program documentation
Catalog ABAP development
Directory of ABAP Dictionary
calling programs Repository Information System
Test framework No
Uses an existing report
Enables you to keep display functions (interactive program)
in a separate program
Uses an existing report
Enables you to keep display functions (interactive program)
in a separate program
Reusability / Use
Reusability / Use


If you want to use complex display functions within a transaction, you can use an interactive
program. You would implement this function in a separate program.


(C) SAP AG BC411 15-32
SAP AG
R
LEAVE TO LIST PROCESSING I
Interface
Interface
Passing methods
Checks
Parameter specification
Data structures
Default values
Changes to interface
Passing methods
Checks
Parameter specification
Data structures
Default values
Changes to interface
List screen - events
List screen - events
Position in elementary modularization units
Position in elementary modularization units
Position in the memory model
Position in the memory model
List always belong to the main program of the
main program group
Events are part of the main program
Part of a program
List always belong to the main program of the
main program group
Events are part of the main program
Part of a program


You can implement simpler display functions within the module pool of a transaction instead of
starting a new ABAP program using SUBMIT.


(C) SAP AG BC411 15-33
SAP AG
R
LEAVE TO LIST PROCESSING II
Global program data
Global program data
Shared data areas
Shared data areas
Data passing (other than interface)
Data passing (other than interface)
Calling unit Program (module)
Call type
Cost/runtime Factor 2
Memory occupied Part of program
Calling unit Program (module)
Call type
Cost/runtime Factor 2
Memory occupied Part of program
Call
Call
Local memory
Local memory
Dialogs
Dialogs
Own dialogs
User interface/
Input possibilities
Own dialogs
User interface/
Input possibilities


The list is created and processed (interactive program) in the same program as the dialog modules.
The global data of the main program is therefore available both for list output and for the events of
the interactive program.


(C) SAP AG BC411 15-34
SAP AG
R
LEAVE TO LIST PROCESSING III
Display functions are implemented within the module pool
Display functions are implemented within the module pool
Reusability / Use
Reusability / Use
Administration function
Administration function
Documentation
Catalog
Directory of
calling programs
Test framework
Documentation
Catalog
Directory of
calling programs
Test framework


LEAVE TO LIST PROCESSING is a simple ABAP statement with no special administration
functions.

SAP AG
R
String Processing: Contents
String comparisons
String operations



(C) SAP AG BC411 16-2
SAP AG
R
Unit Objectives
At the end of this unit, you will be able to
List the string comparisons supported in
ABAP
Use string operations



(C) SAP AG BC411 16-3
SAP AG
R
String Processing
A B
REPLACE
TRANSLATE
SHI FT
CONDENSE
A B A P
A B
+ A
A B A
A B A
A B A
A B A
a b a
A
SEARCH
CONCATENATE
OVERLAY
SPLI T
sy sy- -subrc subrc sy sy- -fdpos fdpos g/k g/k
A B
A A A A
A B A P
A B P


String processing in ABAP uses the following statements:
SEARCH Search in a string
REPLACE Replace the first occurrence of a string
TRANSLATE Replace all characters
SHI FT Shift a string by one place
CONDENSE Remove spaces
CONCATENATE J oin a sequence of strings
OVERLAY Overlay two strings
SPLI T Split a string
In all string operations, the operands are treated like type C fields, regardless of their actual field
type. They are not converted.
The following string processing statements set the system field SY-SUBRC:
SEARCH, REPLACE, SHIFT <st r i ng1>UP TO <st r i ng2>, CONCATENATE, OVERLAY,
SPLI T. SEARCH also sets the system field SY-FDPOS (offset of the found string).
Apart from SEARCH, all string processing statements differentiate between upper- and lowercase.
The standard function STRLEN returns the occupied length of a string.


(C) SAP AG BC411 16-4
SAP AG
R
Searching in a String
SEARCH <f > FOR <sear chst r i ng>.
SEARCH <i t ab> FOR <sear chst r i ng>.
REPORT sapbc411d_st r i ng_pr ocessi ng.
DATA: st r i ng( 100) TYPE c
VALUE ' Abap obj ect ' .
SEARCH st r i ng FOR ' X' .
SEARCH st r i ng FOR ' Obj ecT' .
SEARCH st r i ng FOR ' . . ' .
SEARCH st r i ng FOR ' OBj *' .
SEARCH st r i ng FOR ' *ect ' .
System field:Sy-fdpos:
A b a p o b e c t j
0 1 2 3 4 5 6 7 8 9 10 11


The system searches the field <f >for the string <sear chst r i ng>. <sear chst r i ng>can be
one of the following:

' st r i ng' A string (trailing spaces are ignored)
'.st r .' Any characters between the periods (spaces included in the search)
'*st r ' A word ending in str, including str itself
' st r *' A word beginning with str, including str itself
The offset of the found string is placed in the system field SY-FDPOS. If the search string is not
found, SY-FDPOS contains the value 0.
You can use SEARCH <i t ab>as well as SEARCH <f>. The system then searches for the search
string within the internal table <i t ab>. This variant sets SY-TABIX with the line index of the line
containing the search string, as well as SY-SUBRC and SY-FDPOS.


(C) SAP AG BC411 16-5
SAP AG
R
Manipulating Strings
B b B p +
B b A p +
A B A P +
REPLACE ' A' WI TH ' B' I NTO <f >.
TRANSLATE <f > USI NG ' AB' .
TRANSLATE <f > TO CASE.
A b A p +
A b A p +
A b A p + CONDENSE <f > [ NO- GAPS] .
A b A p +
A b A p +
b A p + SHI FT <f > [ BY <n> PLACES] [ mode] .
A b A p +
UPPER
LOWER


REPLACE <st r i ng1>WITH <st r i ng2>INTO <f >.
The first occurrence of <st r i ng1>in <f >is replaced by <st r i ng2>. In other words, <f >is
both the source and target field.
TRANSLATE <f >USING <st r i ng>.
All letters in <f >are replaced according to <st r i ng>. <st r i ng>contains the search and
replacement characters in pairs. In the above example, each occurrence of A in <f >is replaced
with B.
TRANSLATE <f > TO UPPER | LOWER CASE.
All lowercase letters in <f>are converted to uppercase (or all uppercase letters are converted to
lowercase).
SHIFT <f >.[BY <n>PLACES] [mode].
<f >is shifted one position to the left. The first letter is no longer displayed, and a trailing space
appears at the right-hand end. SHIFT <f >has the following additions:
... RI GHT. Shifts <f>one position to the right.
... CI RCULAR. Shifts <f >cyclically to the left, that is, the outermost character on the
left-hand side is moved to the right hand end.
... RIGHT CI RCULAR. Shi f t s <f >cyclically to the right.
CONDENSE <f>
Series of spaces are replaced with a single space. If you use the NO-GAPS addition, all spaces are
deleted.
Note: You can delete leading and trailing spaces using SHIFT <f > LEFT DELETI NG
TRAILING SPACE or SHI FT <f > RI GHT DELETI NG TRAI LI NG SPACE.



(C) SAP AG BC411 16-6
SAP AG
R
Joining and Splitting Strings
A P
CONCATENATE <f 1> . . . <f n> I NTO <f >
[ . . . SEPARATED BY <seper at or >] .
A B
OVERLAY <f 1> WI TH <f 2>.
SPLI T <f > AT <separ at or > I NTO
<f 1> . . . <f n>.
TABLE <i t ab>.
A B A P
X B A X
A B A P
A B A P
A B A P
A P
+


CONCATENATE <f 1> . . . <f n> I NTO <f > [ SEPARATED BY <separ at or >] .
The fields <f 1> <f n>are joined together and placed in <f >. Trailing spaces are ignored in the
component fields. You can use the SEPARATED BY <separ at or >addition to separate <f1>
<f n>by the contents of <separ at or >.
OVERLAY <f 1> WI TH <f 2>.
<f 2>overlays <f 1>at all positions where <f 2>contains the value SPACE. <f 2>remains
unchanged.
SPLI T <f > AT <separ at or >INTO <f 1> . . . <f n> | I NTO TABLE <i t ab>.
<f >is split wherever <separ at or >occurs, and placed in the fields <f 1> <f n>or into the
lines of an internal table <i t ab>.


(C) SAP AG BC411 16-7
SAP AG
R
String Comparisons
CA
CS
CP
CO
U/L U/L Blanks Blanks
REPORT sapbc411d_st r i ng_pr ocessi ng.
DATA: st r i ng( 100) TYPE c
VALUE ' Abap Obj ect ' .
I F st r i ng CO ' Obj et c Abap' . "t r ue
I F st r i ng CO ' ABAP ' . "f al se
I F st r i ng CO ' i e' . "f al se
I F st r i ng CA ' i e' . "t r ue
I F st r i ng CA ' o' . "f al se
I F st r i ng CS ' ej ' . "f al se
I F st r i ng CS ' j e' . "t r ue
I F st r i ng CP ' *b*' . "t r ue
I F st r i ng CP ' +b#*' . "f al se
I F st r i ng CP ' A+AP# *' . "t r ue


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 <st r i ng1>operator <st r i ng2>, the operators have the following
meanings:
CO: 'Contains Only' <st r i ng1>only contains characters from <st r i ng2>.
CN: 'Contains Not Only' <st r i ng1>does not contain characters from <st r i ng2>. It is
equivalent to NOT <st r i ng1> CO <st r i ng2>
CA: 'Contains Any' <st r i ng1>contains at least one character from <st r i ng2>
NA: 'Contains Not Any' <st r i ng1>contains no characters from <st r i ng2>
CS: 'Contains String' <st r i ng1>contains the string <string2>
NS: 'Contains Not String' <st r i ng1>does not contain the string <st r i ng2>
CP: 'Contains Pattern' <st r i ng1>contains the pattern <st r i ng2>
NP: 'Contains Not Pattern' <st r i ng1>does not contain the pattern <st r i ng2>
The system field sy-fdpos contains the offset of the character that satisfies the condition, or the
length of <st r i ng1>.
For further details, refer to the online documentation in the ABAP Editor for the relevant statement.


(C) SAP AG BC411 16-8
SAP AG
R
Summary
You can process strings using the
following statements:
SEARCH
REPLACE
TRANSLATE
SHIFT
CONDENSE
CONCATENATE
OVERLAY
SPLIT


SAP AG
R
Bit Processing: Contents
Sets as bit patterns
SET BIT/GET BIT
Assigning values to type X fields
Bit calculations
Bit comparisons



(C) SAP AG BC411 17-2
SAP AG
R
Unit Objectives
to write programs that
Use a data object with type X to represent a
set of n elements
Set and read bits within type X data objects
Perform bit calculations using BIT-NOT,
BIT-AND, BIT-OR, and BIT-XOR
Compare a field of any type with a type X
field using the O, Z, and M operators
At the end of this unit, you will be able



(C) SAP AG BC411 17-3
SAP AG
R
Sets as Bit Patterns
Monday Tuesday WednesdayThursday Friday Saturday Sunday
0 0 1 1 0 0 0 0 0 0 0 0 1 1
Type X Type X
with length smallest number >= (n/8)' with length smallest number >= (n/8)'
Set containing n elements


Bit patterns provide a very efficient way of processing sets.
You can represent a set of n elements using a field with type X, whose length is the integer part of
n/8 (there are 8 bits in a byte) plus one byte for the remaining elements. So, for example, if your set
contains 16 elements, you need a type X field with length 2 bytes, and if it contains 17 elements, the
length of the field would be 3 bytes.
If the
ith
element of the basic set is contained in a set, the corresponding (
ith
) byte of the X field is set
to 1, otherwise to 0.
The
ith
bit (1 <= i <= n) of the X field corresponds to the
jth
bit ( 1 <= j <= 8) in the
kth
byte
of the X:
i =(k-1)*8+j, where k and j can be
calculated from i using the following:
k =(i DIV 8) +1, for i >8
k =(i DIV 8) , for i <=8
j =(i MOD 8)
The 13th bit in the X field is therefore the 5th bit in the second byte. The 17th bit is the first bit
in the third byte.


(C) SAP AG BC411 17-4
SAP AG
R
SET BIT and GET BIT
GET BI T <i > OF <hex> I NTO <g>.
0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 ...
1 2 3 4 5 6 7 8 9 10
SET BI T <i > OF <hex> [ TO <f >] .
DATA: hex( 2) TYPE x, g TYPE i ,
val TYPE i VALUE 1.
SET BI T 4 OF hex. WRI TE / hex.
SET BI T 7 OF hex TO val . WRI TE / hex.
GET BI T 4 OF hex I NTO g. WRI TE / g.
GET BI T 7 OF hex I NTO g. WRI TE / g.
0 0
16


SET BI T <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> I NTO <g>retrieves the value of the
ith
bit in the X field <hex>.


(C) SAP AG BC411 17-5
SAP AG
R
Assigning Values to X Fields
DATA: hex1( 2) TYPE x,
hex2( 2) TYPE x VALUE ,
c( 4) TYPE c VALUE ,
i TYPE i VALUE .
hex1 = hex2. WRI TE / hex1.
hex1 = c. WRI TE / hex1.
hex1 = i . WRI TE / hex1.
' 1A4F'
' 1A4F'
' 6735'
0 0
1
2
15
0 0
2
2
14
0 0
3
2
13
1 1
4
2
12
4096
1 1
5
2
11
2048
0 0
6
2
10
1 1
7
2
9
512
0 0
8
2
8
0 0
9
2
7
1 1
10
2
6
64
0 0
11
2
5
0 0
12
2
4
1 1
13
2
3
8
1 1
14
2
2
4
1 1
15
2
1
2
1 1
16
2
0
1
1 1
x
A A 4 4 F F
6735
Bit No.
Value


When you assign a type C field to a type X field, ABAP interprets the C field as a hexadecimal
value. One way of making use of this is to specify a text literal with hexadecimal contents for the C
field, for example, VALUE '1A4F'.
When you assign a type I field to a type X field, the decimal value of the I field is converted into its
corresponding hexadecimal value (6735 decimal equals '1A4F' hex). Caution: The internal
representation of integers is platform-dependent. The sequence of the bits in the above example may
be reversed. In other words, programming in the above manner may mean that your program will not
run on all platforms.
Caution: You must write hexadecimal constants in uppercase. Lowercase letters are interpreted as
zeros. For example writing DATA hex2(2) TYPE x VALUE '1a4F' would produce an entirely
different result to the declaration in the above example.



(C) SAP AG BC411 17-6
SAP AG
R
Bit Calculations
1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0
1 2 3 4 5 6 7 8
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8
<hex1>
<hex2>
<bi t _expr essi on>
BIT-NOT <hex2>
<hex1> BIT-AND <hex2>
<hex1> BIT-OR <hex2>
<hex1> BIT-XOR <hex2>
COMPUTE <hex> = . <bi t _expr essi on>
0 1 1 0 1 1 0 1 0 1 1 0 1 1 0 1
1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0
1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 0
0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0


The statement COMPUTE <hex> = <bi t expr essi on>analyzes the but expression <bi t
expr essi on>and places the result into the field <hex>. You can use the four bit operations
BI T- NOT, BI T- AND, BI T- XOR, and BI T- OR. The operands are linked bit by bit according to
the table below.
The priority is: BI T- NOT before BI T- AND before BI T- XOR before BI T- OR. Parenthetical
expressions are allowed.
The operands in <bi t expr essi on>and the result field must all be of type X.
Link table:

x y BI T- NOT x x BI T- AND y x BI T- XOR y x BI T- OR y
__________________________________________________________
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 0 1
If the operands are not the same length, they are converted to the length of the result field using
MOVE X TO X logic. This means that operands shorter than the result field are filled with hex 0 at
their right-hand end, and those longer than the result field are truncated at the right-hand end.


(C) SAP AG BC411 17-7
SAP AG
R
Bit Comparisons
1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0
1 2 3 4 5 6 7 8
1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8
O
<f > Z <hex>
M
DATA: hex1( 1) TYPE x, hex2( 1) TYPE x.
I F hex1 O hex2. "f al se
I F hex1 Z hex2. "f al se
I F hex1 M hex2. "t r ue
<f>
<hex>
Bit mask


You can test a field of any type against a type X field <hex>using the O, Z, and M operators.
<hex>is interpreted as a bit mask. The comparison only applies to the bits in <f >that have the
value 1 in <hex>. If <f >is shorter than <hex>, it is implicitly filled with null bytes.
The relational operators O, Z, and M have the following meanings:

O (One) The expression is true if all bits in <hex>with the value 1 also have the value 1 in
<f >.
Z (Zero) The expression is true if all bits in <hex>with the value 1 have the value 0 in <f >.
M (Mixed) The expression is true if all bits in <hex>with the value 1 have at least one 1 and at
least
one 0 in <f >.
You can use bit comparisons to check whether a set contains another set. To do this, you specify a
pattern containing the set you want to search for, and use the bit comparison statements to check
whether it belongs to the other set.



(C) SAP AG BC411 17-8
SAP AG
R
Example: Representing Flights with an X Field
REPORT sapbc411d_bi t _pr ocessi ng.
TYPES: week( 1) TYPE x.
DATA: f l i ght _t ab TYPE TABLE OF week
WI TH HEADER LI NE,
ever y_week TYPE x VALUE ' FE' ,
one_week TYPE x.
* f i l l f l i ght _t ab wi t h bi t pat t er n
* cal cul at e ever y_week and one_week
LOOP AT f l i ght _t ab.
ever y_week = f l i ght _t ab BI T- AND ever y_week.
one_week = f l i ght _t ab BI T- OR one_week.
ENDLOOP.
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0
1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 0
0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0
1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 0
0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0
1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 0
0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0
1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 0
0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 0
f l i ght _t ab
On which day of the week is there a
flight every week:
0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0
1 1 1 1 0 1 1 0 1 1 1 1 0 1 1 0
one_week
ever y_week
On which days of the week is there flight
in at least one week:


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 ( f l i ght _t ab)
with line type X(1).
The variable ever y_week is initialized with ' FE' ( 1111 1110). In other words, the relevant
bits (one to seven) are all set. Using BI T- AND to compare ever y_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 BI T- OR to
compare one_week with each line of the internal table, it is possible to find out the days of the
week on which there is a flight in at least one week of the year, since the relevant bit changes from 9
to 1 if there is a flight on the corresponding day of a given week.


(C) SAP AG BC411 17-9
SAP AG
R
Summary
You can use the data type X to represent a basic
set of n elements in a single data object.
You can use SET BIT and GET BIT to set or read a
single bit of a type X field.
BIT-NOT, BIT-AND, BIT-OR, and BIT-XOR allow you
to perform calculations with X fields using normal
boolean operations.
O, Z, and M are relational operators for X fields. You
can use them to compare the state of a bit in a field
of any type with a bit in a bit mask.


SAP AG
R
Data Clusters: Contents
EXPORT
IMPORT
DELETE



(C) SAP AG BC411 18-2
SAP AG
R
Unit Objectives
At the end of this unit, you will be able to
store data objects under an ID
In a cluster database
In the cross-transaction application buffer
(shared buffer)
In ABAP memory
You will be able to use clusters in your
programs, and be aware of their advantages
and disadvantages.



(C) SAP AG BC411 18-3
SAP AG
R
Data Clusters: Overview
KTNRA NAME1 TDM
Data cluster:
DATABASE
A1 A1
... ...
An An
Export Import
ABAP memory Shared buffer
Fields
Structured
fields
Internal
tables


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, I MPORT, and DELETE. You can store them in
ABAP memory, in a cluster database, or in the shared buffer.
The following pages explain more about ABAP memory, cluster databases, and the shared buffer.


(C) SAP AG BC411 18-4
SAP AG
R
REPORT xxx
TABLES i ndx.
EXPORT optional
<f i el d 1> FROM <f i el d a>
<f i el d 2> FROM <f i el d b>
. .
. .
<st r uct ur e 1> FROM <st r uct ur e a>
. .
. .
<i t ab 1> FROM <i t ab a>
. .
. .
TO DATABASE i ndx( <ar >)
I D <i d>.
EXPORT <name> FROM <obj >
[ <obj >]
TO DATABASE <dbt ab>( <ar >) I D <i d>.
Syntax: EXPORT to a Cluster Database


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 I D.
To export data, you need a cluster database. The table INDX is an all-purpose cluster database.
Cluster databases should be created as transparent tables in the ABAP Dictionary, and must have a
standard structure. For further information, refer to the online documentation in the ABAP Editor for
the EXPORT statement.
In the EXPORT statement, you list the data objects that belong to your cluster.
To export data, specify the name of the cluster database and the work area. You identify the cluster
itself by its cluster ID. If you want a data object in the cluster to have a different name from that in
the program, use the optional addition FROM. You can specify the data object in the list in any
order. There is no write-protection when you export data - existing clusters are automatically
overwritten in a new EXPORT.
The data is stored in compressed form in the cluster database.
At the start of your program, declare a work area for your cluster database using the TABLES
statement.
Caution: You cannot export the header line of an internal table. The EXPORT statement always
applies to the entire table contents.



(C) SAP AG BC411 18-5
SAP AG
R
REPORT xxx
TABLES i ndx.
I MPORT optional
<f i el d 1> TO <f i el d a>
<f i el d 2> TO <f i el d b>
. .
. .
<st r uct ur e 1> TO <st r uct ur e a>
. .
. .
<i t ab 1> TO <i t ab a>
. .
FROM DATABASE i ndx( <ar >)
I D<i d>.
I MPORT <name TO <obj >
[ <obj >]
FROM DATABASE <dbt ab>( <ar >) I D <i d>.
DELETE FROM DATABASE I NDX( <ar >)
I D<i d>.
Syntax: IMPORT and DELETE


When you import data, you can list the data objects in any order in the IMPORT statement. You do
not need to import all of the data objects from your cluster. If you want the data objects in the
program to have different names to those used in the cluster, you can use the optional TO addition.
The IMPORT statement sets the return code field SY-SUBRC, which applies to the entire cluster,
not to individual data objects. SY-SUBRC is unequal to zero if the cluster does not exist.
The structure of the fields, structures, and internal tables that you want to import must correspond to
the structure of the data objects in the database, otherwise a runtime error occurs. Furthermore, you
must import the objects using the same names under which you exported them. If the cluster exists,
the return code is set to zero, whether or not objects have been imported.
Caution: The IMPORT statement always imports the body of an internal table. This means that the
header line of the table remains unchanged by the import.
The DELETE statement deletes the entire cluster and sets the return code field SY-SUBRC. You
cannot delete an individual data object within a cluster.



(C) SAP AG BC411 18-6
SAP AG
R
Key of the Database Table INDX
Cluster area: a1 INDX INDX
1 - 3 4 - 5 6 - 27 28 -31 Position
Client Area Cluster ID Next entry Contents
001 a1 E105 0001 Example
1 - 3 4 - 5 6 - 27 28 -31 Position
Client Area Cluster ID Next entry Contents
001 a1 E105 0001 Example
001 a1 E10 50000
f1 f2 f3
I1
Next entry: 0000
Next entry: 0001
Next entry: 0002
Next entry: 0003
001 a1 E10 50003
l1 Fortsetzg
l2 t1 . . .
001 a1 E10 50002
l2 t1 . . .
001 a1 E10 50001
l1 Continued
l2 I3 . . .
Key
Contents


The database table INDX is an example of a table in which you can store data clusters. In your
system, it is installed with a standard key length of 31 bytes.
You can display the structure of the table from the online documentation in the ABAP Editor by
entering the table structure INDX. The key consists of client, work area, cluster ID, and next entry
number. The cluster ID has a default length of 22 bytes, but it can have any length.
For large data clusters, the runtime system automatically appends new entries with the same length.


(C) SAP AG BC411 18-7
SAP AG
R
ABAP Cluster Databases
3 2 n 4 m 2
MANDT RELID SRTF2 CLUSTR CLUSTD CLUSTD
Char Char Char INT4 INT2 LRAW LRAW
Generated, based
on the length for the
cluster table
Created structure
Structure:
Length
Name
Type
Client Work
area
Cluster ID Next
entry
counter
Your
own
fields
(optional)
Length Data field
INDX PERG RETL MLTS
. . .
Examples:
Key fields


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 RELI D, 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 I MPORT.
The field names for the cluster ID and the user-defined fields can be chosen freely. The other fields
must be named as above.
The length of the part of the table used for the data cluster is the total length of the structure minus
the length of the first six fields.


(C) SAP AG BC411 18-8
SAP AG
R
Example: Catalog for INDX
REPORT sapbc411d_cl ust er cat al ogue.
TABLES i ndx.
SELECT- OPTI ONS:
ar ea FOR i ndx- r el i d,
cl st r _i d FOR i ndx- sr t f d.
START- OF- SELECTI ON.
SELECT DI STI NCT r el i d sr t f d aedat user a pgmi d
I NTO ( i ndx- r el i d, i ndx- sr t f d, i ndx- aedat ,
i ndx- user a, i ndx- pgmi d) FROM i ndx
WHERE r el i d I N ar ea
AND sr t f d I N cl st r _i d.
* AND sr t f 2 = 0.
WRI TE: / i ndx- r el i d,
i ndx- sr t f d,
i ndx- aedat DD/ MM/ YYYY,
i ndx- user a,
i ndx- pgmi d.
ENDSELECT.
REPORT sapbc411d_cl ust er cat al ogue.
TABLES i ndx.
SELECT- OPTI ONS:
ar ea FOR i ndx- r el i d,
cl st r _i d FOR i ndx- sr t f d.
START- OF- SELECTI ON.
SELECT DI STI NCT r el i d sr t f d aedat user a pgmi d
I NTO ( i ndx- r el i d, i ndx- sr t f d, i ndx- aedat ,
i ndx- user a, i ndx- pgmi d) FROM i ndx
WHERE r el i d I N ar ea
AND sr t f d I N cl st r _i d.
* AND sr t f 2 = 0.
WRI TE: / i ndx- r el i d,
i ndx- sr t f d,
i ndx- aedat DD/ MM/ YYYY,
i ndx- user a,
i ndx- pgmi d.
ENDSELECT.


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 I NDX- AEDAT) .


(C) SAP AG BC411 18-9
SAP AG
R
ABAP Memory - Overview: Communication
Between Internal Sessions
External session 1
Internal session 1
A
B
A
P

m
e
m
o
r
y
A
B
A
P

m
e
m
o
r
y
Internal session 2
External session 2
Internal session 1
Program 3 Program 3
A
B
A
P

m
e
m
o
r
y
A
B
A
P

m
e
m
o
r
y
Internal session 2
Export
Import
Export
Import
R/3 terminal session
Roll area
Roll area
Roll area
Roll area
Program 4 Program 4
Program 1 Program 1
Program 2 Program 2


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 TRANSACTI ON), a dialog
module ( CALL DI ALOG) or a report ( SUBMI TAND 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 I MPORT FROM MEMORY to read it.


(C) SAP AG BC411 18-10
SAP AG
R
ABAP/4
Transporting Data Between Programs
(ABAP Memory)
ABAP memory
MYID
SPFLI SPFLI
IT_SPFLI IT_SPFLI
PROGRAM p1 . . . .
. . .
DATA: p1_spf l i LI KE spf l i ,
i t _spf l i LI KE spf l i
OCCURS 0.
. . .
SUBMI T p2.
I MPORT
spf l i TO p1_spf l i
i t _spf l i
FROM MEMORY I D ' MYI D' .
PROGRAM p2 . . . .
. . .
DATA: p2_spf l i LI KE spf l i ,
i t _spf l i LI KE spf l i
OCCURS 0.
. . .
I MPORT
spf l i TO p2_spf l i
i t _spf l i
FROM MEMORY I D ' MYI D' .


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 TRANSACTI ON, CALL
DI ALOG, SUBMI TAND 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 I MPORTFROM 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 I D <i d>using the FREE MEMORY I D <i d>statement (analogous to FREE
<i t ab>) .


(C) SAP AG BC411 18-11
SAP AG
R
Application server 1
Program 1 Program 1
S
h
a
r
e
d

b
u
f
f
e
r
Program 2 Program 2
Export
Import
Export
Import
Shared Buffer - Overview


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 <dbt ab>( ar ) I D <i d>and
- I MPORT . . . FROM SHARED BUFFER <dbt ab>( ar ) I D <i d>
and delete data in the buffer using the statement
- DELETE FROM SHARED BUFFER <dbt ab>( ar ) I D <i d>
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, I MPORT, and DELETE statements, (database table),
must have a standardized structure.


(C) SAP AG BC411 18-12
SAP AG
R
Cl ust er t abl e Cl ust er t abl e Tr anspar ent t abl e Tr anspar ent t abl e
Onl y contains data within the
cluster
Little access for large amounts of
data
Heterogenous data (field,
structured fields, internal tables)
Flexible technique
Not possible to link data
Access requires cluster ID and
area
Access only returns one cluster
In relational database
Multiple access, since the data is
stored in different tables
Data can be linked and evaluated
Select with any number of logical
conditions
Cluster Tables and Transparent Tables


The cluster database contains the data in the required form. The internal administration of the cluster
table means that you can read large quantities of data with relatively few database accesses.
In transparent tables, the standardization means that the data has to be selected from several tables,
requiring more access. However, this can be made more efficient by using joins (from Release 3.1)
in ABAP Open SQL (refer to the unit about ABAP Open SQL). The advantage of transparent tables
is that you can read single obejcts from different tables and relate them to other objects. Compare
this with cluster tables, where you can only read the data of a single cluster and cannot link this data
to that in other clusters.
To access cluster data, you must know the cluster ID and the work area. Furthermore, the access can
only return the data for a single cluster ID (where a SELECT loop could return more than one
cluster). In transparent tables, you can retrieve data based on any logical expression.


(C) SAP AG BC411 18-13
SAP AG
R
Summary
In this unit, you have learned how to store
data objects under an ID:
In a cluster table
In ABAP memory
In the shared bufffer


SAP AG
R
Exercises
Note:
There may not be sufficient time to work
through all the exercises during the course.
The exercises marked Optional should be seen
as supplementary examples that can be used,
time permitting, during the course. Attendees
can also use these exercises after the course,
to consolidate what they have learned.



(C) SAP AG BC411 19-2
Data used in the exercises:

Data from database tables SGEOCI TY, SPFLI , SFLI GHT, SBOOK
All of the Repository objects used in this course can be found in development
class SAPBC411. This development class is supplied to customers. You
should find it in your I DES system.
Names of model solutions
Program name
SAPBC411S_LIST

SAPBC411S_TYPE

SAPBC411S_ASSIGN

SAPBC411S_KEYTAB_DEFINITION
SAPBC411S_KEYTAB_FILL
SAPBC411S_KEYTAB_READ
SAPBC411S_TESTFRAME_ITABS

SAPBC411S_OO_CREATE_CLASS
SAPBC411S_OO_OBJ ECT_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-3

SAPBC411S_STRING_BIT_OPERATION


(C) SAP AG BC411 19-4



Unit: Development process and tools
Exercise 1: Correcting the errors in a program and
runtime analysis
Theme: Development process





1.1 Description of program:
The program displays a selection screen containing a default date range of 01.01.1900 to
01.01.2000, and a parameter in which the user can specify a column of a structure,
defined in the program. The program then displays a list of all flights within the specified
period. The list is sorted by the column chosen by the user on the selection screen.
1.2 Copy the template program SAPBC411T_LIST and all of its includes to program
ZBC411_##_LIST. Rename the includes with appropriate names.
1.3 Edit the three includes (<prefix>TOP, <prefix>E01, and <prefix>F01) and correct the
syntax errors and warnings. Edit the main program to remove the syntax errors from the
entire program.
1.4 Check the program using the extended program check and correct any errors and
warnings.
1.5 Perform a runtime analysis for your program. Find out why the runtime is so high and
correct the cause.

(C) SAP AG BC411 19-5

Object Name / Description
Copy program SAPBC411T_List
Create program ZBC411_##_List



Activities




In the ABAP Editor settings, select the Key words large option. This
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.
Tips &
tricks






(C) SAP AG BC411 19-6



Unit: Types
Exercise 1: Adjusting data types
Theme: Data conversions and runtime





1.5 Copy the template program SAPBC411T_TYPE to ZBC411_##_TYPE. The program
calculates the factorial of a number n.
1.6 Use the runtime analysis (Transaction SE30) to check the program for unnecessary type
conversions. Eliminate these by using a single data type throughout the program.


Object Name / Description
Template program SAPBC411T_TYPE
Target program ZBC411_##_TYPE

Activities





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.
Tips & Tricks




(C) SAP AG BC411 19-7



Unit: Field symbols
Exercise 1: Assigning an object to a field symbol
Theme: Different ways of assigning field symbols using the
ASSI GN statement





1.1 Copy the template program SAPBC411T_ASSIGN to ZBC411_##_ASSIGN. The
program reads entries from table SFLIGHT for a given airline, and displays the column
of the table specified in the COMPONO parameter. There is an error in the program
that prevents it from running properly.
1.2 Correct the error.
1.3 The required column is displayed with length 30. Change the program so that the
minimum length is displayed, that is, the contents of the field without any trailing spaces.
1.4 Change the program so that the user can enter the component name instead of the
component number.

1.5 a) For the first solution, use
ASSIGN COMPONENT
Optional:
b) Create a second solution that does not use the
ASSIGN COMPONENT statement.

(C) SAP AG BC411 19-8

Object Name / Description
Template program SAPBC411T_ASSIGN
Activities


Target program ZBC411_##_ASSIGN




(C) SAP AG BC411 19-9



Unit: I nternal tables
Exercise 1:
Theme: Defining internal tables

1.1 Write a program that defines an internal table of each of the three
table types standard, sorted, and hashed.

1.2 Start by defining a line type. This should have the following
structure: TYPES: a TYPE i,
b(1000) TYPE c,
d TYPE p.

1.3 Define the standard and sorted tables with a non-unique key, and the
hashed table with a unique key. The key field in all three cases should
be field a. Define all of the tables without header lines.

Object Name / Description
Program ZBC411_##_itab




Activities






Tips &
Tricks




(C) SAP AG BC411 19-10



Unit: I nternal tables
Exercise 2:
Theme: Filling internal tables

2.1 Write a program that fills the internal tables that you defined in
exercise 1.

2.2 Do this by defining a parameter in which you can define the
number of entries that you want to add to the table. Use the
parameter to number key field a in ascending order. You can use
any values for the two other fields.

Object Name / Description
Program ZBC411_##_itab




Activities




You can fill all three table types using the statement INSERT <wa>INTO
TABLE <table>.

Tips &
Tricks




(C) SAP AG BC411 19-11



Unit: I nternal tables
Exercise 3: Accessing a single line of an internal table
Theme: Runtime of single line access


3.1 Write a program to read a single line from each of the internal
tables that you filled in exercise 2.

3.2 In your program, define a parameter that you can use to specify the
key of the entry you want to read.

3.3 Optional: Measure the runtime required to read the data for the
different table types by embedding your program in the test
framework program.

3.4 Optional: Copy the program SAPBC411T_TESTFRAME to the
program ZBC411T_##_TESTFRAME_ITAB and copy the
corresponding lines of the program ZBC411_##_ITAB into the
form routines f1, f2, and f3. Form routine is an empty routine to
allow the program to measure the runtime of a subroutine call.
Place the data definitions from your program in the TOP include of
the measurement program.

Object Name / Description
Program ZBC411_##_itab
Program template for runtime
measurement
ZBC411T_testframe
Optional: Your program for
measuring the runtime (copied from
template)
ZBC411_##_testframe


Activities




Tips &
You can read from all three table types using the statement
READ TABLE <table>WITH TABLE KEY a =<parameter>INTO wa.

(C) SAP AG BC411 19-12

Tricks






(C) SAP AG BC411 19-13



Unit: ABAP Objects
Exercise 1: Defining and implementing classes
Theme: Classes


1.1 Write a program to create the classes C_SHIP and S_TRUCK
1.2 You should both define and implement the classes. At this stage,
create only the private and class attributes (you will add methods
and other features in subsequent exercises). Both classes should
have the attributes listed below.

1.3 Define the attribute INST_ID in the classes as a class attribute. This
will act as a counter for the various instances.
1.4 Define the attribute ID for the number of an instance and the
attribute SHIP_SPEED or TRUCK_SPEED for the current speed.

1.5 Create the following objects for the program:

Object Name / Description
Program ZBC411_##_OO_create_class
Class C_SHIP: Ship class
Class C_TRUCK: Truck class
Attribute SHIP_SPEED, TRUCK_SPEED: speed
Type: integer
Attribute MAX_SPEED: maximum speed
Type: integer
Attribute ID: Identity
Type: integer
Activities


Class attribute INST_ID: Instance ID
Type: integer


(C) SAP AG BC411 19-14



Unit: ABAP Objects
Exercise 2: Defining, implementing, and calling methods
Theme: Methods


2.1 Extend the program you wrote in exercise 1 by defining and
implementing methods.
2.2 Both classes should have the methods CONSTRUCTOR,
SPEED_UP, STOP, and WRITE. None of the methods has an
interface.
2.3 Define the instances OSHIP and OTRUCK, and two internal tables
that can store the instances of the classes you have defined.
2.4 Using a DO loop for each class, create two instances of each of the
classes C_TRUCK and C_SHIP and add them to the appropriate
internal table.
2.5 Use a LOOP statement to process the entries of each internal table.
Within the loop, call the methods SPEED_UP and WRITE for the
corresponding instances.




(C) SAP AG BC411 19-15

2.6 Create the following objects for the program:

Object Name / Description
Program ZBC411_##_OO_object_method
Method CONSTRUCTOR: Increase the class
attribute INST_ID by 1, assign the value
to the ID attribute, and set the
MAX_SPEED attribute to 30 for class
C_SHIP and to 140 for class C_TRUCK.
Method SPEED_UP: Check that SPEED is less
than MAX_SPEED, and then increase
the speed by 10 for C_SHIP or by 20 for
C_TRUCK.
Method STOP: Set SPEED to 0.
Method WRITE: Display the following:
'TRUCK- ID =<value>
SPEED =<value>'
Activities


Instance OSHIP
OTRUCK
Internal table SHIP_TAB
TRUCK_TAB
with type REF TO class
C_SHIP or C_TRUCK

Tips & Tricks

Do not forget to insert the START-OF-SELECTION statement at the
appropriate point.


(C) SAP AG BC411 19-16



Unit: ABAP Objects
Exercise 3: Defining, implementing, and using interfaces
Theme: I nterfaces

3.1 Extend your program from exercise 2 by enclosing repetitively-
used logic in an interface that presents a common point of contact
for both classes. Define and implement the interface I_VEHICLE.
3.2 The methods SPEED_UP, STOP, and WRITE, and the attributes
ID and MAX_SPEED should now be defined in the interface, and
implemented in the classes C_SHIP and C_TRUCK. The methods
have no interface.
3.3 Implement the CONSTRUCTOR method so that the interface
attribute ID is supplied with the value of the class attribute
INST_ID. You will also need to adjust the interface attribute
MAX_SPEED accordingly.
3.4 Change the main program so that the two internal tables are replaced
by a single table veh_tab that can contain references to the interface.
3.5 Define an interface reference variable IVEHICLE.
3.6 In a DO lop, fill the internal table VEH_TAB and call the interface
methods SPEED_UP, WRITE, STOP, and WRITE.


(C) SAP AG BC411 19-17

Create the following objects in your program:

Object Name / Description
Program ZBC411_##_OO_interfaces
Interface I_VEHICLE: Methods SPEED_UP,
STOP, WRITE
Attributes: ID and MAX_SPEED.
Method CONSTRUCTOR: Supply values to the
interface attributes ID and
MAX_SPEED.
Attribute Define INST_ID as a class attribute.
Interface method SPEED_UP: Change the name of the
method and its attributes as required. Its
function does not change.
Interface method STOP: Change the name of the method
and its attributes as required. Its function
does not change.
Method WRITE: Change the name of the method
and attributes as required. Its function
does not change.
Activities


Internal table VEH_TAB: Replaces the two previous
internal tables. Line type: TYPE REF TO
I_VEHICLE.
Interface reference variable IVEHICLE Type: TYPE REF TO
I_VEHICLE.
DO loops APPEND to the internal table
LOOP Call the interface methods
SPEED_UP, WRITE, STOP, WRITE


(C) SAP AG BC411 19-18



Unit: ABAP Objects
Exercise 4: Defining, calling, handling, and registering
events
Theme: Events


4.1 Copy the template program SAPBC411T_OO_EVENTS to
ZBC411_##_OO_EVENTS and include event handling in it. The
program allows you to create instances of the classes C_SHIP and
C_TRUCK using pushbuttons. You can also call the methods
SPEED_UP, WRITE and STOP using pushbuttons if the cursor is
on an existing object.
4.2 Familiarize yourself with the program SAPBC411S_OO_EVENTS.
4.3 Insert two events. 1.) The interface event SPEED_CHANGE with
export parameter NEW_SPEED and 2.) the class event
BUTTON_CLICKED with export parameter FCODE.
4.4 The event SPEED_CHANGE should be triggered by the interface
methods SPEED_UP and STOP and be handled by the handler
method LIST_CHANGE in the new class C_LIST. The event
BUTTON_CLICKED should be triggered by the class method
USER_ACTION of the new class STATUS and be handled by the
handler method FCODE_HANDLER in class C_LIST.
4.5 Use SET HANDLER to register both handler methods.
4.6 Make the necessary changes at the appropriate points in the
program code.

(C) SAP AG BC411 19-19

4.7 Create the following objects for the program:

Object Name / Description
Program template SAPBC411T_OO_events
Target program ZBC411_##_OO_events
Interface event SPEED_CHANGE
Exporting parameter NEW_SPEED type
I, passed by value
Class event BUTTON_CLICKED
Exporting parameter
FCODE LIKE SY-UCOMM, passed by
value
Handler method FCODE_HANDLER
in the PUBLIC SECTION of class
C_LIST. Define this method for the
event BUTTON_CLICKED of class
status, receiving the import parameter
FCODE.
Handler method LIST_CHANGE
in the PUBLIC SECTION of class
C_LIST. Define this method for the
event SPEED_CHANGE of interface
I_VEHICLE, receiving the import
parameter NEW_SPEED.
Trigger event The interface methods SPEED_UP and
STOP should call the event
SPEED_CHANGE in all classes using
the RAISE EVENT statement and
passing the export parameter. The
parameter must be supplies with the
value of the corresponding actual
parameter.
Trigger event The class event BUTTON_CLICKED
should be triggered by the method
USER_ACTION in class STATUS. Its
export parameter is FCODE, which is set
when the user chooses a pushbutton
(FCODE =SY-UCOMM).
Activities


Register events In the main program, register the handler
methods FCODE_HANDLER and
LIST_CHANGE. Register
LIST_CHANGE with the addition FOR
ALL INSTANCES so that it applies to
all instances of the class C_LIST.

(C) SAP AG BC411 19-20


(C) SAP AG BC411 19-21



Unit: ABAP Objects
Exercise 5: Defining, calling, handling, and registering
events
Theme: Logging with events



5.1 Extend your program ZBC411_##_OO_EVENTS or copy the model solution
SAPBC411S_OO_EVENTS to ZBC411_##_OO_EVENTS and include more event
handling. Create a log of the functions that the user has chosen and display a list the first
time the user chooses Cancel. The program should not end until the user presses Cancel a
second time. Familiarize yourself with program
SAPBC411S_OO_EVENT_PROTOKOLL.
5.2 You need to extend the existing program in three places. 1.) Define and implement a class
C_PROTOKOLL with the public class methods FCODE_HANDLER and
WRITE_PROTOCOLL, the public static attribute PROTOCOLL_WRITTEN, and the
private static attribute FCODE_TAB, an internal table for storing the function codes
triggered by the user.
5.3 The method FCODE_HANDLER is the handler method for the event
BUTTON_CLICKED in class STATUS. It imports the function code from the variable
FCODE.
5.4 2.) In the method FCODE_HANDLER of class C_LIST, you need to find out whether the
static variable PROTOCOLL_WRITTEN =1 when the user chooses CANCEL. If it is,
leave the program. If not, call the static method WRITE_PROTOCOLL of the class
C_PROTOCOLL, and stop the CASE statement with the STOP statement.
5.5 In the method WRITE_PROTOCOLL, loop through the internal table FCODE_TAB and
display the contents. Afterwards, set the attribute PROTOCOLL_WRITTEN to 1.
5.6 Include another SET HANDLER statement to register the method FCODE_HANDLER
for the class C_PROTOKOLL.

(C) SAP AG BC411 19-22

5.7 Create the following objects for the program:


Object Name / Description
Program template SAPBC411S_OO_events or your program
ZBC411_##_OO_events

Define and implement a class C_PROTOCOLL
Class definition
Public section: class methods


Static attribute
FCODE_HANDLER for the event
BUTTON_CLICKED of class STATUS.
Importing parameter FCODE
WRITE_PROTOCOLL, no interface
PROTOCOLL_WRITTEN TYPE i
READ ONLY.
Private section: Internal table FCODE_TAB LIKE sy-ucomm
OCCURS 0.
Class implementation FCODE_HANDLER should inserts
FCODE into the internal table
FCODE_TAB.
WRITE_PROTOCOLL: Loop through the
internal table FCODE_TAB into a local
variable within the method and display the
contents. Then set the static variable
PROTOCOLL_WRITTEN to 1.
Handle event The handler method FCODE_HANDLER
in class C_LIST needs to be changed for
the CANCEL function so that you leave
the program if the static variable
PROTOCOLL_WRITTEN has the value 1
(C_PROTOCOLL=>
PROTOCOLL_WRITTEN =1),
otherwise, you call the static method
WRITE_PROTOCOLL (CALL
METHOD C_PROTOCOLL=>
WRITE_PRTOCOLL) and then leave the
CASE statement with the STOP
statement.
Activities


Register event In the main program, register the handler
method FCODE_HANDLER.
(SET HANDLER
C_PROTOCOLL=>FCODE_HANDLER)


(C) SAP AG BC411 19-23


(C) SAP AG BC411 19-24



Unit: Contexts
Exercise 1: Creating a context to calculate the distance
between two cities
Theme: Creating contexts

1.7 Create a context to calculate the distance between two cities. It
should consist of the following modules:
1.8 Context C_GEOGR_INFO and the function module
CONTEXT_DEMO_COMPUTE_DISTANCE, which calculates
the distance.

It is your task to create a general context for an application that allows a
program to efficiently calculate the distance between two cities.



Object Name / Description
Context ZBC411_##_C_Geogr_Dist




Activities




1.3 Create the context and test it within the Context Builder.

Tips &
Tricks




(C) SAP AG BC411 19-25



Unit: Contexts
Exercise 2: Using the context to calculate the distance
between two cities
Theme: Using contexts in programs

2.1 Write a program that uses the context ZBC411_##_C_Geogr_Dist to
calculate the distance between two cities.
2.2 To do this, define a context instance in your program and use the
SUPPLY statement to pass values for the key fields to it. Calculate
the distance between NEW YORK and FRANKFURT, retrieve it
from the context using the DEMAND statement, and display it on a
list. Leave error handling to the system.
1.


Object Name / Description
Program ZBC411_##_Geogr_Dist




Activities






Tips &
Tricks





(C) SAP AG BC411 19-26



Unit: ABAP Open SQL
Exercise 1: Read all flights for one year
Theme: Keeping the result set small

1.1 Write a program that displays all flights for a given year from the
table SFLIGHT. Make it possible for the user to enter the year in a
PARAMETER. Read the appropriate entries from SFLIGHT and
display any of their fields in a list.

Object Name / Description
Program ZBC411_##_Flights_Of_One_Year




Activities




1.2 Once you have written the program, run the SQL trace on it to measure your database
access times.



Tips &
Tricks




(C) SAP AG BC411 19-27



Unit: ABAP Open SQL
Exercise 2: Reading the first 10 flights
Theme: Minimizing the amount of data transferred

2.3 Write a program that reads the first ten entries for airline LH from
table SFLIGHT (the order in which they occur is not important).
Display the following fields in a list:
SFLIGHT-CARRID
SFLIGHT-CONNID
SFLIGHT-FLDATE
SFLIGHT-PRICE
SFLIGHT-CURRENCY

Object Name / Description
Program ZBC411_##_Read_10_Flights




Activities




2.2 Once you have written the program, run the SQL trace on it to measure your database
access times.



Tips &
Tricks





Unit: ABAP Open SQL
Exercise 3: Reading data and calculating the sum
Theme: Minimizing the amount of data transferred

(C) SAP AG BC411 19-28

3.2 Write a program to calculate the booking revenue for 1998 from
field SBOOK-LOCCURAM of table SBOOK.

3.5 You work for a travel agency, and have to write a program that
produces the list described above. The list should have the
following format:
Airline Flight No. Amount in local currency
----------------------------------------------------------------------
AA 0017 4590
AA 0026 8730


Object Name / Description
Program ZBC411_##_Cumulate_Loccuram




Activities




3.6 Once you have written the program, run the SQL trace on it to measure your database
access times.


Tips &
Tricks






Unit: ABAP Open SQL
Exercise 4: Reading from more than one table
Theme: Minimizing the number of transfers

(C) SAP AG BC411 19-29

4.1 Write a program that displays the all not overbooked flights of the
year 1998 between Frankfurt and New York.

4.2 You work for a travel agency, and have to write a program that
produces the list described above. The list should display the fields
CARRID, CONNID, and FLDATE.
Carrier Flight number Flight date
------------------------------------------------------
AA 0017 12.29.1998
LH 0400 12.21.1998

Object Name / Description
Program ZBC411_##_Sel_Sflight_Sbook




Activities




4.3 Once you have written the program, run the SQL trace on it to measure your database
access times.



Tips &
Tricks






Unit: ABAP Open SQL
Exercise 5: Reading high and low values
Theme: Minimizing the number of transfers

(C) SAP AG BC411 19-30

5.1 Write a program that finds and displays, for each flight in
SFLIGHT, the date with the most seats booked (field SEATSOCC).

5.2 You work for a travel agency, and have to write a program that
produces the list described above. The list should display the fields
CARRID, CONNID, and FLDATE, and the maximum value of the
field SEATSOCC.

5.3 Note: It is not asked for one flight with the most flight, but for all
flights that eventually contain the maximum value.

Object Name / Description
Program ZBC411_##_Sel_Max_Seatsocc




Activities




5.4 Once you have written the program, run the SQL trace on it to measure your database
access times.



Tips &
Tricks






Unit: ABAP Open SQL
Exercise 6: Reading grouped data with particular
conditions

(C) SAP AG BC411 19-31
Theme: Minimizing the amount of data transferred

6.1 Write a program to find the number of passengers and the average
luggage weight of all Lufthansa flights after Dec. 01 1998 having
an average luggage weight of 20 kg.

6.2 You work for a travel agency and it is your task to write a program
that produces the list described above. The list should contain the
fields CARRID (LH), CONNID, FLDATE; the average luggage
weight (LUGGWEIGHT) and the total number of all passengers
(COUNT(*)),and be structured as follows:
CARRID CONNID FLDATE avg. LUGGWEIGHT number of pass.
LH 0400 12.02.1998 31 12



Object Name / Description
Program ZBC411_##_Select_Having




Activities




1.4 Once you have written the program, run the SQL trace on it to measure your database
access times.

(C) SAP AG BC411 19-32

Use the addition GROUP BY carrid connid fldate in the SELECT
statement.
Tips &
Tricks






(C) SAP AG BC411 19-33



Unit: String Processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: String processing

1.9 Write a program to convert the value of a type I input field into a
binary string. Display the binary string as a 32-character type C
field.

Object Name / Description
Program ZBC411_##_String_Operation


Activities




Method: Use a WHILE loop with the MOD and DIV statements to retrieve
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
Tips &
Tricks




(C) SAP AG BC411 19-34



Unit: Bit processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: Bit processing

1.10 Repeat the string processing exercise, but this time use bit
operations.
Write a program to convert the value of a type I input field into a
binary string. Display the binary value in a 32-character type C
field.

Object Name / Description
Program ZBC411_##_ Bit_Operation


Activities





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
R
Solutions



(C) SAP AG BC411 20-2



Unit: Development process and tools
Exercise 1: Correcting the errors in a program and
runtime analysis
Theme: Development process

Model solution SAPBC410S_LIST
TOP include
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& I ncl ude BC411S_LI STTOP
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

PROGRAM sapbc411s_l i st MESSAGE- I D bc411 LI NE- SI ZE 130.

*TABLES st at ement not necessar y

PARAMETERS:
s_f r om TYPE s_dat e DEFAULT ' 19000101' ,
s_t o TYPE s_dat e DEFAULT ' 20000101' ,
s_sor t ( 1) TYPE c DEFAULT ' 1' .



DATA:
sl i st TYPE t ab_sl i st ,
r esul t TYPE c.

*CONSTANTS c_l engt h i s not used

*Macr o def i ni t i on i ncr eases r unt i me unnecessar i l y

(C) SAP AG BC411 20-3

SAPBC411S_LI STEE01 I ncl ude ( Event i ncl ude)
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* I NCLUDE BC411S_LI STE01
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*wr ong par amet er s passed

CALL FUNCTI ON ' SAPBC411_GET_DATA' EXPORTI NG p_f r om = s_f r om
p_t o = s_t o
I MPORTI NG p_l i st = sl i st
EXCEPTI ONS no_dat a = 1.
*Ret ur ncode check and possi bl e EXI T st at ement wer e mi ssi ng

I F sy- subr c <> 0.
WRI TE ' No f l i ght s f ound' ( 001) .
EXI T.
ENDI F.

*Spel l i ng er r or and wr ong par amet er passed
PERFORM sor t TABLES sl i st USI NG s_sor t CHANGI NG r esul t .

I F r esul t = space.
MESSAGE s000.
ENDI F.

*Spel l i ng er r or and wr ong par amet er passed
PERFORM out put USI NG sl i st .


(C) SAP AG BC411 20-4
SAPBC411S_LISTEF01 (Form include)
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* I NCLUDE BC411S_LI STF01
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

*pass par amet er p_sor t i ndex as r ef er ence
FORM sor t TABLES p_l i st TYPE t ab_sl i st
USI NG p_sor t i ndex TYPE c
CHANGI NG p_r esul t TYPE c.

*l _f i el d1( cl engt h) not r equi r ed
*def i ni ng l _component as t ype i r educes unnecessar y t ype p
*conver si on
*see r unt i me anal yses

DATA:
l _component TYPE i .
FI ELD- SYMBOLS
<l _f s>.
p_r esul t = ' X' .
*spel l i ng er r or
l _component = p_sor t i ndex.
*Spel l i ng er r or i n f i el d symbol
ASSI GN COMPONENT l _component OF STRUCTURE p_l i st TO <l _f s>.
* Cl ear bef or e EXI T
I F sy- subr c <> 0.
CLEAR p_r esul t .
EXI T.
ENDI F.
SORT p_l i st BY <l _f s>.
*Macr o def i ni t i on i ncr eases r unt i me. Macr o unnecessar y
ENDFORM.


*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* FORM OUTPUT
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

(C) SAP AG BC411 20-5
*
*Pass Par amet er p_l i st wi t h VALUE

FORM out put USI NG p_l i st TYPE t ab_sl i st .
DATA:
*Spel l i ng er r or : LI KE LI NE OF p_l i st i nst ead of LI KE LI NE OF *
*l _l i st
l _l i st _wa LI KE LI NE OF p_l i st .
*St at us LI STE i nst ead of LI ST. And SET PF- STATUS onl y once
*out si de of t he LOOP.
SET PF- STATUS ' LI STE' .

LOOP AT p_l i st I NTO l _l i st _wa.
*l _l i st _wa- pr i ce wi t hout cur r ency cl ause
WRI TE: /
l _l i st _wa- f l dat e,
l _l i st _wa- count r yf r ,
l _l i st _wa- ci t yf r om,
l _l i st _wa- count r yt o,
l _l i st _wa- ci t yt o,
l _l i st _wa- pr i ce CURRENCY l _l i st _wa- cur r ency,
l _l i st _wa- cur r ency.
ULI NE.
ENDLOOP.
WRI TE ' End of l i st ' ( 002) .
ENDFORM.

*empt y FORM wor k. Not necessar y

*PERFORM af t er FORM can not be r eached.


(C) SAP AG BC411 20-6



Unit: Types
Exercise 1: Adjusting Data Types
Theme: Runtime of Data Type Conversions

Solution SAPBC411S_TYPE

*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411T_TYPE
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*&
*

REPORT sapbc411t _t ype .


PARAMETERS:
*n t ype i avoi ds t ype P conver si ons. Al so t r ue f or var i abl e r esul t
n TYPE i .

DATA:
r esul t TYPE i .

*n of Type i . Don' t pass as st r i ng. Avoi ds i nt er nal conver si ons.
I F n > 12.
WRI TE ' N i s t oo l ar ge' ( 001) .
EXI T.
ENDI F.

PERFORM f akul t aet USI NG n CHANGI NG r esul t .

WRI TE: / n, r esul t .

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* FORM FAKULTAET
*

(C) SAP AG BC411 20-7
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* - - > VALUE( P_N)
*
* - - > P_RESULT
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*p_n pass as r ef er ence i s f ast er . Compl et e t ype def i ni t i on r educes
*er r or s.
FORM f akul t aet USI NG p_n TYPE i
CHANGI NG p_r esul t TYPE i .
DATA:
*l _t emp onl y wi t h l engt h 1 r equi r ed. Def i ned as t ype i avoi ds
*conver si ons i n cal cul at i ons

l _t emp TYPE i .
*Val ue 0 not as st r i ng. Avoi ds i nt er nal conver si ons. Al so t r ue wi t h
*p_r esul t

I F p_n = 0.
p_r esul t = 1.
EXI T.
ENDI F.
*Don' t pass val ue 1 as st r i ng
l _t emp = p_n - 1.
PERFORM f akul t aet USI NG l _t emp CHANGI NG p_r esul t .
p_r esul t = p_n * p_r esul t .

ENDFORM.


(C) SAP AG BC411 20-8



Unit: Field symbols
Exercise 1: Assigning an object to a field symbol
Theme: Different ways of assigning field symbols using the
ASSI GN statement

Model solution SAPBC410S_BI T_OPERATI ON
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*& Repor t SAPBC411S_ASSI GN
*&
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

REPORT sapbc411t _assi gn.


PARAMETERS:
car r i d TYPE sf l i ght - car r i d DEFAULT ' LH' ,
compno TYPE i DEFAULT ' 1' ,
compname( 8) TYPE c DEFAULT ' CONNI D' .


PERFORM wr i t e_sel ect ed_f i el d USI NG compno.
ULI NE.
PERFORM wr i t e_sel ect ed_f i el d_2 USI NG compname.
ULI NE.
PERFORM wr i t e_sel ect ed_f i el d_3 USI NG compname.


*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* FORM WRI TE_SELECTED_FI ELD
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* . . . . . . . .
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* - - > P_COMPNO
*

(C) SAP AG BC411 20-9
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

FORM wr i t e_sel ect ed_f i el d USI NG p_compno TYPE any.

DATA:
l _wa_sf l i ght TYPE sf l i ght ,
l _f i el d( 30) TYPE c,
l _l engt h TYPE i .
FI ELD- SYMBOLS:
<l _f s>.

SELECT * FROM sf l i ght I NTO l _wa_sf l i ght WHERE car r i d = car r i d.
PERFORM assi gn_component USI NG l _wa_sf l i ght
p_compno
CHANGI NG l _f i el d.
l _l engt h = STRLEN( l _f i el d ) .
ASSI GN l _f i el d( l _l engt h) TO <l _f s>.
I F sy- subr c = 0.
WRI TE / <l _f s> COLOR COL_NEGATI VE.
ENDI F.
ENDSELECT.
ENDFORM.
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* FORM ASSI GN_COMPONENT
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* . . . . . . . .
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* - - > P_STRUCTURE
*
* - - > P_COMPONENT
*
* - - > P_RESULT
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
FORM assi gn_component USI NG p_st r uct ur e TYPE any
p_component TYPE any
CHANGI NG p_r esul t TYPE any.
FI ELD- SYMBOLS:
<l _f s>.


(C) SAP AG BC411 20-10
ASSI GN COMPONENT p_component OF STRUCTURE p_st r uct ur e TO <l _f s>.
MOVE <l _f s> TO p_r esul t .

ENDFORM.
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* FORM WRI TE_SELECTED_FI ELD_2
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* . . . . . . . .
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* - - > P_COMPNO
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
FORM wr i t e_sel ect ed_f i el d_2 USI NG p_compname TYPE c.

DATA:
l _wa_sf l i ght TYPE sf l i ght ,
l _f i el d( 30) TYPE c,
l _l engt h TYPE i .
FI ELD- SYMBOLS:
<l _f s>.

SELECT * FROM sf l i ght I NTO l _wa_sf l i ght WHERE car r i d = car r i d.
PERFORM assi gn_component USI NG l _wa_sf l i ght
p_compname
CHANGI NG l _f i el d.
l _l engt h = STRLEN( l _f i el d ) .
ASSI GN l _f i el d( l _l engt h) TO <l _f s>.
WRI TE / <l _f s> COLOR COL_NEGATI VE.
ENDSELECT.

ENDFORM.




(C) SAP AG BC411 20-11
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* FORM WRI TE_SELECTED_FI ELD_3
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* . . . . . . . .
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* - - > P_COMPNO
*
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- *
FORM wr i t e_sel ect ed_f i el d_3 USI NG p_compname TYPE c.

DATA:
l _wa_sf l i ght TYPE sf l i ght , " #EC *
l _f i el d_name( 30) TYPE c,
l _l engt h TYPE i .

FI ELD- SYMBOLS:
<l _f s>.

SELECT * FROM sf l i ght I NTO l _wa_sf l i ght WHERE car r i d = car r i d.
CONCATENATE ' L_WA_SFLI GHT- ' p_compname I NTO l _f i el d_name.
ASSI GN ( l _f i el d_name) TO <l _f s>.
l _l engt h = STRLEN( <l _f s> ) .
ASSI GN <l _f s>( l _l engt h) TO <l _f s>.
WRI TE / <l _f s> COLOR COL_NEGATI VE.
ENDSELECT.

ENDFORM.


(C) SAP AG BC411 20-12



Unit: I nternal Tables
Exercise 1
Theme: Defining I nternal Tables

Soultion SAPBC411S_KEYTAB_DEFI NI TION
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411S_KEYTAB_DEFI NI TI ON
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411s_keyt ab_def i ni t i on .

TYPES: BEGI N OF st r uc,
a TYPE i ,
b( 1000) TYPE c,
d TYPE p,
END OF st r uc.

DATA: st d_t ab TYPE STANDARD TABLE OF st r uc
WI TH NON- UNI QUE KEY a,
sor t _t ab TYPE SORTED TABLE OF st r uc
WI TH NON- UNI QUE KEY a,
hash_t ab TYPE HASHED TABLE OF st r uc
WI TH UNI QUE KEY a.


(C) SAP AG BC411 20-13



Unit: I nternal Tables
Exercise 2:
Theme: Filling internal tables

Solution SAPBC411S_KEYTAB_FI LL
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411S_KEYTAB_FI LL *
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411s_keyt ab_f i l l .
* Type def i ni t i on f or i nt er nal t abl es

TYPES: BEGI N OF st r uc,
a TYPE i ,
b( 1000) TYPE c,
d TYPE p,
END OF st r uc.

* i nt er nal t abl e def i ni t i on

DATA: st d_t ab TYPE STANDARD TABLE OF st r uc
WI TH NON- UNI QUE KEY a,
sor t _t ab TYPE SORTED TABLE OF st r uc
WI TH NON- UNI QUE KEY a,
hash_t ab TYPE HASHED TABLE OF st r uc
WI TH UNI QUE KEY a.

PARAMETERS: val ue TYPE i .
DATA: wa TYPE st r uc.

(C) SAP AG BC411 20-14
* f i l l i nt er nal t abl es

DO val ue TI MES.
wa- a = sy- i ndex.
wa- b = ' i nt er ne Tabel l en machen Spa' ( 001) .
wa- d = ' 100. 01' .
I NSERT wa I NTO TABLE st d_t ab.
I NSERT wa I NTO TABLE sor t _t ab.
I NSERT wa I NTO TABLE hash_t ab.
ENDDO.




(C) SAP AG BC411 20-15



Unit: I nternal Tables
Exercise 3: Accessing a single entry
Theme: Runtime for accessing single entries

Solution SAPBC411S_KEYTAB_READ
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411S_KEYTAB_DEFI NI TI ON
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411s_keyt ab_def i ni t i on .

* Type def i ni t i on f or i nt er nal t abl es

TYPES: BEGI N OF st r uc,
a TYPE i ,
b( 1000) TYPE c,
d TYPE p,
END OF st r uc.

* i nt er nal t abl e def i ni t i on

DATA: st d_t ab TYPE STANDARD TABLE OF st r uc
WI TH NON- UNI QUE KEY a,
sor t _t ab TYPE SORTED TABLE OF st r uc
WI TH NON- UNI QUE KEY a,
hash_t ab TYPE HASHED TABLE OF st r uc
WI TH UNI QUE KEY a.

PARAMETERS: val ue TYPE i , r ead_val TYPE i .

DATA: wa TYPE st r uc.

* f i l l i nt er nal t abl es
DO val ue TI MES.

(C) SAP AG BC411 20-16
wa- a = sy- i ndex.
wa- b = ' i nt er ne Tabel l en machen Spa' ( 001) .
wa- d = ' 100. 01' .
I NSERT wa I NTO TABLE st d_t ab.
I NSERT wa I NTO TABLE sor t _t ab.
I NSERT wa I NTO TABLE hash_t ab.
ENDDO.

*r ead a l i ne f r omt he i nt er nal t abl es.

READ TABLE st d_t ab I NTO wa WI TH TABLE KEY a = r ead_val .
WRI TE: / wa- a, wa- b, wa- d.
READ TABLE sor t _t ab I NTO wa WI TH TABLE KEY a = r ead_val .
WRI TE: / wa- a, wa- b, wa- d.
READ TABLE hash_t ab I NTO wa WI TH TABLE KEY a = r ead_val .
WRI TE: / wa- a, wa- b, wa- d.


(C) SAP AG BC411 20-17



Unit: ABAP Objects
Exercise 1: Defining and I mplementing Classes
Theme: Classes


Solution SAPBC411S_OO_CREATE_CLASS
REPORT oo_i nt er f aces_1 NO STANDARD PAGE HEADI NG.

********************************************************************
* Si mpl e exampl e f or cl asses def i ni t i on and i mpl ement at i on.
********************************************************************


CLASS c_shi p DEFI NI TI ON.
PUBLI C SECTI ON.
* met hods/ i nt er f aces wi l l be def i ned l at er
PRI VATE SECTI ON.
DATA: shi p_speed TYPE i .
DATA: max_speed TYPE i VALUE 30.
DATA: i d TYPE i .
CLASS- DATA: i nst _i d TYPE i .

ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck DEFI NI TI ON.
PUBLI C SECTI ON.
* met hods/ i nt er f aces wi l l be def i ned l at er
PRI VATE SECTI ON.
DATA: t r uck_speed TYPE i .
DATA: max_speed TYPE i VALUE 10.
CLASS- DATA: i nst _i d TYPE i .
ENDCLASS.


(C) SAP AG BC411 20-18

********************************************************************
* I mpl ement at i ons
********************************************************************

CLASS c_shi p I MPLEMENTATI ON.
* her e al l METHOD wi l l be i mpl ement ed
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck I MPLEMENTATI ON.
* her e al l METHOD wi l l be i mpl ement ed
ENDCLASS.

********************************************************************
* Pr ogr am
********************************************************************

START- OF- SELECTI ON.


(C) SAP AG BC411 20-19



Unit: ABAP Objects
Exercise 2: Creating Instances, Defining, I mplementing,
and Calling Methods
Theme: I nstances and Methods



Solution SAPBC411S_OO_OBJ ECTS_METHODS
REPORT sapbc411s_oo_obj ect _met hod NO STANDARD PAGE HEADI NG.

********************************************************************
* Si mpl e exampl e f or cl asses def i ni t i on/ i mpl ement at i on wi t h met hods
********************************************************************


CLASS c_shi p DEFI NI TI ON.
PUBLI C SECTI ON.
New par t s ar e mar ked bol d and i t al i c
METHODS const r uct or . " I s cal l ed aut omat i cal l y i n Rel . 4. 5A i n
" CREATE OBJ ECT
METHODS speed_up.
METHODS st op.
METHODS wr i t e.
PRI VATE SECTI ON.
DATA: shi p_speed TYPE i .
DATA: max_speed TYPE i VALUE 30.
DATA: i d TYPE i .
CLASS- DATA: i nst _i d TYPE i .

ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck DEFI NI TI ON.
PUBLI C SECTI ON.


(C) SAP AG BC411 20-20
METHODS const r uct or . " I s cal l ed aut omat i cal l y i n Rel . 4. 5A
" i n CREATE OBJ ECT
METHODS speed_up.
METHODS st op.
METHODS wr i t e.
PRI VATE SECTI ON.
DATA: t r uck_speed TYPE i .
DATA: max_speed TYPE i VALUE 10.
DATA: i d TYPE i .
CLASS- DATA: i nst _i d TYPE i .

ENDCLASS.


********************************************************************
* I mpl ement at i ons
********************************************************************

CLASS c_shi p I MPLEMENTATI ON.
METHOD const r uct or .
i nst _i d = i nst _i d + 1.
i d = i nst _i d.
max_speed = 30.
ENDMETHOD.
METHOD speed_up.
CHECK shi p_speed < max_speed.
shi p_speed = shi p_speed + 10.
ENDMETHOD.
METHOD st op.
shi p_speed = 0.
ENDMETHOD.
METHOD wr i t e.
WRI TE: / ' Shi p: I D = ' , i d, ' Speed = ' , shi p_speed.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck I MPLEMENTATI ON.
METHOD const r uct or .

(C) SAP AG BC411 20-21
i nst _i d = i nst _i d + 1.
i d = i nst _i d.
max_speed = 130.
ENDMETHOD.
METHOD speed_up.

CHECK t r uck_speed < max_speed.
t r uck_speed = t r uck_speed + 50.
ENDMETHOD.
METHOD st op.
t r uck_speed = 0.
ENDMETHOD.
METHOD wr i t e.
WRI TE: / ' Tr uck: I D = ' , i d, ' Speed = ' , t r uck_speed.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Pr ogr am
********************************************************************

START- OF- SELECTI ON.
DATA oshi p TYPE REF TO c_shi p.
DATA ot r uck TYPE REF TO c_t r uck.

DATA shi p_t ab TYPE REF TO c_shi p OCCURS 0.
DATA t r uck_t ab TYPE REF TO c_t r uck OCCURS 0.
*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*- - - cr eat e some i nst ances ( I D i s set aut omat i cal l y) .
DO 2 TI MES.
CREATE OBJ ECT oshi p.
CALL METHOD oshi p- >const r uct or .
APPEND oshi p TO shi p_t ab.
ENDDO.
DO 2 TI MES.
CREATE OBJ ECT ot r uck.
CALL METHOD ot r uck- >const r uct or .
APPEND ot r uck TO t r uck_t ab.
ENDDO.


(C) SAP AG BC411 20-22
*- - - - speed up and wr i t e
LOOP AT shi p_t ab I NTO oshi p.
CALL METHOD oshi p- >speed_up.
CALL METHOD oshi p- >wr i t e.
ENDLOOP.
LOOP AT t r uck_t ab I NTO ot r uck.
CALL METHOD ot r uck- >speed_up.
CALL METHOD ot r uck- >wr i t e.
ENDLOOP.


(C) SAP AG BC411 20-23



Unit: ABAP Objects
Exercise 3: Defining, I mplementing, and Using I nterfaces
Theme: I nterfaces

Solution SAPBC411S_OO_I NTERFACES
REPORT sapbc411s_oo_i nt er f aces NO STANDARD PAGE HEADI NG.

********************************************************************
* Si mpl e exampl e of i nt er f aces
********************************************************************
new par t s ar e mar ked bol d, i t al i c
I NTERFACE i _vehi cl e.
DATA: i d TYPE i READ- ONLY.
METHODS: speed_up,
wr i t e,
st op.
ENDI NTERFACE.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_shi p DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS const r uct or . " I s cal l ed aut omat i cal l y i n Rel . 4. 5A
" i n CREATE OBJ ECT

I NTERFACES i _vehi cl e.
PRI VATE SECTI ON.
DATA shi p_speed TYPE i .
DATA: max_speed t ype i .
CLASS- DATA: i nst _i d TYPE i .
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck DEFI NI TI ON.
PUBLI C SECTI ON.

(C) SAP AG BC411 20-24
METHODS const r uct or . " I s cal l ed aut omat i cal l y i n Rel . 4. 5A
" i n CREATE OBJ ECT

I NTERFACES i _vehi cl e.
PRI VATE SECTI ON.
DATA t r uck_speed TYPE i .
DATA: max_speed t ype i .
CLASS- DATA: i nst _i d TYPE i .
ENDCLASS.


********************************************************************
* I mpl ement at i ons
********************************************************************

CLASS c_shi p I MPLEMENTATI ON.
METHOD const r uct or .
i nst _i d = i nst _i d + 1.
i _vehi cl e~i d = i nst _i d.
max_speed = 30.
ENDMETHOD.
METHOD i _vehi cl e~speed_up.
CHECK shi p_speed < max_speed.
shi p_speed = shi p_speed + 10.
ENDMETHOD.
METHOD i _vehi cl e~st op.
shi p_speed = 0.
ENDMETHOD.
METHOD i _vehi cl e~wr i t e.
WRI TE: / ' Shi p: I D = ' , i _vehi cl e~i d, ' Speed = ' , shi p_speed.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck I MPLEMENTATI ON.
METHOD const r uct or .
i nst _i d = i nst _i d + 1.
i d = i nst _i d.
max_speed = 130.

(C) SAP AG BC411 20-25
ENDMETHOD.
METHOD i _vehi cl e~speed_up.
CHECK t r uck_speed < speed.
t r uck_speed = t r uck_speed + 50.
ENDMETHOD.
METHOD i _vehi cl e~st op.
t r uck_speed = 0.
ENDMETHOD.
METHOD i _vehi cl e~wr i t e.
WRI TE: / ' Tr uck: I D = ' , i _vehi cl e~i d, ' Speed = ' , t r uck_speed.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Pr ogr am
********************************************************************

START- OF- SELECTI ON.
DATA oshi p TYPE REF TO c_shi p.
DATA ot r uck TYPE REF TO c_t r uck.
DATA i vehi cl e TYPE REF TO i _vehi cl e.

DATA veh_t ab TYPE REF TO i _vehi cl e OCCURS 0.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*- - - cr eat e some i nst ances ( I D i s set aut omat i cal l y) .
DO 2 TI MES.
CREATE OBJ ECT oshi p.
CALL METHOD oshi p- >const r uct or .
APPEND oshi p TO veh_t ab.
ENDDO.

DO 2 TI MES.
CREATE OBJ ECT ot r uck.
CALL METHOD ot r uck- >const r uct or .
APPEND ot r uck TO veh_t ab.
ENDDO.

*- - - - speed up and wr i t e
LOOP AT veh_t ab I NTO i vehi cl e.

(C) SAP AG BC411 20-26
CALL METHOD i vehi cl e- >speed_up.
CALL METHOD i vehi cl e- >speed_up.
CALL METHOD i vehi cl e- >wr i t e.
CALL METHOD i vehi cl e- >st op.
CALL METHOD i vehi cl e- >wr i t e.
SKI P.
ENDLOOP.


(C) SAP AG BC411 20-27



Unit: ABAP Objects
Exercise 4: Defining, I mplementing, Handling, and
Registering Events
Theme: Events

Solution SAPBC411S_OO_EVENTS
Refer to the program for the definition of the screen
REPORT sapbc411s_oo_event s NO STANDARD PAGE HEADI NG.

I NCLUDE <l i st >.

********************************************************************
* Decl ar at i ons
********************************************************************
new par t s ar e mar ked bol d
I NTERFACE i _vehi cl e.
DATA max_speed TYPE i .
EVENTS: speed_change EXPORTI NG val ue( new_speed) TYPE i .
METHODS: speed_up,
st op.
ENDI NTERFACE.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_shi p DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS const r uct or . " I s cal l ed aut omat i cal l y i n Rel . 4. 5A
" i n CREATE OBJ ECT

I NTERFACES i _vehi cl e.
PRI VATE SECTI ON.
* ALI ASES max FOR i _vehi cl e~max_speed. " Rel . 4. 5A
DATA shi p_speed TYPE i .
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

(C) SAP AG BC411 20-28

CLASS c_t r uck DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS const r uct or . " I s cal l ed aut omat i cal l y i n Rel . 4. 5A
" i n CREATE OBJ ECT

I NTERFACES i _vehi cl e.
PRI VATE SECTI ON.
* ALI ASES max FOR i _vehi cl e~max_speed. " Rel . 4. 5A
DATA t r uck_speed TYPE i .
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS st at us DEFI NI TI ON.
PUBLI C SECTI ON.
CLASS- EVENTS but t on_cl i cked EXPORTI NG val ue( f code) LI KE sy- ucomm.
CLASS- METHODS: cl ass_const r uct or , " I s cal l ed aut omat i cal l y i n
" Rel . 4. 5A i n CREATE OBJ ECT

user _act i on.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_l i st DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: f code_handl er FOR EVENT but t on_cl i cked OF st at us
I MPORTI NG f code,
l i st _change FOR EVENT speed_change OF i _vehi cl e
I MPORTI NG new_speed,
l i st _out put .
PRI VATE SECTI ON.
DATA: i d TYPE i ,
r ef _shi p TYPE REF TO c_shi p,
r ef _t r uck TYPE REF TO c_t r uck,
BEGI N OF l i ne,
i d TYPE i ,
f l ag,
i r ef TYPE REF TO i _vehi cl e,

(C) SAP AG BC411 20-29
speed TYPE i ,
END OF l i ne,
l i st LI KE SORTED TABLE OF l i ne WI TH UNI QUE KEY i d.
ENDCLASS.

********************************************************************
* I mpl ement at i ons
********************************************************************

CLASS c_shi p I MPLEMENTATI ON.
METHOD const r uct or .
i _vehi cl e~max_speed = 30.
ENDMETHOD.
METHOD i _vehi cl e~speed_up.
CHECK shi p_speed < i _vehi cl e~max_speed.
shi p_speed = shi p_speed + 10.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = shi p_speed.
ENDMETHOD.
METHOD i _vehi cl e~st op.
CHECK shi p_speed > 0.
shi p_speed = 0.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = shi p_speed.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck I MPLEMENTATI ON.
METHOD const r uct or .
max = 150.
ENDMETHOD.
METHOD i _vehi cl e~speed_up.
CHECK t r uck_speed < i vehi cl e~max_speed.
t r uck_speed = t r uck_speed + 50.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = t r uck_speed.
ENDMETHOD.
METHOD i _vehi cl e~st op.

(C) SAP AG BC411 20-30
CHECK t r uck_speed > 0.
t r uck_speed = 0.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = t r uck_speed.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS st at us I MPLEMENTATI ON.
METHOD cl ass_const r uct or .
SET PF- STATUS ' VEHI CLE' .
WRI TE ' Cl i ck a but t on! ' .
ENDMETHOD.
METHOD user _act i on.
RAI SE EVENT but t on_cl i cked EXPORTI NG f code = sy- ucomm.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_l i st I MPLEMENTATI ON.
METHOD f code_handl er .
CLEAR l i ne.
CASE f code.
WHEN ' CREA_SHI P' .
i d = i d + 1.
CREATE OBJ ECT r ef _shi p.
CALL METHOD r ef _shi p- >const r uct or .
l i ne- i d = i d.
l i ne- f l ag = ' S' .
l i ne- i r ef = r ef _shi p.
APPEND l i ne TO l i st .
WHEN ' CREA_TRUCK' .
i d = i d + 1.
CREATE OBJ ECT r ef _t r uck.
CALL METHOD r ef _t r uck- >const r uct or .
l i ne- i d = i d.
l i ne- f l ag = ' T' .
l i ne- i r ef = r ef _t r uck.

(C) SAP AG BC411 20-31
APPEND l i ne TO l i st .
WHEN ' SPEED_UP' .
CHECK sy- l i l l i > 0. " absol ut e l i ne number i n l i st
READ TABLE l i st I NDEX sy- l i l l i I NTO l i ne.
CALL METHOD l i ne- i r ef - >speed_up.
WHEN ' STOP' .
LOOP AT l i st I NTO l i ne.
CALL METHOD l i ne- i r ef - >st op.
ENDLOOP.
WHEN ' CANCEL' .
LEAVE PROGRAM.
ENDCASE.
CALL METHOD l i st _out put .
ENDMETHOD.
METHOD l i st _change.
l i ne- speed = new_speed.
MODI FY TABLE l i st FROM l i ne.
ENDMETHOD.
METHOD l i st _out put .
sy- l si nd = 0. " Li st l evel
SET TI TLEBAR ' TI T' .
LOOP AT l i st I NTO l i ne.
I F l i ne- f l ag = ' S' .
WRI TE / i con_ws_shi p AS I CON.
ELSEI F l i ne- f l ag = ' T' .
WRI TE / i con_ws_t r uck AS I CON .
ENDI F.
WRI TE: ' Speed = ' , l i ne- speed.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Gl obal dat a of pr ogr am
********************************************************************

DATA l i st TYPE REF TO c_l i st .

********************************************************************
* Pr ogr amevent s

(C) SAP AG BC411 20-32
********************************************************************

START- OF- SELECTI ON.

CREATE OBJ ECT l i st .


SET HANDLER: l i st - >f code_handl er ,
l i st - >l i st _change FOR ALL I NSTANCES.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

AT USER- COMMAND.
CALL METHOD st at us=>user _act i on.

*************************************************************

(C) SAP AG BC411 20-33



Unit: ABAP Objects
Exercise 5: Defining, I mplementing, Handling, and
Registering Events
Theme: Logging with Events

Solution SAPBC411S_OO_EVENT_PROTOCOLL
Refer to the program for the screen definition
REPORT sapbc411s_oo_event _pr ot okol l NO STANDARD PAGE HEADI NG.

I NCLUDE <l i st >.

********************************************************************
* Decl ar at i ons
********************************************************************

I NTERFACE i _vehi cl e.
DATA max_speed TYPE i .
EVENTS: speed_change EXPORTI NG val ue( new_speed) TYPE i .
METHODS: speed_up,
st op.
ENDI NTERFACE.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_shi p DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS const r uct or .
I NTERFACES i _vehi cl e.
PRI VATE SECTI ON.
* ALI ASES max FOR i _vehi cl e~max_speed. " Rel 4. 5A
DATA shi p_speed TYPE i .
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck DEFI NI TI ON.

(C) SAP AG BC411 20-34
PUBLI C SECTI ON.
METHODS const r uct or .
I NTERFACES i _vehi cl e.
PRI VATE SECTI ON.
* ALI ASES max FOR i _vehi cl e~max_speed. " Rel 4. 5A
DATA t r uck_speed TYPE i .
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS st at us DEFI NI TI ON.
PUBLI C SECTI ON.
CLASS- EVENTS but t on_cl i cked EXPORTI NG val ue( f code) LI KE sy- ucomm.
CLASS- METHODS: cl ass_const r uct or ,
user _act i on.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_l i st DEFI NI TI ON.
PUBLI C SECTI ON.
METHODS: f code_handl er FOR EVENT but t on_cl i cked OF st at us
I MPORTI NG f code,
l i st _change FOR EVENT speed_change OF i _vehi cl e
I MPORTI NG new_speed,
l i st _out put .
PRI VATE SECTI ON.
DATA: i d TYPE i ,
r ef _shi p TYPE REF TO c_shi p,
r ef _t r uck TYPE REF TO c_t r uck,
BEGI N OF l i ne,
i d TYPE i ,
f l ag,
i r ef TYPE REF TO i _vehi cl e,
speed TYPE i ,
END OF l i ne,
l i st LI KE SORTED TABLE OF l i ne WI TH UNI QUE KEY i d.
ENDCLASS.

********************************************************************

(C) SAP AG BC411 20-35
* Pr ot ocol l by event handl i ng
****** PROTOCOLL MODI FI CATI ON ******

CLASS c_pr ot ocol l DEFI NI TI ON.
PUBLI C SECTI ON.
CLASS- METHODS: f code_handl er FOR EVENT but t on_cl i cked OF st at us
I MPORTI NG f code.
CLASS- METHODS: wr i t e_pr ot ocol l .
CLASS- DATA: pr ot ocol l _wr i t t en TYPE i READ- ONLY.
PRI VATE SECTI ON.
CLASS- DATA f code_t ab LI KE sy- ucommOCCURS 0.
ENDCLASS.

CLASS c_pr ot ocol l I MPLEMENTATI ON.
METHOD f code_handl er . " - - Ar g: f code
APPEND f code TO f code_t ab.
ENDMETHOD.
METHOD wr i t e_pr ot ocol l .
DATA commLI KE sy- ucomm.
LOOP AT f code_t ab I NTO comm.
WRI TE: / comm.
ENDLOOP.
pr ot ocol l _wr i t t en = 1.
ENDMETHOD.
ENDCLASS.

****** PROTOCOLL MODI FI CATI ON END ******

********************************************************************
* I mpl ement at i ons
********************************************************************

CLASS c_shi p I MPLEMENTATI ON.
METHOD const r uct or .
i _vehi cl e~max_speed = 30.
ENDMETHOD.
METHOD i _vehi cl e~speed_up.
CHECK shi p_speed < i _vehi cl e~max_speed.
shi p_speed = shi p_speed + 10.
RAI SE EVENT i _vehi cl e~speed_change

(C) SAP AG BC411 20-36
EXPORTI NG new_speed = shi p_speed.
ENDMETHOD.
METHOD i _vehi cl e~st op.
CHECK shi p_speed > 0.
shi p_speed = 0.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = shi p_speed.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS c_t r uck I MPLEMENTATI ON.
METHOD const r uct or .
i _vehi cl e~max_speed = 150.
ENDMETHOD.
METHOD i _vehi cl e~speed_up.
CHECK t r uck_speed < i _vehi cl e~max_speed.
t r uck_speed = t r uck_speed + 50.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = t r uck_speed.
ENDMETHOD.
METHOD i _vehi cl e~st op.
CHECK t r uck_speed > 0.
t r uck_speed = 0.
RAI SE EVENT i _vehi cl e~speed_change
EXPORTI NG new_speed = t r uck_speed.
ENDMETHOD.
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

CLASS st at us I MPLEMENTATI ON.
METHOD cl ass_const r uct or .
SET PF- STATUS ' VEHI CLE' .
WRI TE ' Cl i ck a but t on! ' .
ENDMETHOD.
METHOD user _act i on.
RAI SE EVENT but t on_cl i cked EXPORTI NG f code = sy- ucomm.
ENDMETHOD.

(C) SAP AG BC411 20-37
ENDCLASS.

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CLASS c_l i st I MPLEMENTATI ON.
METHOD f code_handl er .
CLEAR l i ne.
CASE f code.
WHEN ' CREA_SHI P' .
i d = i d + 1.
CREATE OBJ ECT r ef _shi p.
CALL METHOD r ef _shi p- >const r uct or .
l i ne- i d = i d.
l i ne- f l ag = ' C' .
l i ne- i r ef = r ef _shi p.
APPEND l i ne TO l i st .
WHEN ' CREA_TRUCK' .
i d = i d + 1.
CREATE OBJ ECT r ef _t r uck.
CALL METHOD r ef _t r uck- >const r uct or .
l i ne- i d = i d.
l i ne- f l ag = ' T' .
l i ne- i r ef = r ef _t r uck.
APPEND l i ne TO l i st .
WHEN ' SPEED_UP' .
CHECK sy- l i l l i > 0. " absol ut l i ne number i n l i st
READ TABLE l i st I NDEX sy- l i l l i I NTO l i ne.
CALL METHOD l i ne- i r ef - >speed_up.
WHEN ' STOP' .
LOOP AT l i st I NTO l i ne.
CALL METHOD l i ne- i r ef - >st op.
ENDLOOP.
WHEN ' CANCEL' .
********* PROTOLL MODI FCATI ON ****
I F c_pr ot ocol l =>pr ot ocol l _wr i t t en = 1.
LEAVE PROGRAM.
ENDI F.
CALL METHOD c_pr ot ocol l =>wr i t e_pr ot ocol l .
STOP.
ENDCASE.
****** PROTOCOLL MODI FI CATI ON END ******

(C) SAP AG BC411 20-38

CALL METHOD l i st _out put .
ENDMETHOD.
METHOD l i st _change.
l i ne- speed = new_speed.
MODI FY TABLE l i st FROM l i ne.
ENDMETHOD.
METHOD l i st _out put .
sy- l si nd = 0. " Li st l evel
SET TI TLEBAR ' TI T' .
LOOP AT l i st I NTO l i ne.
I F l i ne- f l ag = ' C' .
WRI TE / i con_ws_shi p AS I CON.
ELSEI F l i ne- f l ag = ' T' .
WRI TE / i con_ws_t r uck AS I CON .
ENDI F.
WRI TE: ' Speed = ' , l i ne- speed.
ENDLOOP.
ENDMETHOD.
ENDCLASS.

********************************************************************
* Gl obal dat a of pr ogr am
********************************************************************

DATA l i st TYPE REF TO c_l i st .


********************************************************************
* Pr ogr amevent s
********************************************************************

START- OF- SELECTI ON.

CREATE OBJ ECT l i st .

SET HANDLER: l i st - >f code_handl er ,
l i st - >l i st _change FOR ALL I NSTANCES.

****** PROTOCOLL MODI FI CATI ON ******

(C) SAP AG BC411 20-39
*- - - ext ensi on f or pr ot ocol l of commands
SET HANDLER: c_pr ot ocol l =>f code_handl er .
****** PROTOCOLL MODI FI CATI ON END ******

*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

AT USER- COMMAND.
CALL METHOD st at us=>user _act i on.

********************************************************************




(C) SAP AG BC411 20-40



Unit: Contexts
Exercise 1: Creating a context to calculate the distance
between two cities
Theme: Creating contexts

Model solution context C_GEOGR_DI STANC: See definition in the Context
Builder (Transaction SE33)

Modules used:
Name Type Name .
DI STANCE Funct i on modul e
Cont ext _demo_comput e_di st ance
C_GEOGR_I NFORMATI ON Cont ext C_GEOGR_I NFORMATI ON


Module Distance
Parameters I /O Fieldname .
Longi t ude1 I Longi t ude
Lat t i t ude1 I Lat t i t ude
Longi t ude2 I Longi t ude_1
Lat t i t ude2 I Lat i t ude_1
Di st ance O Di st ance

*Anmer kung: Not e t he par amet er s ar e t he i mpor t par amet er s of t he
f unct i on modul e Cont ext _demo_comput e_di st ance. The f i el d names ar e
t hose used i n t he cont ext , and ar e al so t hose t hat you wi l l use i n
t he SUPPLY and DEMAND st at ement s i n exer ci se 2.

(C) SAP AG BC411 20-41

ModuleC_Geogr_I nformation
Parameters I /O Field names
Ci t yf r om I Ci t y
Count r yf r om I Count r y
Ci t yt o I Ci t y_1
Count r yt o I Count r y_1
Lat i t udef r om O Lat i t ude
Longi t udef r om O Longi t ude
Lat i t udet o O Lat i t ude_1
Longi t udet o O Longi t ude_1
*Not e: These par aemt er s ar e t he i nput / out put par amet er s of t he
modul es of cont ext C_Geogr _I nf or mat i on. The f i el d names ar e t hose
used i n t he cur r ent cont ext , and ar e t hose t hat you wi l l use i n t he
SUPPLY and DEMAND st at ement s i n t he second exer ci se.

(C) SAP AG BC411 20-42



Unit: Contexts
Exercise 2: Using the context from exercise 1 to calculate
the distance between two cities
Theme: Using contexts in programs

Model solution SAPBC411S_CONTEXT_GEOGR_DI STANC

*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411S_CONTEXT_GEOGR_DI STAN
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Thi s Repor t demands t he geogr aphi cal l at i t ude and l ongi t ude
* of t wo ci t i es f r oma cont ext
*& Er r or messages f r omt he cont ext ar e deal t wi t h i n t he
* pr ogr am.
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *


*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& I ncl ude BC411_DCONTEXT_GEOGR_DI STANCE
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* Begi n of TOP I ncl ude

pr ogr am zbc411s_cont ext _geogr _di st at op.

i ncl ude <l i st >. " i ncl udes i ncl ude <symbol > und i ncl ude
" <i con>
cont ext s: c_geogr _di st anc.

t ypes cont ext _t yp t ype cont ext _t _c_geogr _di st anc.

dat a: l at i t udef r om t ype cont ext _t yp- l at i t ude,
l ongi t udef r om t ype cont ext _t yp- l ongi t ude,

(C) SAP AG BC411 20-43
l at i t udet o t ype cont ext _t yp- l at i t ude,
l ongi t udet o t ype cont ext _t yp- l ongi t ude,
di st ance l i ke l at i t udef r om.
*
par amet er s: p_ci t yf r t ype cont ext _t yp- ci t y def aul t ' FRANKFURT' ,
p_counf r t ype cont ext _t yp- count r y def aul t ' DE' ,
p_ci t yt o t ype cont ext _t yp- ci t y def aul t ' NEWYORK' ,
p_count o t ype cont ext _t yp- count r y def aul t ' US' .
*

dat a: geogr _di st ance_i nst 1 t ype cont ext _c_geogr _di st anc.

dat a i t ab l i ke symsg occur s 0 wi t h header l i ne.

* End of TOP I ncl ude

* Begi n of mai n pr ogr am

i ncl ude zbc411s_cont ext _geogr _di st at op.

st ar t - of - sel ect i on.
per f or mget _dat a.
i f sy- subr c <> 0.
per f or mwr i t e_mess.
el se.
per f or mwr i t e_dat a.
endi f .


f or mget _dat a.
suppl y ci t y = p_ci t yf r
count r y = p_counf r
ci t y_1 = p_ci t yt o
count r y_1 = p_count o
t o cont ext geogr _di st ance_i nst 1.

demand l ongi t ude = l ongi t udef r om
l at i t ude = l at i t udef r om
l ongi t ude_1 = l ongi t udet o
l at i t ude_1 = l at i t udet o

(C) SAP AG BC411 20-44
di st ance = di st ance
f r omcont ext geogr _di st ance_i nst 1 messages i nt o i t ab.
endf or m.

f or mwr i t e_mess.
sy- t var 0 = ' Wi t h er r or handl i ng' ( 007) .
wr i t e: ' Di spl ay er r or message f r omi nt er nal t abl e' ( 006) .
l oop at i t ab.
wr i t e: / i t ab- msgt y, i t ab- msgi d, i t ab- msgno,
i t ab- msgv1, i t ab- msgv2.
endl oop.
endf or m.


*out put
f or mwr i t e_dat a.
wr i t e: / ( 20) ' Ci t y' ( 001) col or 1, ' | ' ,
( 22) ' Longi t ude' ( 002) col or 1, ' | ' ,
( 22) ' Lat i t ude' ( 003) col or 1, ' | ' .
ul i ne.
wr i t e: / p_ci t yf r col or 4, ' | ' ,
l ongi t udef r omcol or 2, ' | ' ,
l at i t udef r om col or 2, ' | ' .
wr i t e: / p_ci t yt o col or 4, ' | ' ,
l ongi t udet o col or 2, ' | ' ,
l at i t udet o col or 2, ' | ' .
ul i ne.
f or mat col or 3.
wr i t e / 72 ' ' .
wr i t e: 1( 20) ' Di st ance' ( 004) , ' | ' , ( 21) di st ance, ( 32) ' km' .

endf or m.



(C) SAP AG BC411 20-45



Unit: ABAP Open SQL
Exercise 1: Reading all flights for one year
Theme: Runtime of a single access

Solution SAPBC411S_FLI GHTS_OF_ONE_YEAR
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*& Repor t SAPBC411S_FLI GHT_OF_ONE_YEAR
*
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
REPORT sapbc411s_f l i gt s_of _one_year .

PARAMETERS: par am1( 4) DEFAULT ' 1998' .

DATA: wa_sf l i ght LI KE sf l i ght .
DATA: BEGI N OF sear ch_st r i ng,
par am( 4) ,
r est VALUE ' %' ,
END OF sear ch_st r i ng.
DATA: t 1 TYPE i , t 2 TYPE i .

GET RUN TI ME FI ELD t 1.

SELECT * FROM sf l i ght I NTO wa_sf l i ght .
CHECK wa_sf l i ght - f l dat e( 4) = par am1.
* WRI TE: / wa_sf l i ght - car r i d, wa_sf l i ght - conni d.
ENDSELECT.

GET RUN TI ME FI ELD t 1.
WRI TE: / ' SELECT . . . CHECK: ' ( 001) , t 1, Number : ' ( 002) , sy- dbcnt .

(C) SAP AG BC411 20-46

sear ch_st r i ng- par am= par am1.
GET RUN TI ME FI ELD t 1.

SELECT * FROM sf l i ght I NTO wa_sf l i ght
WHERE f l dat e LI KE sear ch_st r i ng.
* WRI TE: / wa_sf l i ght - car r i d, wa_sf l i ght - conni d.
ENDSELECT.

GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
WRI TE: / ' SELECT . . . WHERE: ' ( 003) , t 2, Number : ' ( 002) , sy- dbcnt .

(C) SAP AG BC411 20-47



Unit: ABAP Open SQL
Exercise 2: Reading the first 10 flights
Theme: Using data selectively

Solution SAPBC411S_READ_10_FLI GHTS
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411S_READ_10_FLI GHTS
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411s_r ead_10_f l i ght s .

DATA: t 1 TYPE i , t 2 TYPE i .
DATA: BEGI N OF wa,
car r i d LI KE sbook- car r i d,
conni d LI KE sbook- conni d,
END OF wa.

GET RUN TI ME FI ELD t 1.

SELECT car r i d conni d I NTO wa FROM sbook
WHERE car r i d =' LH' .
I F sy- dbcnt > 10.
EXI T.
ENDI F.
* WRI TE: / wa- car r i d, wa- conni d.
ENDSELECT.

GET RUN TI ME FI ELD t 1.
WRI TE: / ' SELECT . . . I F sy- dbcnt > 10' ( 001) , Ti me: ' ( 002) , t 1.
GET RUN TI ME FI ELD t 1.

SELECT car r i d conni d FROM sbook I NTO wa
UP TO 10 ROWS WHERE car r i d = ' LH' .
* WRI TE: / wa- car r i d, wa- conni d.

(C) SAP AG BC411 20-48
ENDSELECT.

GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
WRI TE: / ' SELECT . . . UP TO 10 ROWS: ' ( 003) , Ti me: ' ( 002) , t 2.



(C) SAP AG BC411 20-49



Unit: ABAP Open SQL
Exercise 3: Calculating sums
Theme: Using aggregate functions

Solution SAPBC411S_CUMULATE_LOCCURAM
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411D_CUMULATE_LOCCURAM
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411d_cumul at e_l occur am.

DATA: wa_l occur amLI KE sbook- l occur am.
DATA: wa_l occur key LI KE sbook- l occur key.
DATA: sumTYPE sbook- l occur am.
DATA: t 1 TYPE i , t 2 TYPE i .
*- sl ow ver si on- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GET RUN TI ME FI ELD t 1.
sum= 0.

SELECT l occur amwuni t FROM sbook I NTO ( wa_l occur am, wa_l occur key)
WHERE f l dat e LI KE ' 1998%' .
sum= sum+ wa_l occur am.
ENDSELECT.

GET RUN TI ME FI ELD t 1.
WRI TE: / ' Tot al r evenue' ( 002) , sumCURRENCY wa_l occur key.
WRI TE: / ' Ent r i es r ead' ( 001) , sy- dbcnt , ' Ti me: ' ( 003) , t 1.
SKI P 3.

(C) SAP AG BC411 20-50

*- f ast ver si on - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
sum= 0.
GET RUN TI ME FI ELD t 1.

SELECT SUM( l occur am) I NTO ( sum)
FROM sbook WHERE f l dat e LI KE ' 1998%' .

GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
WRI TE: / ' Tot al r evenue' ( 002) , sumCURRENCY wa_l occur key.
WRI TE: / ' Ent r i es r ead' ( 001) , sy- dbcnt , ' Ti me: ' ( 003) , t 2.




(C) SAP AG BC411 20-51



Unit: ABAP Open SQL
Exercise 4: Reading from more than one table
Theme: J oin

Solution SAPBC411S_SEL_SFLI GHT_SBOOK
&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
& Repor t SAPBC411D_SEL_SFLI GHT_SBOOK *
&
*
&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411s_sel _sf l i ght _sbook .

TYPES: BEGI N OF t _f l i ght _book,
car r i d TYPE sbook- car r i d,
conni d TYPE sbook- conni d,
f l dat e TYPE sbook- f l dat e,
pr i ce TYPE sf l i ght - pr i ce,
cur r ency TYPE sf l i ght - cur r ency,
payment sumTYPE sf l i ght - payment sum,
booki d TYPE sbook- booki d,
cust omi d TYPE sbook- cust omi d,
END OF t _f l i ght _book.
DATA: i t _f b TYPE t _f l i ght _book OCCURS 0 WI TH HEADER LI NE.
DATA: t 1 TYPE i , t 2 TYPE i .

GET RUN TI ME FI ELD t 1.

SELECT car r i d conni d f l dat e pr i ce cur r ency payment sum
FROM sf l i ght
I NTO ( i t _f b- car r i d, i t _f b- conni d, i t _f b- f l dat e,
i t _f b- pr i ce, i t _f b- cur r ency, i t _f b- payment sum) .
SELECT booki d cust omi d
FROM sbook
I NTO ( i t _f b- booki d, i t _f b- cust omi d)
WHERE car r i d = i t _f b- car r i d

(C) SAP AG BC411 20-52
AND conni d = i t _f b- conni d
AND f l dat e = i t _f b- f l dat e.
APPEND i t _f b.
ENDSELECT.
ENDSELECT.

GET RUN TI ME FI ELD t 1.
WRI TE: / ' Ti me ( manual l y) : ' ( 001) , ' Ti me: ' ( 002) , t 1.
*l oop at i t _f b.
* WRI TE: / i t _f b- car r i d, i t _f b- conni d, i t _f b- f l dat e, i t _f b- pr i ce
* CURRENCY i t _f b- cur r ency,
* i t _f b- booki d, i t _f b- cust omi d.
*endl oop.

GET RUN TI ME FI ELD t 1.

SELECT f ~car r i d f ~conni d f ~f l dat e f ~pr i ce f ~cur r ency f ~payment sum
b~booki d b~cust omi d
FROM sf l i ght as f I NNER J OI N sbook as b
ON f ~car r i d = b~car r i d AND
f ~conni d = b~conni d AND
f ~f l dat e = b~f l dat e
I NTO TABLE i t _f b.

GET RUN TI ME FI ELD t 2. t 2 = t 2 - t 1.
WRI TE: / ' Ti me usi ng J OI N: ' ( 003) , ' Ti me: ' ( 002) , t 2.
*LOOP AT i t _f b.
* WRI TE: / i t _f b- car r i d, i t _f b- conni d, i t _f b- f l dat e, i t _f b- pr i ce,
* cur r ency i t _f b- cur r ency
* i t _f b- booki d, i t _f b- cust omi d.
*ENDLOOP.
WRI TE: ' sy- dbcnt ' , sy- dbcnt .





(C) SAP AG BC411 20-53



Unit: ABAP Open SQL
Exercise 5: Reading extreme values
Theme: Subquery

Solution SAPBC411S_SELECT_SUBQUERY
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411D_SELECT_SUBQUERY
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411d_sel ect _subquer y.

DATA: f TYPE sf l i ght , f 1 TYPE sf l i ght .
DATA: t 1 TYPE i , t 2 TYPE i .

GET RUN TI ME FI ELD t 1.

SELECT car r i d conni d MAX( seat socc ) FROM sf l i ght
I NTO ( f - car r i d, f - conni d, f - seat socc)
GROUP BY car r i d conni d
ORDER BY car r i d conni d.
SELECT car r i d conni d f l dat e FROM sf l i ght
I NTO ( f 1- car r i d, f 1- conni d, f 1- f l dat e)
WHERE car r i d = f - car r i d
AND conni d = f - conni d
AND seat socc = f - seat socc.
* WRI TE: / f 1- car r i d, f 1- conni d, f 1- f l dat e, f - seat socc.
ENDSELECT.
ENDSELECT.

GET RUN TI ME FI ELD t 1.
WRI TE: / ' Ti me wi t h nest i ng: ' ( 001) , t 1.


GET RUN TI ME FI ELD t 1.

(C) SAP AG BC411 20-54

SELECT car r i d conni d f l dat e seat socc FROM sf l i ght as f
I NTO ( f - car r i d, f - conni d, f - f l dat e, f - seat socc)
WHERE seat socc =
( sel ect MAX( seat socc ) FROM sf l i ght
WHERE car r i d = f ~car r i d
AND conni d = f ~conni d )
ORDER BY car r i d conni d f l dat e.
* WRI TE: / f - car r i d, f - conni d, f - f l dat e, f - seat socc.
ENDSELECT.

GET RUN TI ME FI ELD t 2. t 2 = t 2 - t 1.
WRI TE: / ' Ti me wi t h subquer y: ' ( 002) , t 2.
WRI TE: / ' sy- dbcnt ' , sy- dbcnt .


(C) SAP AG BC411 20-55



Unit: ABAP Open SQL
Exercise 6: Reading grouped data with conditions
Theme: HAVI NG clause

Solution SAPBC411S_SELECT_HAVI NG
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
*& Repor t SAPBC411S_SELECT_HAVI NG
*
*&
*
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *

REPORT sapbc411s_sel ect _havi ng.
DATA: t 1 TYPE i , t 2 TYPE i .
DATA: count TYPE i , max TYPE i .
DATA: conni d TYPE sbook- conni d.
DATA: f l dat e TYPE sbook- f l dat e.
DATA: avg TYPE f .

* SELECT and CHECK- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GET RUN TI ME FI ELD t 1.

SELECT conni d f l dat e COUNT( *) AVG( l uggwei ght )
I NTO ( conni d, f l dat e, count , avg)
FROM sbook
WHERE car r i d = ' LH'
AND f l dat e > ' 19981201'
GROUP BY conni d f l dat e.
CHECK avg > 2.
WRI TE: / ' LH' , conni d, f l dat e, avg, count .
ENDSELECT.
WRI TE: / ' sy- dbcnt : ' , sy- dbcnt .
GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
WRI TE: / ' Ti me wi t h CHECK: ' ( 001) , ' Ti me: ' ( 002) , t 2.

* HAVI NG CLAUSE- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

(C) SAP AG BC411 20-56
GET RUN TI ME FI ELD t 1.

SELECT conni d f l dat e COUNT( * ) AVG( l uggwei ght )
I NTO ( conni d, f l dat e, count , avg)
FROM sbook
WHERE
car r i d = ' LH' AND
f l dat e > ' 19981201'
GROUP BY conni d f l dat e
HAVI NG AVG( l uggwei ght ) > 2.
WRI TE: / ' LH' , conni d, f l dat e, avg, count .
ENDSELECT.


GET RUN TI ME FI ELD t 2.
t 2 = t 2 - t 1.
WRI TE: / ' Ti me wi t h HAVI NG: ' ( 003) , t 2.











(C) SAP AG BC411 20-57



Unit: String processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: String processing

Model solution SAPBC411S_STRI NG_OPERATI ON
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*& Repor t SAPBC411S_STRI NG_OPERATI ON
*&
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

REPORT sapbc411s_st r i ng_oper at i on.

PARAMETERS: n TYPE i .

DATA: bi nst r ( 32) TYPE c,
di gi t s TYPE i ,
r est TYPE c,
i TYPE i .

* Deci mal t o bi nar y conver si on usi ng st r i ng oper at i ons
i = n.
WHI LE i <> 0.
r est = i MOD 2.
CONCATENATE r est bi nst r I NTO bi nst r .
i = i DI V 2.
ADD 1 TO di gi t s.
ENDWHI LE.

I F di gi t s < 32.
di gi t s = 32 - di gi t s.
SHI FT bi nst r RI GHT BY di gi t s PLACES.
TRANSLATE bi nst r USI NG ' 0' .
ENDI F.


(C) SAP AG BC411 20-58
WRI TE: / ' Deci mal t o bi nar y conver si on usi ng st r i ng
oper at i ons: ' ( 005) ,
/ ' Deci mal : ' ( 002) , n LEFT- J USTI FI ED,
/ ' bi nar y: ( 003) ' ( 004) , bi nst r .


(C) SAP AG BC411 20-59



Unit: Bit processing
Exercise 1: Converting the value of a type I input field into
a binary string
Theme: Bit processing

Model solution SAPBC410S_BI T_OPERATI ON
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*& Repor t SAPBC411S_BI T_OPERATI ON
*&
*&- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

REPORT sapbc411s_bi t _oper at i on.

PARAMETERS: n TYPE i .
* Deci mal t o bi nar y conver si on usi ng bi t oper at i ons
DATA: bi nst r ( 32) TYPE c
DATA: hex( 4) TYPE x,
of f s TYPE i ,
b TYPE i .

CLEAR bi nst r WI TH ' 0' .
hex = n.
DO 32 TI MES.
GET BI T sy- i ndex OF hex I NTO b.
I F b = 1.
of f s = sy- i ndex - 1.
bi nst r +of f s( 1) = ' 1' .
ENDI F.
ENDDO.
SKI P.
WRI TE: / ' Deci mal t o bi nar y conver si on usi ng bi t oper at i ons: ' ( 001) ,
/ ' Deci mal : ' ( 002) , n LEFT- J USTI FI ED,
/ ' Bi nar y: ' ( 003) , bi nst r .



SAP AG
R
Glossary



(C) SAP AG BC411 22-2
ABAP Glossary
Each entry in the glossary contains a reference to the application component to which it belongs. You can use this
path in the R/3 Library to find further information. For example, for more information about ABAP Dictionary,
look under ABAP Workbench (application component BC-DWB).

A
0ABAP Dictionary
ABAP Workbench (BC-DWB)
Central and redundancy-free storage facility for all data used in the R/3 System. The ABAP Dictionary describes
the logical structure of application development objects and their representation in the structures of the underlying
relational database. All runtime environment components such as application programs or the database interface,
get information about these objects from the ABAP Dictionary. The ABAP Dictionary is an active data dictionary
and is fully integrated into the ABAP Workbench.
1ABAP Native SQL
ABAP Workbench (BC-DWB)
ABAP Native SQL allows you to include database-specific SQL statements in an ABAP program. Most ABAP
programs containing database-specific SQL statements do not run with different databases. If different databases
are involved, use Open SQL. To execute ABAP Native SQL in an ABAP program, use the statement EXEC.
2ABAP Open SQL
ABAP Workbench (BC-DWB)
Subset of standard SQL statements.
To avoid conflicts between database tables and to keep ABAP programs independent from the database system
used, SAP has generated its own set of SQL statements known as Open SQL.
Using Open SQL allows you to access all database tables available in the R/3 System, regardless of the
manufacturer.
3ABAP Program
ABAP Workbench (BC-DWB)
Program written in the ABAP programming language.
An ABAP program consists of a collection of processing locks, which are processed sequentially as soon as they
are called by the runtime system.
There are two main kinds of ABAP program:
Report programs (ABAP reports)
Dialog programs
4ABAP Query
Basis Services/Communication Interfaces (BC-SRV)
ABAP Workbench tool that allows users without knowledge of the ABAP programming language, or table or
field names, to define and execute their own reports.
To determine the structure of reports in ABAP Query, users only have to enter texts, and select fields and options.
Fields are selected from functional areas and can be assigned a sequence by numbering.
There are three types of report available:
Basic lists
Statistics
Ranked lists
5ABAP Report
ABAP Workbench (BC-DWB)
ABAP program that reads and analyzes the data in database tables without modifying the database.
ABAP report programs are defined as type '1' programs and are linked to a particular logical database. Both of
these values are specified in the program attributes.
When you execute an ABAP report program, you can display the resulting output list - also known as a report - on
the screen or send it to a printer.

(C) SAP AG BC411 22-3
6ABAP Workbench
ABAP Workbench (BC-DWB)
SAP's integrated graphical programming environment.
The ABAP Workbench supports the development and modification of R/3 client/server applications written in
ABAP.
You can use the tools of the ABAP Workbench to
write ABAP code
design screens
create user interfaces
use predefined functions
get access to database information
control access to development objects
test applications for efficiency
debug applications
7Activation
ABAP Workbench (BC-DWB)
Process that makes an object available at runtime.
When you activate an object, the system generates a load version that application programs and screens can access
and use.
8Amodal Dialog Box
Graphical User Interface (BC-FES-GUI)
Dialog box, allowing the user to work on one screen without the previous screen first being closed.
9Application Hierarchy
Business Navigator (BC-BE-NAV)
Organizational tool for displaying all of the business applications in the R/3 System.
The application hierarchy has a user interface similar to that of a file manager, with a hierarchical structure. You
can display either the standard applications delivered with the system, or a company-specific hierarchy.
10Application Link Enabling
Integration Technology ALE (CA-BFA-ALE)
Application Link Enabling (ALE) refers to the creation and operation of distributed applications.
The basic idea is to guarantee a distributed, but integrated, R/3 installation. This involves business-controlled
message exchange with consistent data across loosely linked SAP applications.
Application integration is achieved not via a central database, but via synchronous and asynchronous
communication.
ALE comprises the following three layers:
application services
distribution services
communication services
11Application Toolbar
Graphical User Interface (BC-FES-GUI)
Element of the graphical user interface,
The application toolbar is situated below the standard toolbar on the screen. It contains pushbuttons, which allow
users quick access to application-specific functions, and occupies the whole of the primary window.
Before you can assign a function to a pushbutton, you must assign it to a function key.
12Authorization
Computing Center Management System (BC-CCM)
Authority to perform a particular action in the R/3 System.
Each authorization refers to one authorization object and defines one or more permissible values for each
authorization field listed in the authorization object.
Authorizations are combined in profiles which are entered in a user's master record.
13Authorization Field
Computing Center Management System (BC-CCM)

(C) SAP AG BC411 24-4
Element of an authorization object.
In authorization objects, authorization fields represent values for individual system elements which are supposed
to undergo authorization checking to verify a user's authorization.
14Authorization Object
Computing Center Management System (BC-CCM)
Element of the authorization concept.
Authorization objects allow you to define complex authorizations.
An authorization object groups together up to 10 authorization fields in an AND relationship in order to check
whether a user is allowed to perform a certain action.
To pass an authorization test for an object, the user must satisfy the authorization check for each field in the
object.
15Authorization Profile
Computing Center Management System (BC-CCM)
Element of the authorization concept.
An authorization profile gives a user access to the system. It contains authorizations, identified by the name of an
authorization object. Users have all of the authorizations contained in each profile entered in their user master
record.

B
16Batch I nput
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 I nput Session
Basis Services/Communications Interfaces (BC-SRV)
Set of transactions supplied with data by a program.
The transactions are stored as a stack. You can then run the session later in dialog mode. The database changes are
not made until you have run the session.
This method allows you to import large quantities of data into an R/3 System in a short time.

C
18Change Request
ABAP Workbench (BC-DWB)
Information folder in the Workbench Organizer and Customizing Organizer for entering and administrating all
changes to Repository objects and Customizing settings made during a development project.
19Change Request, Transportable
ABAP Workbench (BC-DWB)
A change request that can be transported into other systems once it has been released.
20Client
Business Engineer (BC-BE)
In commercial, organizational and technical terms, a self-contained unit in an R/3 System with separate master
records and its own set of tables.
See also the glossary entry for "logical system".
21Clipboard
Graphical User Interface (BC-FES-GUI)
Memory resource that stores a copy of the last information to be copied with the 'Copy' function, or cut with the
'Cut' function.
You can use the 'Paste' function to copy data stored in the clipboard to the current program.
The clipboard is managed by the operating system.
22Command Field
Graphical User Interface (BC-FES-GUI)

(C) SAP AG BC411 25-5
Input field in the standard toolbar to the right of the ENTER pushbutton.
You can enter fastpaths or transaction codes in this field, to choose menu entries or call transactions respectively.
23Control Group Change
ABAP Workbench (BC-DWB)
Point at which the system changes from one control group to another in a report.
The control group change represents a change in the value of whichever field is currently most significant. In an
ABAP program, you trigger it with the AT NEW statement.

D
24Data Definition Language
ABAP Workbench (BC-DWB)
Language used to define all the attributes and properties of a database management system
The query language SQL (Structured Query Language) consists of two kinds of statements:
DDL (data definition language)
DML (data manipulation language)
25Data Extract
ABAP Workbench (BC-DWB)
Sequential dataset in the memory area of a report.
26Data Manipulation Language
ABAP Workbench (BC-DWB)
Language for processing data in a database management system.
The query language SQL (Structured Query Language) consists of two kinds of statements:
DDL (data definition language)
DML (data manipulation language)
27Data Model
Data Model (BC-RMC-DMO)
Structured description of data objects, their attributes, and the relationships between them.
There are different types of data model, depending on the types of data structure you want to define (for example,
relational data model).
28Data Object
ABAP Workbench (BC-DWB)
Physical unit used by a program.
Each data object has a certain data type, which defines how ABAP processes it. All data object occupy memory
space.
29Data Type
ABAP Workbench (BC-DWB)
Attribute of a Data Object
Data types describe the technical attributes of data objects. They are purely descriptions, and occupy no memory
space.
30Database Commit
ABAP Workbench (BC-DWB)
In a database commit, all of the database update requests from the current logical unit of work (LUW) are written
to the database.
In the R/3 System, database commits are either triggered automatically or manually, using the ABAP statement
COMMIT WORK (or, in Native SQL, the database-specific equivalent).
31Database Rollback
ABAP Workbench (BC-DWB)
If you discover an error within an LUW, you can undo all of the update requests in the LUW (that is, since the last
commit) using a database rollback.
In the R/3 System, database rollbacks are either triggered automatically or manually, using the ABAP statement
ROLLBACK WORK (or, in Native SQL, the database-specific equivalent).

(C) SAP AG BC411 27-6
32Database View
ABAP Workbench (BC-DWB)
A type of view in the ABAP Dictionary.
Database views are implemented using an equivalent view in the underlying database system.
33Development Class
ABAP Workbench (BC-DWB)
Group of logically related development objects. A development class contains all the objects which must be
corrected and transported as a whole. The objects which make up a transaction usually belong to one development
class. Customer development classes begin with 'Y' or 'Z'.

E
34EDI
IDoc Interface / Electronic Data Interchange (CA-EDI)
Electronic Data Interchange.
Business-to-business electronic data interchange (for example, sales documents). The business partners may be in
different countries, and might be using different hardware, software, and communication services. The data is
formatted according to fixed standards.
In addition, SAP ALE enables companies to exchange data internally.
35Event Keyword
ABAP Workbench (BC-DWB)
Type of ABAP keyword.
An event keyword defines a processing block in an ABAP program. The processing block is processed when the
particular event occurs.
Examples. GET, START-OF-SELECTION, AT SELECTION-SCREEN.
F
36Function Group
ABAP Workbench (BC-DWB)
Group of functions that logically belong together and use a shared program context at runtime.
The function group is a container program for the function modules that it contains. Functions that work with the
same data are usually all included in the same function group.
Function groups are an administrative unit within the Function Builder.
37Function Module
ABAP Workbench (BC-DWB)
Reusable function.
Function modules are external subroutines that you maintain centrally in the Function Builder, and which can be
called from any ABAP program. This allows you to avoid redundancy in your coding and makes programming
more efficient.
Unlike normal subroutines, function modules have a defined interface.
38Functional Area
Basis Services/Communications Interfaces (BC-SRV)
You can use ABAP Query to define reports without any previous programming knowledge. When you create a
query, you must assign it to a functional area, which determines the tables and fields that the query can use.
Functional areas in ABAP Query are usually subsets of logical databases.
39Functional Group
Basis Services/Communications Interfaces (BC-SRV)
Element of ABAP Query
A functional group is a collection of fields that forms a logical unit. You use them to provide users with a
selection of fields so that he or she does not need to sort through all of the fields in a logical database in order to
create a query.
You must assign a field to a functional group in order for it to be used later in a query.


(C) SAP AG BC411 30-7
G
40GUI Status
Graphical User Interface (BC-FES-GUI)
Main element of the graphical user interface.
A GUI status consists of:
A menu bar with menus
A standard toolbar
An application toolbar
Functions, and function key settings

H
41Hide Area
ABAP Workbench (BC-DWB)
Main memory area for storing key fields of a line in a report list.
If you want to select further data based on a line selection, the system can find the key fields that it requires in the
hide area.
You must place the key fields into the hide area yourself using the HIDE statement.

I
42I con
Graphical User Interface (BC-FES-GUI)
Graphical representation of an object or functions. Icons are small colored bitmaps that are used for pushbuttons,
checkboxes, and radio buttons, either with or without text.
Unlike symbols, icons always have the same size, which is one of two, selected automatically by the system
according to the font size.


(C) SAP AG BC411 32-8
43I DES
IMG (BC-BE-IMG)
The R/3 International Demonstration and Education System.
IDES contains several fictional companies that model the different business processes in the R/3 System. Simple
user guides and sample master and transaction data allow you to simulate a wide range of scenarios. This makes
IDES a useful tool for training your project team.
44I nheritance
ABAP Workbench (BC-DWB)
Data Modeler (BC-RMC-DMO)
Passing of attributes from one data object to another.
Attributes can either be passed generally (all attributes), or by copying individual characteristics.
Workflow (BC-BMT-WFM)
is a relationship between object types in which shared attributes and methods of supertypes are passed
automatically to subtypes.
Subtypes usually have the same key fields as the supertype, but a more wide-ranging function.
45I nternal Table
ABAP Workbench (BC-DWB)
Temporary data structure that exists during the runtime of a program.
Internal tables are one of two structured data types in ABAP. They consist of any number of table lines, each of
which has the same structure. They may or may not have a header line.
The header line is a structure, and serves as a work area for the internal table. The data type of the line can be
either elementary or structured.

L
46List
Graphical User Interface (BC-FES-GUI)
Standard function in the R/3 System used to display lists.
47List Header
ABAP Workbench (BC-DWB)
First line of the screen in a list.
The list header is often the same as the title of the program. However, you can maintain it independently of the
program title.
48Logical Database
ABAP Workbench (BC-DWB)
Special ABAP program that combines the contents of certain database tables.
You can attach a logical database to an ABAP report program as one of the program attributes. It supplies the
report with a set of hierarchically-structured table lines, which can come from different database tables. This saves
the programmer from having to retrieve the data him- or herself.
The term logical database applies not only to the program, but also to the data itself.
49Logical Unit of Work
ABAP Workbench (BC-DWB)
Inseparable sequence of database operations, working on the all-or-nothing principle, where the operations are
either all carried out, or all canceled.
From the point of view of the database system, logical units of work (LUWs) are crucial to the integrity of the
data in the database.

M
50Menu
Graphical User Interface (BC-FES-GUI)
Graphical element for choosing functions.

(C) SAP AG BC411 33-9
Menus are graphical elements that present the user with a series of options, each of which triggers a function in
the system. This can include opening a submenu.
There are two types of menu:
Menu bars
Action menus
To choose a menu entry, single-click it with the mouse, or position the cursor on it using the arrow keys and press
ENTER.
51Menu Bar
Graphical User Interface (BC-FES-GUI)
Element of the graphical user interface.
The menu bar appears directly below the title bar in the primary window.
When you choose an entry in the menu bar, the system opens the corresponding action menu below the entry. You
can put up to 6 menus in the menu bar, to which the system automatically adds the System and Help menus.
52Menu Exit
ABAP Workbench (BC-DWB)
Placeholder in the standard system for customers own menu entries.
Menu exits allow you to link your own functions to menu entries reserved in the standard system as part of the
enhancement concept (Transaction CMOD). You use an associated function module exit to implement the
function.
53Menu Painter
ABAP Workbench (BC-DWB)
Development tool in the ABAP Workbench for designing the graphical user interface of an ABAP program. Each
GUI consists of a title and a GUI status.
The GUI status contains the following elements:
Menu bar with menus
Standard toolbar
Application toolbar
Functions, assigned to function keys.
54Message Class
ABAP Workbench (BC-DWB)
Collection of messages that are used by a particular application.
Each ABAP program is linked to a message class. The name of the class can be up to 20 characters.
55Metadata
ABAP Workbench (BC-DWB)
Data that describes other data.
Metadata are data definitions, usually stored in a data dictionary.
56Modal Dialog Box
Graphical User Interface (BC-FES-GUI)
Dialog box that must be processed or canceled before the screen behind it can be processed further.
57Modification
ABAP Workbench (BC-DWB)
Customer-specific change to an R/3 Repository object.
When you upgrade the system, you need to check, and possibly update, your modified objects.

P
58Processing Block
ABAP Workbench (BC-DWB)
Group of program statements that are processed together as a unit at a particular point.
ABAP is an event-oriented language (the flow of a program is controlled by events). Program sections are
therefore grouped into processing blocks, which are assigned to particular events. Events are triggered in the
program using event keywords.

(C) SAP AG BC411 33-10
A processing block consists of all of the statements between two event keywords or between an event keyword
and a FORM statement.
59Program
ABAP Workbench (BC-DWB)
A set of statements that provides a solution to a task.
A program consists of a set of statements that are interpreted and executed by a computer.


(C) SAP AG BC411 36-11
Q
60Query
Basis Services/ Communication Interfaces (BC-SRV)
Report that users without programming expertise can generate using ABAP Query.
There are three different types of query:
Basic list
Statistic
Ranked list

R
61R/3 Repository
ABAP Workbench (BC-DWB)
Central store for development objects in the ABAP Workbench.
Development objects include ABAP programs, screens, documentation, and so on.
62R/3 Repository I nformation System
ABAP Workbench (BC-DWB)
Information system that enables you to find information about al of the development objects in the R/3 System
and the relationships between them.
The user interface of the R/3 Repository Information System displays objects in a hierarchical structure similar to
a file manager.
The R/3 Repository Information allows you to:
Create lists of programs, tables, fields, data elements, and domains.
Find out where tables and fields are used in ABAP programs and screens.
Display foreign key relationships.
63RFC
ABAP Workbench (BC-DWB)
Remote Function Call.
RFC is an SAP interface protocol based on CPI-C. This simplifies the process of programming communication
between systems.
RFC allows you to call and execute predefined functions in a remote system. They have built-in communication
control, parameter passing, and error handling.

S
64SAP Memory
ABAP Workbench (BC-DWB)
Global, user-specific memory.
You address the SAP memory using SPA/GPA parameters.
65Screen
ABAP Workbench (BC-DWB)
A screen (in the sense of a 'dynpro' or DYNamic PROgram) consists of a screen and its underlying flow logic.
The main components of a screen are:
attributes (e.g. screen number, next screen)
layout (the arrangement of texts, fields, and other elements)
field attributes (definition of the properties of individual fields)
flow logic (calls the relevant ABAP modules)
66Selection Screen
Graphical User Interface (BC-FES-GUI)
Screen in an ABAP report program.

(C) SAP AG BC411 37-12
You use the selection screen to enter the selection criteria by which the system should retrieve data from the
database.
67Selection Table
ABAP Workbench (BC-DWB)
Internal table containing selection criteria.
The system creates a selection table for each SELECT-OPTIONS statement that you use in an ABAP report
program. They allow you to save complex selections in a standard format.
T
68Table
ABAP Workbench (BC-DWB)
Tabular collection of data. The definition is stored in the ABAP Dictionary, the contents are stored in the
database.
A table consists of columns (sets of data values with the same type) and lines (data records).
Each line of a table can be identified uniquely using a field or a combination of fields.
69Table Work Area
ABAP Workbench (BC-DWB)
Data object created in an ABAP program using the TABLES statement.
A table work area is a structure with the same construction as the corresponding table in the ABAP Dictionary.
70Task
ABAP Workbench (BC-DWB)
Information carrier in the Workbench Organizer for entering and managing all changes to Repository objects and
Customizing settings performed by employees within a development project.
A task is assigned to a change request
71Text Symbol
ABAP Workbench (BC-DWB)
Text constant that you create and maintain outside programs.
You use text symbols instead of text literals to make texts easier to maintain and translate.
Each text symbol is identified by a three-character code.
72Title Bar
Graphical User Interface (BC-FES-GUI)
Element in the graphical user interface.
The title bar is the top line of every primary window and dialog box in the R/3 System.
It contains the title of the window, and icons that allow you to control the window size.
73Transaction
ABAP Workbench (BC-DWB)
A logical process in the R/3 System.
From the users point of view, a transaction is a logical unit (for example, to generate a list of customers, change a
customers address, create a reservation for a flight, or run a program). From the programmers point of view, it is
a complex object, consisting of a module pool and a set of screens. You start transactions using a transaction code.
After logging onto the R/3 System, there are three levels - the SAP level, work area level, and application level. A
transaction is a process at application level. To start the transaction, you can either use the menus or enter a four-
character transaction code. Using the transaction code saves you having to remember the menu path.
Example:
To start a program from the ABAP Workbench, you can either choose Tools ABAP Workbench ABAP
Editor, or enter SE38 in the command field.
74Transaction Code
ABAP Workbench (BC-DWB)
Sequence of up to twenty characters that identifies an SAP transaction.
When you enter a transaction code in the command field, the corresponding transaction is started in the R/3
System.
For example, the transaction code SM31 identifies the transaction Display Table.

(C) SAP AG BC411 37-13
75Transparent Table
ABAP Workbench (BC-DWB)
Table type in the ABAP Dictionary.
You define transparent tables in the ABAP Dictionary. They are created in the database.
76Transport Request
Computing Center Management System (BC-CCM)
Document for copying corrections between different kinds of system.
Released corrections are collected in a transport request. When you release the request, it is transported.
For example, you can transport corrections from an integration system into a consolidation system.

(C) SAP AG BC411 39-14

77Typing
ABAP Workbench (BC-DWB)
Function in the ABAP Editor that enables you to avoid unnecessary type conversions in ABAP programs.
When the function is called, the system analyzes the parameters in the PERFORM statements and searches in the
FORM statements for formal parameters with similar technical attributes ( type and length). Whenever it finds
two parameters that correspond, it suggests a type for the formal parameter in the FORM statement. You can then
change your coding accordingly.
78User Group
Basis Services/Communication Interfaces (BC-SRV)
Object in ABAP Query.
The assignment to a user group determines which queries a user is allowed to execute and/or maintain.
79User I nterface
ABAP Workbench (BC-DWB)
Technical features and functions available to the user to exchange information with the computer system.
In the R/3 System, you design the user interface in the ABAP Workbench with the Screen Painter and the Menu
Painter.

V
80View
ABAP Workbench (BC-DWB)
Application-specific view of different tables in the ABAP Dictionary.
When you create a table, you assign a key according to technical criteria. However, the key fields may be
insufficient for solving certain problems, or some of them may be irrelevant. In this case, you can use a view to
access part of a table or a series of tables.

W
81Web Reporting
Web Basis (CA-B-WEB)
WebRFC applicat allowing Internet users to access information in the R/3 System.
Users can access SAP reports, display lists, and navigate through reporting trees using URLs.

You might also like