Advanced ABAP Programming
Advanced ABAP Programming
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
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