BC411 - Advanced ABAP Programming

488
BC411 Advanced ABAP Programming BC411 R/3 System Release 46B 24.06.2002 0

Transcript of BC411 - Advanced ABAP Programming

Page 1: BC411 - Advanced ABAP Programming

BC411 Advanced ABAP Programming BC411

R/3 System Release 46B 24.06.2002

0

Page 2: BC411 - Advanced ABAP Programming

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

Page 3: BC411 - Advanced ABAP Programming

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

Page 4: BC411 - Advanced ABAP Programming

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

Page 5: BC411 - Advanced ABAP Programming

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

Page 6: BC411 - Advanced ABAP Programming

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

Page 7: BC411 - Advanced ABAP Programming

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

Page 8: BC411 - Advanced ABAP Programming

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

Page 9: BC411 - Advanced ABAP Programming

Internal Subroutine III ................................................................................................................. 15-7 External Subroutine I .................................................................................................................. 15-8 External Subroutine II ................................................................................................................. 15-9 External Subroutine III .............................................................................................................. 15-10 Function Module I ..................................................................................................................... 15-11 Function Module II .................................................................................................................... 15-12 Function Module III ................................................................................................................... 15-13 Screen, CALL SCREEN, CALL SELECTION-SCREEN I ......................................................... 15-14 Screen, CALL SCREEN, CALL SELECTION-SCREEN II ........................................................ 15-15 Screen, CALL SCREEN, CALL SELECTION-SCREEN III ....................................................... 15-16 Module I.................................................................................................................................... 15-17 Module II................................................................................................................................... 15-18 Module III.................................................................................................................................. 15-19 Event I ...................................................................................................................................... 15-20 Event II ..................................................................................................................................... 15-21 Event III .................................................................................................................................... 15-22 Dialog Module I......................................................................................................................... 15-23 Dialog Module II........................................................................................................................ 15-24 Dialog Module III....................................................................................................................... 15-25 Transaction I............................................................................................................................. 15-26 Transaction II............................................................................................................................ 15-27 Transaction III........................................................................................................................... 15-28 Program, SUBMIT I .................................................................................................................. 15-29 Program, SUBMIT II ................................................................................................................. 15-30 Program, SUBMIT III ................................................................................................................ 15-31 LEAVE TO LIST PROCESSING I............................................................................................. 15-32 LEAVE TO LIST PROCESSING II............................................................................................ 15-33 LEAVE TO LIST PROCESSING III........................................................................................... 15-34

String Processing: Contents........................................................................................................... 16-1 Unit Objectives ........................................................................................................................... 16-2 String Processing ....................................................................................................................... 16-3 Searching in a String .................................................................................................................. 16-4 Manipulating Strings ................................................................................................................... 16-5 Joining and Splitting Strings ....................................................................................................... 16-6 String Comparisons .................................................................................................................... 16-7 Summary .................................................................................................................................... 16-8

Bit Processing: Contents................................................................................................................ 17-1 Unit Objectives ........................................................................................................................... 17-2 Sets as Bit Patterns .................................................................................................................... 17-3 SET BIT and GET BIT ................................................................................................................ 17-4 Assigning Values to X Fields ...................................................................................................... 17-5 Bit Calculations........................................................................................................................... 17-6 Bit Comparisons ......................................................................................................................... 17-7 Example: Representing Flights with an X Field........................................................................... 17-8 Summary .................................................................................................................................... 17-9

Page 10: BC411 - Advanced ABAP Programming

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

Page 11: BC411 - Advanced ABAP Programming

© SAP AG 1999

BC411 Advanced ABAP ProgrammingAdvanced ABAP Programming

© SAP AG

BC 411BC 411Advanced ABAP Advanced ABAP Programming Programming

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

Page 12: BC411 - Advanced ABAP Programming

© SAP AG

R

Copyright

Copyright 1998 SAP AG. All rights reserved.

Neither this training manual nor any part thereof maybe copied or reproduced in any form or by any means,or translated into another language, without the priorconsent of SAP AG. The information contained in thisdocument 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.

Page 13: BC411 - Advanced ABAP Programming

© SAP AG

R

R/3 Integration Model

R/3R/3Client/Server

ABAPClient/Server

ABAP

COControlling

COControlling

AAAsset

Accounting

AAAsset

Accounting

PSProjectSystem

PSProjectSystem

WFWorkflow

WFWorkflow

ISIndustry

Solutions

ISIndustry

Solutions

MMMaterials

Mgmt

MMMaterials

Mgmt

HRHuman

Resources

HRHuman

Resources

SDSales &

Distribution

SDSales &

Distribution

PPProductionPlanning

PPProductionPlanning

QMQualityMgmt

QMQualityMgmt

FIFinancial

Accounting

FIFinancial

Accounting

PMPlant

Maintenance

PMPlant

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.

Page 14: BC411 - Advanced ABAP Programming

© SAP AG

R

ABAP WorkbenchLevel 3

BC420 2 daysInterface Programmingfor Data TransferBC430 2 daysABAP Dictionary

BC405 5 daysTechniques of List ProcessingBC410 5 daysTransaction Processing

BC415 3 daysCommunication Interface Programmingin ABAP

BC460 3 daysSAPscript: FormsDesign and TextManagement in R/3

BC425 2 daysEnhancements andModificationsBC440 5 daysDeveloping Internet Application Components(IAC)

BC411 5 daysAdvanced ABAPProgramming

Level 2

BC400 5 daysABAP WorkbenchBasics

Page 15: BC411 - Advanced ABAP Programming

© 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

Page 16: BC411 - Advanced ABAP Programming

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

Page 17: BC411 - Advanced ABAP Programming

© SAP AG

R

Introduction: Contents

Course goal

Course objectives

Contents

Overview diagram

Overall business scenario

Page 18: BC411 - Advanced ABAP Programming

(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 :

Page 19: BC411 - Advanced ABAP Programming

(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

Page 20: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 1-4

© SAP AG

R

Contents I

Unit Introduction Unit Contexts

Unit Development process and Unit ABAP Open SQLdevelopment tools

Unit Types Unit Exceptions and message handling

Unit Field symbols Unit Modularization units

Unit Internal tables Unit Generating dynamic programs

Unit Object-oriented programmingin ABAP

Unit ABAP Objects

Introduction

Page 21: BC411 - Advanced ABAP Programming

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

Appendix C Further information about ABAP Open SQL

Appendix D Further information about modularization units

Appendix E String processing

Appendix F Bit processing

Appendix G Data clusters

Exercises

Solutions

Glossary

Appendices

Page 22: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 1-6

© SAP AG

R

Overview Diagram

Complex problems:

What ABAP constructionscan I use to solve the problem?

Page 23: BC411 - Advanced ABAP Programming

(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

Page 24: BC411 - Advanced ABAP Programming

© SAP AG

R

Development Process and Tools: Contents

Development process for an ABAP program

Static checksSyntax check

Extended program check

Runtime errors

Debugger

Performance toolsABAP runtime analysis

GET RUN TIME

SQL TRACE

Page 25: BC411 - Advanced ABAP Programming

(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 ABAPprogram Check the syntax of a programRun an extended program check for a program Analyze a short dumpUse the most important functions of the DebuggerDetermine the flow and runtime of a program usingruntime analysisMeasure runtime using the GET RUN TIME statementAnalyze database access using the main functions ofthe SQL Trace tool

Page 26: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-3

© SAP AG

R

Development Process for an ABAP Program

TRDIRTRDIRattributesattributes

ProgramABAP Development

Source codeSource code

Syntax checkExtended program check

Syntax checkExtended program check

ErrorsWarningsLoad Generated form

Page 27: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-4

© SAP AG

R

Types of Program AnalysisErrorError

Static analysisStatic analysisWarningWarning

Syntax checkSyntax check

Database accessDatabase access

DynamicanalysisDynamicanalysis

Memory contentsMemory contents

General memory allocationGeneral memory allocation

Program interruptionProgram interruption

DebuggingDebugging

Dump analysisDump analysis Runtime errorRuntime error

Extended program checkExtended program check Error Error

WarningWarning

MessageMessage

SQL TraceSQL Trace

Program flowProgram flow

Runtime measurementRuntime measurement

Memory requirementsMemory requirements

ABAP runtimeanalysis

ABAP runtimeanalysis

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.

Page 28: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-5

© SAP AG

R

Syntax Check

*& REPORT sapsyntaxcheck.INCLUDE syntaxchecktop.INCLUDE syntaxcheckf01.

*& REPORT sapsyntaxcheck.INCLUDE syntaxchecktop.INCLUDE syntaxcheckf01.

*INCLUDE SYNTAXCHECKF01

PERFORM subprog.*Form Routine not defined *in program.

*INCLUDE SYNTAXCHECKF01

PERFORM subprog.*Form Routine not defined *in program.

*& INCLUDE SYNTAXCHECKTOP. REPORT syntaxcheck.

*& INCLUDE SYNTAXCHECKTOP. REPORT syntaxcheck.

Syntax errorSyntax 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.

Page 29: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-6

© SAP AG

R

Syntax Check

*& INCLUDE SAPBC411D_SYNTAXCHECKF01.

PERFORM subprogram.FORM subprogram.SELECT ...ENDSELECT.

ENDFORM.PERFORM u_pgm.

*& INCLUDE SAPBC411D_SYNTAXCHECKF01.

PERFORM subprogram.FORM subprogram.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.

Page 30: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-7

© SAP AG

R

Syntax Errors

Extendedprogram check

Extendedprogram check

Warnings from the syntax checkWarnings from the syntax check

PERFORM/FORM interfacesPERFORM/FORM interfacesCALL FUNCTION interfacesCALL FUNCTION interfaces

Screen consistencyScreen consistencySTATUS and TITLEBARSTATUS and TITLEBAR

StringsStringsField attributesField attributes

ConversionsConversions

The standard syntax check leaves out many checks to save runtime. Only the extended program check provides a complete examination of your program that includes the interfaces to other programs that it calls.

Errors in the extended program check (other than inaccessible coding) cause runtime errors, and must therefore be corrected. You should also correct warnings. If warnings occur that you want to ignore (for example, they occur because of dynamic calls in your program), you can use pseudo-comments to suppress them ("+EC*). For further information, refer to the extended help for the extended program check transaction.

As a programmer, you should always run the extended program check as part of your development process. A program is only finished once you have corrected all of the errors and warnings (although a few non-critical messages may remain).

The extended syntax check, like the standard check, is a static check. This means that runtime errors may still occur in your program. For example, if your program contains the statement CALL FUNCTION field, the static check cannot tell whether the value of field corresponds to a valid function module name. However, if you write CALL FUNCTION 'JOHN_SMITH', the extended program check will look to see if the function module 'JOHN_SMITH' exists.

Page 31: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-8

© SAP AG

R

Runtime Errors

Runtime errorsRuntime errors

What happened?What happened?

What can you do?What can you do?

Error analysisError analysis

System environmentSystem environment

How to correct the errorHow to correct the error

Info: Where error occurredInfo: Where error occurred

Chosen variablesChosen variables

Active calls/ eventsActive calls/ events

......

Overview

Debugger

Internal errorsInternal errors

Installation and environment/resourceerrors

Installation and environment/resourceerrors

Errors in applicationprograms

Errors in applicationprograms

Short textShort 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.

Page 32: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-9

© SAP AG

R

Dump AnalysisDump Analysis

MaterialManagement

Overview Statistics

DisplayPrint

KeepRelease

ReorganizationReorganization

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.

Page 33: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-10

© SAP AG

R

Dynamic Analysis

Dynamic analysis Debugging

SQL Trace

ABAP runtimeanalysis

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.

Page 34: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-11

© SAP AG

R

Debugging Mode

BREAK-POINT <value>.BREAK-POINT <value>.1. Program statementRepository BrowserRepository Browser

Program??

Goto System HelpEdit

Test/Execute

SAPBC411 SAP Training: BC411

Object type development classProgramsContext_I_C_GEOGR_DISTANCEContext_I_C_GEOGR_DISTANCE

BREAK-POINT <Value>.BREAK-POINT <Value>.1. Program statementABAP Editor: Initial ScreenABAP Editor: Initial Screen

Program Goto System HelpEdit

Debugging

SAPBC411D_TESTProgram Create

ExecuteSub-objects

Source codeVariants

Attributes

Documentation

/H ......Utilities >...

Debugging ...

There are four different ways of starting the Debugger: - From the Repository Browser, by choosing Test/Execute. - From the ABAP Editor by choosing Debugging. - From a transaction, by entering /h in the command field. - From any screen by choosing System -> Utilities -> Debugging. - By setting breakpoints in the source code and starting the program.

Page 35: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-12

© SAP AG

R

The Most Important Debugging Functions

Single step

Continue

Breakpoint

Hexadecimaldisplay

Replace function

Processes the next line of the program.

Continues processing until thenext breakpoint or the end of theprogram occurs.

Displays a screen on which you can set breakpoints.

Use this button to displaythe field contents in hexadecimal form.

Allows you to change the contents of a field.

Processes the next line of the program.

Continues processing until thenext breakpoint or the end of theprogram occurs.

Displays a screen on which you can set breakpoints.

Use this button to displaythe field contents in hexadecimal form.

Allows you to change the contents of a field.

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

Page 36: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-13

© SAP AG

R

The Most Important Debugging Functions II

Up to five watchpoints linkedwith relational operators.

You can expand structured fields by double-clicking.

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

Up to five watchpoints linkedwith relational operators.

You can expand structured fields by double-clicking.

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

Pushbutton for expanding substructures

Displaying complexinternal tables

Watchpoint

You can create watchpoints in the Debugger. These allow you to interrupt your program when the contents of a particular field change. You can link watchpoints using logical expressions containing either constant values or field contents.

You can expand a data object that contains a structure as one of its components by double-clicking it. The Debugger also allows you to display complex internal tables.

Page 37: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-14

© SAP AG

R

Debugger: Overview SAP R/3

Debugging??

Bezeichnungen

Goto Breakpoint Settings Development System Help

Main program Test

Source code of Teststart-of-selection

Field namescarrid

Field contents

Crew-Flight Table[2x272]

Fldate 19980810

Crew ********************************************

Select Carrid From SpfliCrew_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.

Page 38: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-15

© SAP AG

R

Expanding Substructures

Structured field

No

Length

Component name Type Length Contents

1 Carrid C 3 LH2 Connid N 43 Crew h 84 Crew-Name C 30 Miller4567

Component name

272

FLIGHT_TABLE

Crew-FunctionCrew-FlightCrew-Flight-No1

ChN

20

4Crew-Flight-No2

8 19980509 Fldate

0400

Pilot

04000402N 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.

Page 39: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-16

© SAP AG

R

Breakpoints in Programs

BREAK-POINT <value>.BREAK-POINT <value>.

1. ABAP statement

SetDeleteDisplay breakpoint

SetDeleteDisplay breakpoint

2. Editor function

BREAK-POINT <value>.BREAK-POINT <value>.

2. Function BreakpointsBREAKPOINTS anzeigen

setzenlöschen

BREAKPOINTS anzeigensetzenlöschen

SAP R/3SAP R/3Program

??

Bezeichnungen

Goto System HelpEdit

1 PROGRAM sapbc411d_debugger.2 INCLUDE bc411d_debuggertop.3 SELECT carrid connid FROM sflight INTO 4 CORRESPONDING FIELDS OF TABLE itab5 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.

Page 40: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-17

© SAP AG

R

Breakpoints in the Debugger

Breakpoints

No Program Line Statement/Event/... Counter

2 SAPBC411D_DEBUG 10 start-of-selection3 SAPBC411D_DEBUG 70 select45678910

1 SAPBC411D_DEBUG 1 appendStop

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.

Page 41: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-18

© SAP AG

R

Watchpoints

Watchpoints

No Program Field name Comparsion field/value

Logical operator between watchpoints

L Op Field

1 SAPBC411D_DEBUG str-cx

2 str-i =x

3 i >x

4 sy-tabix =x

5 str-c <x

Current contents of the last watchpoint reached:

SAPBC411D_DEBUG i 4

x sy-index1

5

or and

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

Page 42: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-19

© SAP AG

R

Runtime Measurement

Runtime Analysis

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

Page 43: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-20

© SAP AG

R

Runtime Analysis I

Runtime analysisRuntime analysis

Report: RSDEMO00Report: RSDEMO00

MeasureMeasure AnalysisAnalysis

Start End

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

Page 44: BC411 - Advanced ABAP Programming

(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

Overallhit list

Table hitlist

Runtime analysis

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

Page 45: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-22

© SAP AG

R

ABAP programsABAP programs

Modularization UnitsModularization Units

Program/ReportProgram/Report

Modules (screens)Modules (screens) MODULEMODULE

SubroutinesSubroutines PERFORMPERFORM

MethodsMethods CALL METHODCALL METHOD

EventsEvents RAISE EVENTRAISE EVENT

Function modulesFunction modules CALL FUNCTIONCALL FUNCTION

ContextsContexts SUPPLY/DEMANDSUPPLY/DEMAND

ReportsReports SUBMITSUBMIT

Measurable Functions I

ABAP program analysis is based on: modularization units, and the statements listed on the next page.

Page 46: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-23

© SAP AG

R

SAP SQLSAP SQL

Database/file accessDatabase/file accessSELECT/INSERT/UPDATE/SELECT/INSERT/UPDATE/DELETEDELETE

Direct SQL interfaceDirect SQL interface EXEC SQLEXEC SQL

Data clusterData cluster EXPORT/IMPORTEXPORT/IMPORT

Sequential filesSequential files TRANSFER/READTRANSFER/READDATASETDATASET

ExtendingExtending APPEND/COLLECTAPPEND/COLLECT

ProcessingProcessing LOOPLOOP

SortingSorting SORTSORT

Internal tablesInternal tables

System timesSystem times

Load/generate programsLoad/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.

Page 47: BC411 - Advanced ABAP Programming

(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 RUNTIME ANALYZER ON/OFF statement.

Page 48: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-25

© SAP AG

R

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

PROGRAM xxx.DATA: t1 TYPE i,

t2 TYPE i,run_time TYPE i.

GET RUN TIME FIELD t1.

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

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.

Page 49: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-26

© SAP AG

R

Test Frame IREPORT sapbc411d_testframe.

TYPES: BEGIN OF result_line, text(60) TYPE c, time TYPE i,

END OF result_line. DATA: t1 TYPE i, t2 TYPE i, base_time TYPE i, res_time(8) TYPE p DECIMALS 1, i TYPE i, result TYPE result_line OCCURS 10 WITH

HEADER LINE. PARAMETERS:

in_cnt TYPE i DEFAULT 100,out_cnt TYPE i DEFAULT 20.

* Specifc data for the measurement ...

REPORT sapbc411d_testframe.

TYPES: BEGIN OF result_line, text(60) TYPE c, time TYPE i,

END OF result_line. DATA: t1 TYPE i, t2 TYPE i, base_time TYPE i, res_time(8) TYPE p DECIMALS 1, i TYPE i, result TYPE result_line OCCURS 10 WITH

HEADER LINE. PARAMETERS:

in_cnt TYPE i DEFAULT 100,out_cnt TYPE i DEFAULT 20.

* Specifc data for the measurement ...

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

Page 50: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-27

© SAP AG

R

Test Frame II* Start measurementPERFORM fill_result USING:

’Base time’, "#EC NOTEXT’..Variant 1.......’, "#EC NOTEXT’..Variant 2.......’. "#EC NOTEXT

LOOP AT result.i = sy-tabix.result-time = 99999999.DO out_cnt TIMES.

GET RUN TIME FIELD t1.DO in_cnt TIMES.

PERFORM i OF f0 f1 f2.ENDDO.GET RUN TIME FIELD t2.t2 = t2 - t1.IF t2 < result-time. result-time = t2.ENDIF.

ENDDO.

* Start measurementPERFORM fill_result USING:

’Base time’, "#EC NOTEXT’..Variant 1.......’, "#EC NOTEXT’..Variant 2.......’. "#EC NOTEXT

LOOP AT result.i = sy-tabix.result-time = 99999999.DO out_cnt TIMES.

GET RUN TIME FIELD t1.DO in_cnt TIMES.

PERFORM i OF f0 f1 f2.ENDDO.GET RUN TIME FIELD t2.t2 = t2 - t1.IF t2 < result-time. result-time = t2.ENDIF.

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 to c2 has a shorter runtime than the measurement accuracy of 1µs. In this case, you would run the statement several times and divide the total runtime by the number of loop passes).

You use the outer loop to determine the number of test runs, from which you then take the minimum runtime. This process should eliminate factors, such as changing work process, that can make individual measurements inaccurate.

Page 51: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-28

© SAP AG

R

Test Frame III

IF i = 1.base_time = result-time.

ELSE.SUBTRACT base_time FROM result-time.

ENDIF.MODIFY result.

ENDLOOP.LOOP AT result.t1 = result-time / in_cnt. WRITE: / result-text, res_time.ENDLOOP.

IF i = 1.base_time = result-time.

ELSE.SUBTRACT base_time FROM result-time.

ENDIF.MODIFY result.

ENDLOOP.LOOP AT result.t1 = result-time / in_cnt. WRITE: / result-text, res_time.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.

Page 52: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-29

© SAP AG

R

Test Frame IV*& FORM FILL_RESULT

FORM fill_result USING text.result-text = text.APPEND result.

ENDFORM.

*& FORM F0

FORM f0....

ENDFORM.

*& FORM F1 Variant 1

FORM f1.

ENDFORM.Statements for variant 1

*& FORM F2 Variant 2

FORM f2.

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

Page 53: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-30

© SAP AG

R

Database Access

ABAPProgram

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.

Page 54: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-31

© SAP AG

R

SQL Trace

Application server Database I/O

SQL Trace

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.

Page 55: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-32

© SAP AG

R

Trace Basic ListDebugging

??

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 0SPFLI

206 FETCH 6 0SPFLI

300 FETCH 0 100SPFLI

209 CLOSE 0 0SPFLI

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.

Page 56: BC411 - Advanced ABAP Programming

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

Page 57: BC411 - Advanced ABAP Programming

(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 00171235 001 AA 0064 1236 001 AZ 05551237 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.

Page 58: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 2-35

© SAP AG

R

Summary

In this unit, you have learned the typical steps involved in program development, in particular how to check programs using

Static checkRuntime check

and the most important functions for Dynamic program checks:

Runtime analysisThe GET RUN TIME statementSQL TraceDebugger

Page 59: BC411 - Advanced ABAP Programming

© 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

Page 60: BC411 - Advanced ABAP Programming

(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:

Page 61: BC411 - Advanced ABAP Programming

(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

ABAP

Dict

iona

ry

ABAP Pr

ogra

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.

Page 62: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-4

© SAP AG

R

Predefined ABAP Types

Data type Description Initial value Default Permittedlength length

P

I

F

N

C

DT

X

Num

eric

Alp

ha-n

umer

ic

REF TO

Packed number

Integer

Floating point number

Numeric stringNumeric string

TextText

Date YYYYMMDDDate YYYYMMDD

Time HHMMSSTime HHMMSS

HexadecimalHexadecimal

ReferenceReference

0

0

0.000

00...000...0

SpaceSpace

0000000000000000

000000000000

X‘00‘X‘00‘

--

8

4

8

11

11

88

66

11

--

1-16

4

8

1 1 -- max.max.

1 1 -- max.max.

88

66

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.

Page 63: BC411 - Advanced ABAP Programming

(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

IP((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 INT1 1 byte integer, value between 0 and 255 INT2 2 byte integer, value between -32767 and 32767 INT3 4 byte integer, value between -2177483647 and 2177483647 CURR Currency field. Corresponds to a DEC amount field.

Fields with this type must point to a reference field with type CUKY. CUKY Currency key referenced by a type CURR field. QUAN Quantity field. Corresponds to a DEC amount field.

Fields with this type must point to a reference field with type UNIT. UNIT Unit key referenced by a type QUAN field. PREC Accuracy of a QUAN field. FLTP Floating point number. NUMC Numeric text. May only contain digits.

Page 64: BC411 - Advanced ABAP Programming

(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. TIMS Time RAW Byte sequence. Fields with type RAW may only be up to 255 characters long in

tables. If you want to use longer RAW fields in tables, use the data type LRAW. LRAW Byte sequence of any length longer than 256 bytes. Fields of this type must

occur at the end of transparent tables and be preceded by a length field with type INT2 that is filled with the required length when the table is filled.

CLNT Client LANG Language key. This is displayed as a two-character code, but stored in the

database as a single character. It is converted using the exit ISOLA.

Page 65: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-7

© SAP AG

R

Calculations Using Numeric Types

REPORT sapbc411d_arithmetic.DATA: int1 TYPE i, int2 TYPE i,

pack1 TYPE p, float TYPE f.

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

ABAP performs calculations using either F, P, or I arithmetic. The arithmetic used is determined by the following rule:

F before P before IF 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 before P before I. This means that:

If at least one of the operands has type F, ABAP will use type F arithmetic. If there are no type F operands, but at least one type P operand, ABAP will use type P arithmetic. If there are no type F or P operands, ABAP will use type I arithmetic.

Note that: Operands with inbuilt functions (such as SQRT(…)) are type F. Numeric strings up to nine digits are type I, and numeric strings with ten or more digits are type P.

Page 66: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-8

© SAP AG

R

Summary of Declarative Statements

Input parameterPARAMETERS

ConstantCONSTANTS

TABLES

Table work area

TypeTYPES

SELECT-OPTIONSRANGES

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-OPTIONS Defines a selection criterion

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

Page 67: BC411 - Advanced ABAP Programming

(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 rule exists.

Compatible types can be assigned to each other without conversion.

Two elementary types are compatible when they have exactly the same type and length (and, for type P fields, the same number of decimal places).

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

Page 68: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-10

© SAP AG

R

Conversion Rules for Elementary Types

For MOVE, COMPUTE, and comparisons, there are conversion rules fFor MOVE, COMPUTE, and comparisons, there are conversion rules for all or all type combinations except type combinations except

T to D and vice versaT to D and vice versafor ABAP Objects (classes and interfaces)for ABAP Objects (classes and interfaces)

REPORT sapbc411d_performance_conversi.DATA: pack TYPE p DECIMALS 2 VALUE '100,00',

char5(5) TYPE c VALUE '12,34',char7(7) TYPE c VALUE '6789,00'.

MOVE char5 TO char5. "Types compatible(cost 2 microsec.)MOVE char5 TO char7. "Type conversion (cost 3 microsec.)MOVE char5 TO pack. "Type conversion (cost 11 microsec.)

Conversion rules exist for MOVE, COMPUTE and comparisons, but noConversion rules exist for MOVE, COMPUTE and comparisons, but not for t for the assignment of actual parameters to formal parameters in FORMthe 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.

Page 69: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-11

© SAP AG

R

Conversion Rule for Structure types

C

PROGRAM SAPBC41D_CONVERSION_OF_RECORD.DATA: BEGIN OF rec1,

text1(3) TYPE C VALUE 'AAA',text2(2) TYPE C VALUE 'BB',pack TYPE P DECIMALS 2 VALUE '2.26',text3(10) TYPE C VALUE 'YY',END OF rec1,BEGIN OF rec2,text1(5) TYPE C VALUE 'CCCCC',pack TYPE P DECIMALS 2 VALUE '72.34',text3 TYPE C VALUE 'Z',END OF REC2.

MOVE REC1 TO REC2.

REC1

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.

Page 70: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-12

© SAP AG

R

Information About an Object at Runtime

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

line_count TYPE I.

SELECT * FROM sflight INTO TABLE flightinfo_list.DESCRIBE TABLE flightinfo_list LINES line_count.

DESCRIBE FIELD <f> LENGTH <len>TYPE <type> [COMPONENTS <n>]OUTPUT-LENGTH <len>DECIMALS <n>.

DESCRIBE TABLE <itab> LINES <lines> [OCCURS <n>].

CARRID CONNID ...Internal table FLIGHTINFO_LIST

LINE_COUNT

4

AAAAAAAA

0017001700260026

The DESCRIBE FIELD statement allows you to find out the following runtime information (RTTI = runtime type information) about any data object:

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

Page 71: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 3-13

© SAP AG

R

Summary

You can create data types either locally in a program or systemwide in the ABAP Dictionary.

ABAP has three numeric types (P,I,F), five non-numeric types (N,C,D,T,X), and a reference type (REF TO).

Each ABAP Dictionary type is converted by the ABAP runtime environment into a numeric or non-numeric ABAP data type.

The ABAP runtime system has type compatibility rules for MOVE, COMPUTE, comparisons of data objects, and the assignment of actual parameters to formal paramters. There are type conversion rules for MOVE, COMPUTE, and comparisons of data objects.

Page 72: BC411 - Advanced ABAP Programming

© SAP AG

R

Field Symbols: Contents

Pointers and field symbols

Using field symbols

Defining and assigning field symbols

Page 73: BC411 - Advanced ABAP Programming

(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

Page 74: BC411 - Advanced ABAP Programming

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

Page 75: BC411 - Advanced ABAP Programming

(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 <fs1> to a field symbol <fs2>, <fs1> takes the value of the data object to which <fs2> refers (value semantics).

- Field symbols in ABAP are always dereferenced, that is, they always access the referenced data object. If you want to change the reference yourself in ABAP, you can use the ASSIGN statement to assign field symbol <fs1> to field symbol <fs2>.

Position in a data structure Field symbols in ABAP are defined using the FIELD-SYMBOLS statement. However, the statement does not define any data type of the ABAP type concept. This means that you cannot use field symbols for chained lists or trees. Instead, chained lists can be programmed very elegantly in ABAP using internal tables.

Page 76: BC411 - Advanced ABAP Programming

(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 HSFLIGHT-CARRID

field_nameS F L I G H T - C A R R I D ...

Dynamic offset and length for a stringDynamic offset and length for a string

Dynamic ASSIGN for any Dynamic ASSIGN for any data objectdata object

Processing components of a Processing components of a structurestructure

Addressing fields whose name is Addressing fields whose name is unknown until runtimeunknown 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 .

Page 77: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-6

© SAP AG

R

Using Field Symbols (1)

0

15

15

15 15

17 17

17

REPORT sapbc411d_field_symbols.REPORT sapbc411d_field_symbols.

DATA counter TYPE i.

FIELD-SYMBOLS <fs> LIKE counter.

counter = 15.

ASSIGN counter TO <fs>.

WRITE : / counter, <fs>.

<fs> = 17.

WRITE : / counter, <fs>.

FIELD-SYMBOLS <fs> [TYPE typ | LIKE s].

ASSIGN field TO <fs>.

You declare field symbols using the FIELD-SYMBOLS statement. They may be declared either with or without a specific type.

At runtime, you assign a field to the field symbol using the ASSIGN statement. All of the operations on the field symbol act on the field that is assigned to it.

When you assign a field to an untyped field symbol, the field symbol adopts the type of the field. If, on the other hand, you want to assign a field to a typed field symbol, the type of the field and that of the field symbol must be compatible.

A field symbol can point to any data object. From Release 4.5A, they can also point to lines of internal tables.

The brackets (<>) are part of the syntax. This makes it easy to distinguish field symbols from normal fields.

Page 78: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-7

© SAP AG

R

Using Field Symbols (2)

UNASSIGN <fs>.

IF <fs> IS ASSIGNED.

PROGRAM sapbc411d_field_symbols.PROGRAM sapbc411d_field_symbols.

UNASSIGN <fs>.

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

ELSE.WRITE 'Field symbol points nowhere'(002).

ENDIF.

Use the expression <fs> IS ASSIGNED to find out whether the field symbol <fs> is assigned to a field.

The statement UNASSIGN <fs> sets the field symbol <fs> so that it points to nothing. The logical expression <fs> IS ASSIGNED is then false. The corresponding negative expression is IF NOT <fs> IS ASSIGNED.

An unassigned, untyped field symbol <fs> behaves as though it were a constant with type C(1) and initial value. MOVE <fs> TO dest Transfers the initial value SPACE to the variable dest MOVE 'abc' TO <fs> Not possible, since <fs> is a constant

Page 79: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-8

© SAP AG

R

Assigning Parts of Strings DynamicallyREPORT sapbc411d_dyn_string_assign.DATA: text_line(30) VALUE ’ABCDEFGHIJKLMNOPQRSTUVWXYZ’,

short_text_line(5),start TYPE i,string_length TYPE i.

FIELD-SYMBOLS <fstring>.

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

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

<fstring>

CDEFG

12345AB12345HI...

Text_line

There are very few statements in which you may specify offset and length using variables (MOVE, WRITE… TO, actual parameters).

If you cannot use variables to specify offset and length, you can use a field symbol instead of the field, since you can always use variable offset and length in the ASSIGN statement.

The first time you use the ASSIGN statement for an untyped field symbol, it adopts the type of the field that you assign to it.

Page 80: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-9

© SAP AG

R

Processing Individual Characters in a String

REPORT sapbc411d_fs_string.DATA: string(15) TYPE c VALUE 'HUGO BOSS',

n TYPE i.FIELD-SYMBOLS <fs>.

n = STRLEN( string ).

ASSIGN string(1) TO <fs>.DO n TIMES.

WRITE: / <fs>.IF sy-index NE n.

ASSIGN <fs>+1 TO <fs>.ENDIF.ENDDO.

<fs>

H U G O B O S Sstring

...

The above program uses a loop to assign each individual character of a string to the field symbol <fs>. This is more efficient than the following algorithm, which uses variable offset to address the string: DO n TIMES. ASSIGN string+sy-index(1) TO <fs>. ENDDO.

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

Page 81: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-10

© SAP AG

R

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

field_name = 'SFLIGHT-CARRID'.ASSIGN (field_name) TO <tab_field>.IF sy-subrc EQ 0.

SELECT * FROM sflight.WRITE: / <tab_field>.

.

.

<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 field_name contains the name of the field to be assigned to the field symbol <tab_field>. Note that dynamic ASSIGN statements are very runtime-intensive.

You can assign an ABAP Dictionary field to the field symbol using the addition TABLE FIELD. The statement would then read (as in the above example) ASSIGN TABLE FIELD (field_name) TO <tab_field>. This shortens the runtime required by the statement, since the system knows that it does not have to search in the list of program fields.

After the ASSIGN statement, the return code field SY-SUBRC tells you whether a field was assigned to the field symbol:

SY-SUBRC = 0: The field in parentheses contained a valid field name. SY-SUBRC > 0: The field in parentheses did not contain a valid field name. The field symbol

continues to point to the data object to which it pointed before the ASSIGN statement.

Page 82: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-11

© SAP AG

R

Referring to Components of a Structure

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

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

FORM write USING rec.DO.

ASSIGN COMPONENT sy-index OF STRUCTURE rec TO <fs>.IF sy-subrc NE 0.

EXIT.ENDIF.WRITE <fs>.

ENDDO.ULINE.

ENDFORM.

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

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

FORM write USING rec.DO.

ASSIGN COMPONENT sy-index OF STRUCTURE rec TO <fs>.IF sy-subrc NE 0.

EXIT.ENDIF.WRITE <fs>.

ENDDO.ULINE.

ENDFORM.

ASSIGN COMPONENT OF STRUCTURE rec TO <fs>.

sflight LH 0400 12/31/1997 ...

<fs>

fieldnamefieldnamenn

You can never address a component of an untyped structure: FORM routine USING rec.

* ASSIGN ('rec-f') TO <fs>. "Unable to access components of untyped * structure ENDFORM. Instead, use ASSIGN COMPONENT f OF STRUCTURE rec TO <fs>.

This variant of the ASSIGN statement allows you to access the components of any structure. The corresponding components of the structure rec are assigned to the field symbol <fs>.

You can assign the components by their name or their index. If comp has type C or is a structure that does not contain an internal table, it is regarded as a

component name. Otherwise, it is interpreted as the component number. The statement returns a value of SY-SUBRC unequal to 0 if the specified component comp of structure rec could not be assigned to the field symbol.

In the above example, the subroutine write displays all of the components of the structure rec passed to it.

Page 83: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-12

© SAP AG

R

Changing the Field Type

PROGRAM sapbc411d_fs_type_change.PARAMETERS: packed(3) TYPE p DEFAULT '128',DATA: lastdigits(2) TYPE c,

len TYPE i.FIELD-SYMBOLS: <fs>.ASSIGN packed to <fs> TYPE 'X'.MOVE <fs>+2(1) TO lastdigits.WRITE: / lastdigit+1(1).

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

If a field symbol is untyped, you can use the TYPE addition to assign the type <type> to the field symbol <fs>. The output length of the field symbol is then adjusted to the correct length for that type.

You should only use the TYPE addition for typed fields if the type of the field field does not correspond to that of the field symbol <fs>. The type <type> must be compatible with the type of the field symbol. Since there is no type conversion with field symbols, the contents of field f must also be compatible with the type <type>.

Page 84: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 4-13

© SAP AG

R

Memory Protection

Commonpart 2

...

Table work area 2 Commonpart 1

All local data Table workarea 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.

Page 85: BC411 - Advanced ABAP Programming

(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

Page 86: BC411 - Advanced ABAP Programming

© 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

Page 87: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-2

© SAP AG

R

Unit Objectives

List the attributes that determine the type of an internal tableDecide which type of internal table is the most appropriate in a given situationDefine an internal tableWork with an internal tableExplain the difference between internal tables with and without header lines

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

Page 88: BC411 - Advanced ABAP Programming

(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 typeABAP

Array Chained list

Dynamictable

extension !!!

Internal tables, like structured fields, are structured data types. An internal table consists of any number of lines, all of which have the same type. Internal tables are comparable with the array concepts of other programming languages. If you insert or delete lines in an internal table, the system updates the link from each line to its new successor, just like in a chained list. The best way to regard internal tables is as an area of memory occupied by similar data.

Unlike arrays in other programming languages, internal tables are extended dynamically at runtime by the ABAP runtime environment.

There are two kinds of table structures - flat tables, whose structure contains no other tables or references, and deep tables, whose structure contains other internal tables or references. Similarly, we refer to the lines of an internal table as either flat or structured.

Page 89: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-4

© SAP AG

R

Uniqueness attributeUniqueness attribute

Internal Table Attributes

AA 0017 2,572 LH 0400 6,162

QF 0005 10,000 Index access

LH 0400 6,162

55

Key access

UA 0007UA 0007

Line typeLine type

Key sequenceKey sequence

Table typeTable type

CARRID CONNID DISTANCECARRID 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 itab INDEX 5. Example of access using key: READ TABLE itab WITH TABLE KEY carrid = 'UA'.

Page 90: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-5

© SAP AG

R

Table Types

Key access

Access costs linear increase logarithmic increase constantwith 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

nn

Table scan Binary search

Hashfunction

The table type defines how ABAP accesses individual table lines. There are three types of internal tables:

Standard tables. In a standard table, you can access data using either the table index or the key. If you use the key, the response time is in linear relation to the number of table entries. The key of a standard table is always non-unique.

Sorted tables. Sorted tables are always stored correctly sorted according to their key. You can access them using either the table index or the key. If you use the key, the response time is in logarithmic relation to the number of table entries, since the system uses a binary search to access the table. The key of a sorted table can be either unique or non-unique.

Standard tables and sorted tables are generically known as index tables. Hashed tables. You can only access a hashed table using its key - neither explicit nor implicit index

operations are allowed. The response time is constant, regardless of the number of table entries. The hash algorithm is administered internally. The key of a hashed table must be unique.

At runtime, you can find out the type of an internal table <itab> using the statement DESCRIBE TABLE <itab> KIND <k>.

Page 91: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-6

© SAP AG

R

Response Times ...

Example: Both tables have n entries

Standard table: Increases quadratically, O(n2)

double n runtime increases fourfold

Sorted table: Increases logarithmically, O(n log2n)

double n runtime increases by factor 2 + 2/log2n

Hashed table: Increases constantly, O(n)

double n runtime doubles

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

ENDLOOP.

LOOP AT OuterTable INTO OuterWa. ...READ TABLE InnerTable INTO InnerWa WITH 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.

Page 92: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-7

© SAP AG

R

Access Times

Loop costs for each internal table type

1

10

100

1000

1000

01E

+051E

+06

5 10 20 40 80 160 320 640 1280

Number of table entries: n

Tim

e in

mic

rose

cond

s

Standard 52 121 335 1,081 3,887 14,999 59,700 238,214 951,704Sorted 44 87 177 391 862 1,895 4,048 8,587 18,136Hashed 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.

Page 93: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-8

© SAP AG

R

Defining Internal Tables

DATA: <itab> TYPE of <linetype>WITH [UNIQUE | NON-UNIQUE] [INITIAL SIZE <n>][WITH HEADER LINE].

TYPES: <itabtype> TYPE of <linetype>[WITH [UNIQUE | NON-UNIQUE] ][INITIAL SIZE <n>].

<itabkind>

<keydef>

[STANDARD] TABLE | SORTED TABLE | HASHED TABLE additionally, for types: INDEX TABLE | ANY TABLE

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

<itabkind>

<keydef>

<keydef><itabkind>

AA 0017 2,572 LH 0400 6,162

QF 0005 10,000 LH 0400 6,162

CARRID CONNID DISTANCECARRID CONNID DISTANCE

SQ 0866 1,625 UA 0007 2,572

The statement TYPES <itabtype> TYPE <tabkind> OF <linetype> [WITH [UNIQUE | NON-UNIQUE] <keydef>] [INITIAL SIZE <n>] creates a data type with type <itabtype>, table type <tabkind>, and line type <linetype>.

Normally, you also specify a user-defined key in the form <f1> … <fn>. All of the fields in the key must have a flat structure. If the line type is not structured, you can use the addition KEY TABLE LINE to designate the entire line as the key. The addition DEFAULT KEY allows you to set the standard key as used in internal tables before Release 4.0.

You can use the UNIQUE or NON-UNIQUE addition to specify whether the table should be allowed to contain entries with duplicate keys.

If you know that your internal table will be smaller than 8KB, you can use the INITIAL SIZE <n> addition to reserve its initial memory space. The value <n> has no effect on the type check.

Unlike other user-defined ABAP data types, you do not have to specify the data type of an internal table fully. Instead, you can use the generic types INDEX TABLE and ANY TABLE. These types are useful for specifying the types of parameters in subroutines.

Page 94: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-9

© SAP AG

R

Internal Tables in Memory (1)Table header

Fixed size: 256 bytesDATA:itab TYPE TABLE OF struc.

•Dynamic data structure

•Empty table occupies 256 bytes (header)

Page 95: BC411 - Advanced ABAP Programming

(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 headerFixed size: 256 bytesDATA:itab TYPE TABLE OF struc.

•Dynamic data structure

•An empty table occupies 256 bytes (header)

•Maximum line length is 64K

APPEND wa TO itab. " 1. Eintrag 1

m

2

Page 96: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-11

© SAP AG

R

Internal Tables in Memory (3)

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

1st page:m entries (e.g.16)

2APPEND wa TO itab. " 1st entry

Table headerFixed size: 256 bytesDATA:itab TYPE TABLE OF struc.

APPEND wa TO itab. " 2nd entry

•Dynamic data structure

•Empty table occupies 256 bytes (header)

•Maximum line length is 64K

Page 97: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-12

© SAP AG

R

Internal Tables in Memory (4)

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

1st page:m entries (e.g.16)

2APPEND wa TO itab. " 1st entry

Table headerFixed size: 256 bytesDATA:itab TYPE TABLE OF struc.

APPEND wa TO itab. " 2nd entry

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

m+1

•Dynamic data structure

•Empty table occupies 256 bytes (header)

•Maximum line length 64K

Page 98: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-13

© SAP AG

R

Internal Tables in Memory (5)

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

1st page:m entries (e.g.16)

2APPEND wa TO itab. " 1st entry

Table headerFixed size: 256 bytesDATA:itab TYPE TABLE OF struc.

APPEND wa TO itab. " 2nd entry

APPEND wa TO itab. " m+1th entry 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 itab. " 3m+1th entry

3m+1 3rd page:M enrties (e.g.1024)

Page 99: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-14

© SAP AG

R

Internal Tables in Memory (6)

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

1st page:m entries (e.g.16)

2APPEND wa TO itab. " 1st entry

Table headerFixed size: 256 bytesDATA:itab TYPE TABLE OF struc.

APPEND wa TO itab. " 2nd entry

APPEND wa TO itab. " m+1th entry 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 itab. " 3m+1th entry

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.

Page 100: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-15

© SAP AG

R

Special Internal Table Operations

Internal table <itab>

Work area <wa>

CARRID CONNID

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

LOOP AT <itab>. ENDLOOP.READ TABLE <itab> ... .

APPEND ... <itab>.COLLECT ... <itab>.INSERT ... <itab>.MODIFY <itab> ... .DELETE <itab> ... . AA

LH00170400

Internal tables in ABAP differ from the array concepts of other programming languages in that you do not directly access actual lines within the table. Instead, you use a separate work area. From Release 4.5A, it will be possible to work directly with a table line using the statements LOOP AT <itab> ASSIGNING <fs> or READ TABLE <itab> ASSIGNING <fs>, where <fs> is a field symbol. For further information about this technique, refer to appendix A.

ABAP contains the following operations for internal tables: Statement Effect APPEND Appends the contents of the work area to the end of the internal table COLLECT Cumulates the contents of the work area in the internal table INSERT Inserts the work area in a particular line of the internal table MODIFY Overwrites a particular line of the internal table with the contents of the work area DELETE Deletes a particular line from the internal table LOOP AT Places the lines of the internal table one by one in a work area READ TABLE Places a single line of an internal table into a work area SORT Sorts the internal table REFRESH Deletes the internal table FREE Deletes the internal table and releases all of the resources used by it

Page 101: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-16

© SAP AG

R

Operations on all Data Objects

TYPES: BEGIN OF line_type,f1 TYPE c,f2 LIKE TABLE OF sflight-carrid,

END OF line_type.DATA: itab1 TYPE TABLE OF line_type,

itab2 TYPE TABLE OF line_type.

MOVE itab1 TO itab2.IF itab1 = itab2.WRITE / 'Tables are the same'.

ENDIF.CLEAR: itab1, itab2.

MOVE <dataobject1> TO <dataobject2>.IF <dataobject1> = <dataobject2>. ... . ENDIF.CLEAR <dataobject>.ASSIGN <dataobject> TO <fs>.EXPORT <dataobject> TO MEMORY | DATABASE ... .IMPORT <dataobject> 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 IF Compares the contents of one data object with those of another data object CLEAR Deletes the contents of a data object ASSIGN Assigns a data object to a field symbol EXPORT Writes a data object to a cluster database or ABAP memory IMPORT Reads a data object from a cluster database or ABAP memory Passing parameters to and from subroutines, function modules, and methods. Note that embedded (deep) structures in internal tables are included in MOVE, IF, CLEAR, and IMPORT/EXPORT operations. This also applies to the FREE and REFRESH statements, but not for the SORT statement (no deep SORT).

Page 102: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-17

© SAP AG

R

Index Access Using Read

Internal table stand_tab

Work area wa

f1 f2

TYPES: BEGIN OF line_type,f1, f2,

END OF line_type.DATA: stand_tab TYPE STANDARD TABLE OF line_type WITH KEY f1,

wa TYPE line_type.

READ TABLE stand_tab INDEX 2 INTO wa.

22

b 1

ab

11

The above example defines a standard table stand_tab. Each line consists of two fields f1 and f2, each of which has type C and length 1. The key consists of field f1. The work area wa is also required for internal table operations.

The READ statement reads the second line of the standard table stand_tab and places it in the work area wa.

Note: You cannot access a hashed table using an index.

Page 103: BC411 - Advanced ABAP Programming

(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 <itab>[FROM <n1>] [TO <n2>][INTO <wa>].ENDLOOP.

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

INSERT [<wa INTO] <itab>[INDEX <n>].

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

DELETE <itab>[INDEX <n>].

DELETE <itab>FROM <n1> TO <n2>.

INSERT LINES OF <itab1>[FROM <n1>] [TO <n2>]INTO <itab2> [INDEX <n3>].

APPEND [<wa> TO] <itab>. APPEND LINES OF <itab1>[FROM <n1>] [TO n2] TO <itab2>.

nn

Internal table operations can be classified as follows: By their access method as index operations or key operations. By the scope of their access as single record processing or mass processing. Single record

processing accesses one line in each operation, mass processing accesses n lines. By the operation type, as Read, Append, Insert, Change, or Delete. ABAP contains the following index operations: Note, again, that index operations are not allowed

on hashed tables. READ TABLE <itab> INDEX <n> INTO <wa>.

Reads the contents of the <n>th line of <itab> into the work area <wa>. APPEND <wa> TO <itab>.

Appends the contents of <wa> to the end of <itab>. INSERT <wa> INTO <itab> INDEX <n>.

Inserts the contents of <wa> into the table before line <n>. MODIFY <itab> INDEX <n> FROM <wa>.

Overwrites the <n>th line of <itab> with the contents of <wa>. DELETE <itab> INDEX <n>.

Deletes the <n>th line of <itab>.

Page 104: BC411 - Advanced ABAP Programming

(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 headerFixed 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 itab INDEX 2.

Linear index1453

212

1234

Page 105: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-20

© SAP AG

R

Linear Index (2)

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

1st page:m entries (e.g.16)

2

Table headerFixed 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 itab INDEX 2.DELETE itab INDEX 51.

Linear index145351

5052

2

m+1

3m+1

1234

Page 106: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-21

© SAP AG

R

Linear Index (3)

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

1st page:m entries (e.g.16)

2

Table headerFixed 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 itab INDEX 2.

Linear index1

45

3

DELETE itab INDEX 51.

51

5052

INSERT wa INTO itab

INDEX 3. 2

3m+1

m+1

1234

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.

Page 107: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-22

© SAP AG

R

Accessing a Single Generic Entry with READTYPES: BEGIN OF line_type,

f1, f2,END OF line_type.

DATA: stand_tab TYPE STANDARD TABLE OF line_type WITH KEY f1,wa type line_type.

wa-f1 = 'b'. wa-f2 = '5'.READ TABLE stand_tab FROM wa INTO wa. "implicity from waREAD TABLE stand_tab WITH TABLE KEY f1 = 'b' INTO wa. "explicitly

Internal table stan_tab

Work area wa

f1 f2

b 5b 1

Ab

11

If you use a key to access and internal table, you can either pass the key values implicitly in a work area, or explicitly using the additions

WITH KEY <f1> = <v1> ... AND <fn> = <vn> or WITH TABLE KEY <f1> = <v1> ... <fn> = <vn>. In the second case, <f1> … <fn> must be key fields of the table.

The READ variants "FROM <wa>" and "WITH TABLE KEY…", new in Release 4.0, are generic, that is, valid for all table types. The access is optimized according to the table type. The cost of the READ statement is linear for standard tables, logarithmic for sorted tables, and constant for hashed tables.

If TABLE occurs before KEY in the new READ variants, the system optimizes the access, but you must supply values for all of the key fields of the table.

To specify fields that differ from the table key, use the WITH KEY addition (note: no TABLE in the addition). This is not internally optimized.

If you use WITH KEY to access a hashed table, the cost is no longer constant, but linear. The exception to the general rule for WITH KEY is that the access is internally optimized for sorted

tables where the specified key is a left-justified extract of the beginning of the table key.

Page 108: BC411 - Advanced ABAP Programming

(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

INSERT [<wa> INTO]TABLE <itab>.

READ TABLE <itab>[INTO <wa>]WITH [TABLE] KEY

<k> = <v>.

LOOP AT <itab>[INTO <wa>]WHERE <condition>.

READ TABLE <itab>[INTO <itab_wa>]FROM <wa>.

MODIFY TABLE <itab>[FROM <wa>].

MODIFY <itab>[FROM <wa>]WHERE <condition>.

DELETE TABLE <itab>[FROM <wa>].

DELETE TABLE <itab>WITH TABLE KEY

<k> = <v>.

DELETE <itab>WHERE <condition>.

INSERT LINESOF <itab1>INTO TABLE <itab2>.

COLLECT [<wa> INTO]<itab>.

The parts of the syntax used to identify lines are italicized in the above table. These are either work areas from which the key values are read (implicit key access), or implicit key specifications using the WITH [TABLE] KEY addition.

If you try to insert a single duplicate entry into an internal table with unique key, the insertion fails, and SY-SUBRC is set to 4. This allows you to filter out duplicates from a set of entries very easily. If you try to insert duplicates during mass processing, a runtime error occurs.

This overview is further illustrated by examples on the following pages.

Page 109: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-24

© SAP AG

R

Operations on Standard Tables (Example)

REPORT sapbc411_standard_tab.TYPES: BEGIN OF line_type,

f1, f2,END OF line_type.

DATA: stand_tab TYPE STANDARD TABLE OF line_type WITH KEY f1,wa TYPE line_type.

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

TYPES: <itabtype> TYPE [STANDARD] TABLE of <linetype>[WITH [NON-UNIQUE] <keydef>][INITIAL SIZE <n>].

The above example processes the following operations using the data objects stand_tab and wa: Appends the contents of wa ('a1') to the end of stand_tab. The index of the insertion point is

placed in SY-TABIX and is 1 in the example. Inserts the contents of wa ('c1') in stand_tab at the position SY-TABIX + 1. This is position

2. The APPEND statement would, of course, have had the same effect. Appends the contents of wa ('b1') to the end of stand_tab. A generic INSERT in a standard

table has the same effect as the APPEND statement. Appends the contents of wa ('b2') to the end of stand_tab. This statement leads to a duplicate

key ('b'), since standard tables always have a non-unique key. Finds the first entry corresponding to the key of wa ('b') and changes it to b2. Deletes the first entry it finds corresponding to the key of wa ('a'). Reads the first entry from the internal table. Displays all of the entries. Sorts stand_tab according to field f2.

Page 110: BC411 - Advanced ABAP Programming

(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 <itab>.INSERT <wa> INTO <itab> INDEX <n>.MODIFY <itab> INDEX <n> FROM <wa>.DELETE TABLE <itab> FROM <wa>.

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

APPEND <itab>.INSERT <itab> INDEX <n>.MODIFY <itab> INDEX <n>.DELETE TABLE <itab>.

READ TABLE <itab> INDEX <n>.

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

Short syntaxClear syntax

AALH

00170400

AALH

00170400

You can define internal tables either with or without header lines. An internal table with header line is a composite of a work area (the header line) and the body of the table, both of which are addressed using the same name. The way in which the system interprets the name depends on the context. For example, the MOVE statement applies to the header line, but the SEARCH statement applies to the body of the table.

To avoid confusion, you are recommended to use internal tables without header lines. However, internal tables with header line do offer a shorter syntax in several statements (APPEND, INSERT, MODIFY, COLLECT, DELETE, READ, LOOP).

You can always address the body of an internal table itab using the syntax itab[], regardless of whether itab has a header line or not. Example: DATA: itab1 TYPE TABLE OF i WITH HEADER LINE. DATA: itab2 TYPE TABLE OF i WITH HEADER LINE. itab1 = itab2 "Copies only the header lines. itab1[] = itab2[] "Copies the contents of the entire table.

Page 111: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-26

© SAP AG

R

Declaring an Internal Table With Header LineDATA: <itab> TYPE <itabkind> OF <linetype>

WITH [UNIQUE | NON-UNIQUE] <keydef> [INITIAL SIZE <n>][WITH HEADER LINE].

REPORT sapbc411_standard_tab.TYPES: BEGIN OF line_type,

f1, f2,END OF line_type.

DATA: stand_tab TYPE STANDARD TABLE OF line_typeWITH KEY f1 WITH HEADER LINE,wa TYPE line_type.

stand_tab = 'a1'. APPEND wa TO stand_tab.tabix = sy-tabix + 1.stand_tab = 'c1'. INSERT wa INTO stand_tab INDEX tabix.stand_tab = 'b1'. INSERT wa INTO TABLE stand_tab.stand_tab = 'b2'. INSERT wa INTO TABLE stand_tab.stand_tab = 'b2'. MODIFY TABLE stand_tab FROM wa.stand_tab = 'a1'. DELETE TABLE stand_tab FROM wa.READ TABLE stand_tab INDEX 1 INTO wa. WRITE wa-f1, wa-f2.SORT stand_tab.

To define an internal table with a header line, use the addition WITH HEADER LINE. In the above examples, the crossed-out code indicates the syntax required for an internal table

without a header line (where you would need the work area wa).

Page 112: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-27

© SAP AG

R

Sorted Table (Example)DATA: <itabtype> TYPE SORTED TABLE of <linetype>

[WITH [UNIQUE | NON-UNIQUE] <keydef>][INITIAL SIZE <n>] [WITH HEADER LINE].

REPORT sapbc411_sorted_tab.TYPES: BEGIN OF line_type,

f1, f2,END OF line_type.

DATA: sorted_tab TYPE SORTED TABLE OF line_typeWITH UNIQUE KEY f1,wa TYPE line_type.

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

The above example processes the following operations using the data objects sorted_tab and wa: Inserts the contents of wa ('a1') into sorted_tab. Inserts the contents of wa ('b1') into sorted_tab. Inserts the contents of wa ('b2') into sorted_tab. This insertion would lead to a

duplicate key ('b'). Since sorted_tab is defined with a unique key, SY-SUBRC <> 0. Finds the first entry corresponding to the key of wa ('b') and changes it to 'b2'. Deletes the first entry corresponding to the key of wa ('b'). Reads the first line of the table and places it in wa. Displays all of the entries.

You can use INSERT … INDEX and APPEND for sorted tables, since the system only checks whether the sort sequence is violated or not. If your table entries are already correctly sorted before you insert them in the table, you can use these statements to bypass the normal binary search for the correct insertion point.

You cannot explicitly sort a sorted table using the SORT statement.

Page 113: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-28

© SAP AG

R

Partial Sequential Processing: Sorted TablesREPORT sapbc411_partseq_loop.TYPES: BEGIN OF line_type,

f1, f2, f3, f4,END OF line_type.

DATA: sorted_tab TYPE SORTED TABLE OF line_typeWITH NON-UNIQUE KEY f1 f2 f3,wa TYPE line_type.

*... Fill sorted_tab with non-unique values ...

LOOP AT sorted_tab INTO wa WHERE f1 = 'X' AND f2 = 'Y'. "optimized

....ENDLOOP.

LOOP AT sorted_tab INTO wa WHERE f1 = 'X' AND f3 = 'Z'. "not optimized

....ENDLOOP.

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

The same applies to the READ statement for sorted tables.

Page 114: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-29

© SAP AG

R

Hashed Tables (Example)TYPES: <itabtype> TYPE HASHED TABLE of <linetype>

[WITH UNIQUE <keydef>][INITIAL SIZE <n>].

REPORT sapbc411_hashed_tab.TYPES: BEGIN OF line_type,

f1, f2,END OF line_type.

DATA: hashed_tab TYPE HASHED TABLE OF line_typeWITH UNIQUE KEY f1,wa TYPE line_type.

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

WRITE wa-f1, wa-f2. ENDLOOP.SORT hashed_tab.

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

sorted). Note that you cannot use any index operations (APPEND, INSERT …. INDEX) on hashed tables.

Page 115: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-30

© SAP AG

R

Filling an Internal Table with Cumulative Values

CARRID PRICE (TYPE P)

4

567

8

9

LH 100000 waAA 2090938 1DL 933338 2LH 1766669 3 1866669

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

TYPES:BEGIN OF flightinfo_type,carrid LIKE sflight-carrid,price LIKE sflight-price,

END OF flightinfo_type.DATA: flightinfo_list TYPE HASHED TABLE OF

flightinfo_type WITH UNIQUE KEY carridconnid,wa TYPE flightinfo_type.

SELECT carrid price FROM sflight INTO wa.COLLECT wa INTO flightinfo_list.

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.

Page 116: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-31

© SAP AG

R

Summary of Internal Table Operations

INSERT

COLLECT

MODIFY

DELETE

READLOOP

INSERTAPPEND

MODIFY

DELETE

READLOOP

SORT

Standard table Sorted table Hashed table

Same as append Inserts in correct sort order Same as append

nn

No index operations onhashed tables

Possible sortorder 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, INSERT … INDEX, LOOP …FROM… TO).

You can use SORT for standard tables and hashed tables. It has no positive effect in a sorted table, and can lead to a syntax or runtime error if the attempted sort violates the key sequence.

You can use control level processing with all table types. Hashed and standard tables must be sorted beforehand.

Page 117: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 5-32

© SAP AG

R

DATA: BEGIN OF <itab> OCCURS <n>,<f1>, ..., <fn>,

END OF <itab>.

TYPES:BEGIN OF <line_type>,<f1>, ..., <fn>,

END OF <line_type>.DATA: <itab> TYPE <line_type>

OCCURS <n>WITH HEADER LINE.

TYPES:BEGIN OF <line_type>,<f1>, ..., <fn>,

END OF <line_type>.DATA: <itab> TYPE TABLE OF <line_type>

WITH HEADER LINE.

Release 2.2

Release 3.0

Release 4.0TYPES:BEGIN OF <line_type>,

<f1>, ..., <fn>,END OF <line_type>.

DATA: <itab> TYPE STANDARD TABLE OF <line_type>WITH DEFAULT KEY INITIAL SIZE <n>WITH HEADER LINE.

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 BEGIN of <itab> OCCURS <n> and END OF <itab>. OCCURS <n> had two meanings: Firstly, it specified the initial size of the table, secondly, it was the addition that identified the data object as an internal table. The implicit key of this kind of internal table consisted of all elementary non-numeric fields. The only attribute that determined the table type was the line type. Caution: This syntax still occurs very frequently in ABAP programs. Remember that it defines a standard table with header line and an implicitly-defined key.

Release 3.0 saw the introduction of the ABAP type concept. For internal tables, this meant that: The line type could be defined separately and referenced in the definition of the internal table

itself. You could define an internal table as a type.

From Release 3.0 onwards, it was also no longer necessary to work with a header line. From Release 4.0, the type of an internal table consists of a freely-definable key, the uniqueness

attribute, and the table type, as well as the line type.

Page 118: BC411 - Advanced ABAP Programming

(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 field sequence, uniqueness attribute, and table type.

Standard tables are particularly suitable for index acces. Sorted tables provide good performance if you use a key, and also allow you to use an index. Hashed tables provide excellent performance if you specify the entire key of an entry, but index access is not allowed.

A header line is a work area belonging to an internal table. You address it using the same name as the body of the table.

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

Page 119: BC411 - Advanced ABAP Programming

© SAP AG

R

Object-Oriented Programming with ABAP Objects: Contents

What are objects?Advantages of object-oriented programmingFrom function groups to objectsClasses and objectsWhat is ABAP Objects?ClassesAttributesReference variables and object instancesDefining and implementing methodsDefining and implementing interfacesTriggering and handling events

Page 120: BC411 - Advanced ABAP Programming

(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

Page 121: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-3

© SAP AG

R

What are Objects?

Function

Function Function

Function Function Function

Function

Function

DataData DataData

DataDataDataData

DataData

Objectattributes

Data MethodMethod

Method

Data MethodMethod

Method

Functions and Data Real World: ObjectsObjects

EncapsulationEncapsulation AbstractionAbstraction

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.

Page 122: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-4

© SAP AG

R

PublicaccessPrivate

access

Objectattributes

Interface

Events

Public attributes

Methods

AddressCustomer

Passengerlist

Flight

BOOK

Objects

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

Page 123: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-5

© SAP AG

R

Encapsulation

Program:...add 1 to

Object: FlightObject: Flight

Method:book

Attribute: passenger

Program:...Read table

No accessNo 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.

Page 124: BC411 - Advanced ABAP Programming

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

Page 125: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-7

© SAP AG

R

From Function Groups to Objects I

External session

DataData...

FunctionFunctionmodulemodule

Function group 11

DataData...

Function Function modulemodule

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.

Page 126: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-8

© SAP AG

R

From Function Groups to Objects II

External sessionExternal session

DatenDaten...

SchnittSchnitt--stellestelle

nth instance, class 1

DataData...

InterfaceInterface

1st instance, class 1DatenDaten...

FunktionsFunktions--bausteinbaustein

nth instance, class n

DataData...

Function Function modulemodule

1st instance, class n

Internal session of an ABAP program

ABAP program with data

In practice, this is very awkward. Consequently, the data is usually stored in the calling program, and the function modules are called to work with it. The problem with this is that all of the programs that use the function modules must use the same data structures as the function group itself. If you change the internal data structure of a function group, you affect a large number of users, and it is often difficult to predict the implications of the changes. The only way to avoid this is to rely heavily on instances and a technique that guarantees that the internal structures of runtime instances will remain hidden, allowing you to change them later without causing any problems.

Another problem is that all users have copies of the data. When you make changes, it is difficult to ensure consistency (who has a copy of what, and where is it stored?)

This requirement is met by object-orientation. ABAP Objects allows you to define data and functions in classes instead of function groups. Using classes, an ABAP program can work with any number of runtime instances based on the same template.

Instead of loading a single runtime instance of a function group into memory implicitly when a function module is called, the ABAP program can now generate the runtime instances of classes explicitly using the new ABAP statement CREATE OBJECT. The individual runtime instances represent unique objects. You address these using object references. Object references are a new ABAP data type (REF TO).

Page 127: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-9

© SAP AG

R

D081512

D081512

Classes and ObjectsPlane

Cargo plane Passenger plane

Private plane Business plane

D471113

D471113

NamePilotsCapacity

NamePilotsPassengers

BB Broadway230.000 kg

BB Broadway230.000 kg

NamePilotsCrewPassengers

AA Hollywood230,000 kg

AA Hollywood230,000 kg

BA Big Ben25200

BA Big Ben25200

LH Munich2380

LH Munich2380

Generalization

Instantiation

A class is an abstract description of a thing - anything - in the real world. You can model classes in a class hierarchy, in which the specialization of the classes increases as you progress from top to bottom.

An object (also known as an instance of a class) is a concrete example of the class. Objects that belong to a particular class all have the same attributes, and can all be accessed using the same methods. You can only have one copy of a class, but the class may have several objects (instances). Classes and objects have the same relationship as TYPES to DATA or the structure of a table to the table contents.

Objects cannot change their class. In this unit, classes are represented by rectangles with right-angled corners, and objects by rectangles with rounded corners.

Page 128: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-10

© SAP AG

R

What is ABAP Objects?

ABAP Objects is a fully compatible extension of the exisiting ABAP language.

You can use 'conventional' ABAP statements within ABAP Objects.

Equally, you can use ABAP Objects within conventional ABAP programs.

Object-orientation in ABAP is a strictly upwards-compatible extension of the existing ABAP language. It provides ABAP programmers with the advantages of object-orientation, such as encapsulation, interfaces, and inheritance, making complex applications easier to control and simplify.

You can use all conventional ABAP statements and modularization units in ABAP Objects, and, conversely, ABAP Objects can also be used in existing ABAP programs.

For further information about ABAP Objects, refer to the online documentation: Help -> R/3 library -> ABAP Workbench -> ABAP Programming -> ABAP Objects or the online documentation in the ABAP Editor for the term ABAP Objects.

Page 129: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-11

© SAP AG

R

Classes I

CLASS <class> DEFINITION.

PUBLIC SECTION.... Definition of public components

PROTECTED SECTION.... Definition of protected components

PRIVATE SECTION.... Definintion of private components

ENDCLASS.

CLASS <class> IMPLEMENTATION.... Method implementation

ENDCLASS.

CLASS <class> DEFINITION.

PUBLIC SECTION.... Definition of public components

PROTECTED SECTION.... Definition of protected components

PRIVATE SECTION.... Definintion of private components

ENDCLASS.

CLASS <class> IMPLEMENTATION.... Method implementation

ENDCLASS.

Objects of the same type are all defined by a single class definition. The declaration part of the class describes its inner structure (attributes), and the methods that you can use to work with the object. The source code of methods is defined in the implementation part of the class.

A few general statements about classes: - Classes contain components. - Each component of a class is assigned to a visibility section. - Classes implement methods.

A class is made up of components, all of which are declared in the declaration part of the class definition. Components define the attributes of the objects of the class. Each component is declared in one of three visibility sections; this defines the interface of the class. All components of a class are visible within the class itself. The three visibility sections are:

PUBLIC - all public components can be addressed by all users and in all methods. They form the external interface of the class. PROTECTED - Protected components of a class can be addressed in the methods of its subclass, and in the class itself (not yet implemented). PRIVATE - Private components of a class can only be addressed in the methods of that class.

Page 130: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-12

© SAP AG

R

Classes II

All users

Class c1

Privatecomponentsa3, m3, e3

Methodimplementation

Subclasses of c1

Protected componentsa2, m2, e2, …

Publiccomponents

a1,m1,e1

CLASS c1 DEFINITION.PUBLIC SECTION.

DATA: a1 …METHODS: m1 …EVENTS: e1 …

PROTECTED SECTION.DATA: a2 …METHODS: m2 …EVENTS: e2 …

PRIVATE SECTION. DATA: a3 …METHODS: m3 …EVENTS: e3 …

ENDCLASS.

CLASS c1 IMPLEMENTATION.

METHOD m1. … ENDMETHOD.

METHOD m2. … ENDMETHOD.

METHOD m3. … ENDMETHOD.

ENDCLASS.

The left-hand side of the illustration shows the declaration and implementation parts of a local class C1. The right-hand side shows the components of the class in their different visibility sections, and the implementation of the methods.

The public components form the point of contact between the class and its external users. Protected components are a point of contact between the class and its subclasses. Private components are fully encapsulated in the class and are not visible externally. The methods in the implementation part have unrestricted access to all of the components in the class.

Page 131: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-13

© SAP AG

R

Declaring Attributes

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

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

REPORT sapbc411d_flight.

CLASS c_customer DEFINITION.PUBLIC SECTION.*-- ID can only be changed within methods of this class

DATA: id TYPE i READ-ONLY,name(30) TYPE C VALUE 'DummyCustomer'.

ENDCLASS.

REPORT sapbc411d_flight.

CLASS c_customer DEFINITION.PUBLIC SECTION.*-- ID can only be changed within methods of this class

DATA: id TYPE i READ-ONLY,name(30) TYPE C VALUE 'DummyCustomer'.

ENDCLASS.

Attributes are internal data fields in classes that determine the state of an object. They may have any ABAP data type. They may be defined as instance attributes, in which case they contain data specific to a single instance, or as static attributes, which only exist once in each class, and are shared by all of the instances of the class.

You declare attributes in the declaration part of a class. Public attributes are visible outside the class, and thus form part of the interface between an object and its users. To encapsulate the state of an object, you use private attribtues. You can also prevent attributes from being changed by using the READ-ONLY addition. When you declare attributes, note that you can only use the LIKE addition to refer to other attributes of the class. You can only refer to data types in the ABAP Dictionary using the TYPE addition.

Page 132: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-14

© SAP AG

R

Static Attributes

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

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

REPORT sapbc411d_flight.

CLASS ccustomer DEFINITION.PUBLIC SECTION.*-- Instance_counter can be changed by methods of this *-- class and from outside the class

CLASS-DATA: instance_counter TYPE i.ENDCLASS.

REPORT sapbc411d_flight.

CLASS ccustomer DEFINITION.PUBLIC SECTION.*-- Instance_counter can be changed by methods of this *-- class and from outside the class

CLASS-DATA: instance_counter TYPE i.ENDCLASS.

You can only use this statement in the declaration part of a class declaration. The CLASS- prefix to the DATA statement means that the attribute a is declared as a static attribute. Otherwise, the CLASS-DATA statement has the same syntax as DATA statement for instance attributes.

Class attributes belong to the components of a class. Unlike instance attributes, which exist separately for each instance (object) of a class, and can only be used after you have created at least one instance, static attributes exist once only and are shared by all instances in the class. The system does not reset the contents of a class attributes while the class is in use, making them similar to local data objects in subroutines that you declare using the STATICS statements. Class attributes usually contain information that is common to all objects, for example, a counter of the number of objects currently in use.

The appearance of static attributes within a class is the same as that of instance attributes, and you can address them in the same way. If you access a static attribute from outside the class, you can use either an object reference or the class name. For example, if a is a static attribute of the class class, you can access it using class=> in programs in which the class class is declared. Once the class has been instantiated into an object obj, you can use the normal object reference obj->f to access the class attribute.

Page 133: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-15

© SAP AG

R

References: Reference Variables

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

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

Main memory

Reference semantics

oflight_1_1

oflight_2_2

Reference variable

Reference variable

Objects are instances of classes. Each object has a unique identity and its own attributes. All objects of a class exist within a single internal session (memory area of an ABAP program). You can create any number of instances of a class.

ABAP programs access objects using object references. Object references are pointers to objects, which, in ABAP, occur exclusively as the contents of reference variables (oflight_1 and oflight_1 above), which use reference semantics (see also the unit on field symbols). This means that you never address the values of attributes or methods directly, but always using their reference variables. ABAP contains a new data type TYPE REF TO <class> for this purpose. One of the advantages of the reference semantics is that the system does not have to copy object components and methods when you assign one object/reference variable to another. Instead, it merely copies the address of the new object.

Object references allow you to work with dynamic data structures such as detail lists, trees, graphs, and so on without having to 'hammer out' their data structure to fit it into a table.

Object attributes can themselves contain reference variables.

Page 134: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-16

© SAP AG

R

References: Creating Objects

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

CREATE OBJECT oflight_1.CREATE OBJECT oflight_2.

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

CREATE OBJECT oflight_1.CREATE OBJECT oflight_2.

oflight_1oflight_1

Main memory

oflight_2oflight_2

Reference semantics

Reference variableReference variable

Reference variableReference variable

C_FLIGHT<1>

C_FLIGHT<2>

Once you have created a reference variable with reference to the class c_flight, you can create an instance of the class (an object) using the statement CREATE OBJECT <cref>. The reference variable <cref> now contains a reference to the object.

You can create any number of objects belonging to the same class, each of which is fully independent of the others. Each object has its own identity and its own attributes. Each CREATE OBJECT statement creates a new object whose identity is defined by its unique object reference.

In the above diagram, instances are displayed as rounded rectangles. The above notation for instances corresponds to the contents of the reference variables as displayed in the ABAP Debugger.

Page 135: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-17

© SAP AG

R

References: Assigning References

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

CREATE OBJECT oflight_1.CREATE OBJECT oflight_2.oflight_2 = oflight_1

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

CREATE OBJECT oflight_1.CREATE OBJECT oflight_2.oflight_2 = oflight_1

oflight_1oflight_1

Main memory

oflight_2oflight_2

Reference semantics

Reference variableReference variable

Reference variableReference variable

C_FLIGHT<1>

C_FLIGHT<2>

You can assign refrences to other reference variables using the MOVE statement. This means that more than one reference variable can point to the same object. When you assign reference variables, the types of the source and target variables must either be compatible or convertible.

In the statement oflight_2 = oflight_1, both of the class references oflight_1 and oflight_2 must have the same type, that is, they must both refer to the same class, or the class of oflight_1 must be the predefined empty class OBJECT.

The class OBJECT has no components. Its significance to reference variables is the same as that of data type ANY to normal variables. Reference variables with the type OBJECT can serve as containers for passing references. However, you cannot use them to access objects.

Page 136: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-18

© SAP AG

R

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

CREATE OBJECT oflight_1.CREATE OBJECT oflight_2.oflight_2 = oflight_1

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

CREATE OBJECT oflight_1.CREATE OBJECT oflight_2.oflight_2 = oflight_1

References: Garbage Collection

Main memory

oflight_1oflight_1

oflight_2oflight_2

Reference semantics

Reference variableReference variable

Reference variableReference variable

C_FLIGHT<1>

C_FLIGHT<2>Garbage collection

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

Page 137: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-19

© SAP AG

R

Classes and Instances: Example

REPORT sapbc411d_flight.TYPES: tpassenger(20).

CLASS c_flight DEFINITION.PUBLIC SECTION.

METHODS: book ...PRIVATE SECTION.

DATA: passenger_list TYPE STANDARD TABLE OF tpassenger.ENDCLASS.

CLASS c_flight IMPLEMENTATION.METHOD book.

MOVE ...APPEND ...

ENDMETHOD. ENDCLASS.START-OF-SELECTION.DATA: oflight TYPE REF TO c_flight.CREATE OBJECT oflight.

REPORT sapbc411d_flight.TYPES: tpassenger(20).

CLASS c_flight DEFINITION.PUBLIC SECTION.

METHODS: book ...PRIVATE SECTION.

DATA: passenger_list TYPE STANDARD TABLE OF tpassenger.ENDCLASS.

CLASS c_flight IMPLEMENTATION.METHOD book.

MOVE ...APPEND ...

ENDMETHOD. ENDCLASS.START-OF-SELECTION.DATA: oflight TYPE REF TO c_flight.CREATE OBJECT oflight.

You define object references in the DATA or TYPES statement using the form <ref.variable> TYPE REF TO <class name>.

The CREATE OBJECT statement creates objects dynamically. The program requests main memory space from the system to enable it to store the attributes and methods of the new object. The reference to the object is stored in the reference variable.

Page 138: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-20

© SAP AG

R

Declaring Methods

METHODS <meth> IMPORTING .. VALUE(<i>)| <i> TYPE type [OPTIONAL]

.. EXPORTING .. VALUE(<e>)| <e> TYPE type [OPTIONAL] ..CHANGING .. VALUE(<c>)| <c> TYPE type [OPTIONAL]

.. RETURNING VALUE(<r>) EXCEPTIONS .. <exc> ..

METHODS <meth> IMPORTING .. VALUE(<i>)| <i> TYPE type [OPTIONAL]

.. EXPORTING .. VALUE(<e>)| <e> TYPE type [OPTIONAL] ..CHANGING .. VALUE(<c>)| <c> TYPE type [OPTIONAL]

.. RETURNING VALUE(<r>) EXCEPTIONS .. <exc> ..

REPORT sapbc411d_… .TYPES: tpassenger(20).TABLES: sflight.DATA: begin of wa, ...CLASS c_flight DEFINITION.

PUBLIC SECTION.METHODS: book IMPORTING passenger TYPE tpassenger

carrid LIKE sflight-carrid,connid LIKE sflight-connid,fldate LIKE sflight-fldate.

REPORT sapbc411d_… .TYPES: tpassenger(20).TABLES: sflight.DATA: begin of wa, ...CLASS c_flight DEFINITION.

PUBLIC SECTION.METHODS: book IMPORTING passenger TYPE tpassenger

carrid LIKE sflight-carrid,connid LIKE sflight-connid,fldate LIKE sflight-fldate.

You declare methods in the declaration part of a class or interface. The above example with its additions declares an instance method. For further information, refer to the keyword documentation in the ABAP Editor for the METHODS statement.

You must specify the type of all interface parameters using the TYPE or LIKE addition. When you declare a method, you also declare its parameters interface using the IMPORTING, EXPORTING, CHANGING and RETURNING additions. These define the input, output, input/output and return code parameters. You also define the attributes of the interface parameters, for example, whether it is passed by reference or value (VALUE), whether it has a fixed type (TYPE), and whether an input parameter is optional (OPTIONAL, DEFAULT). Unlike function modules, the default passing method for methods is by reference. To pass a parameter by value, you must explicitly use VALUE. The return value (RETURNING parameter) must always be passed as a value. This parameter is suitable for methods that return a single value. If you use a returning parameter, you cannot use exporting or changing parameters.

Like function modules, methods allow you to define exception parameters (EXCEPTIONS), allowing the user to react to errors that occur during the method.

Page 139: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-21

© SAP AG

R

Implementing Methods

METHOD <meth>.... Implementation ...ENDMETHOD.

METHOD <meth>.... Implementation ...ENDMETHOD.

REPORT sapbc411d_… .TYPES: tpassenger(20).TABLES: sflight.DATA: begin of wa, ...CLASS c_flight DEFINITION.

PUBLIC SECTION.METHODS: book IMPORTING passenger TYPE tpassenger

carrid LIKE sflight-carrid,connid LIKE sflight-connid,fldate LIKE sflight-fldate.

PRIVATE SECTION.DATA: passenger_list TYPE STANDARD TABLE OF wa.

ENDCLASS.CLASS c_flight IMPLEMENTATION.

METHOD book.MOVE carrid TO wa-carrid, ...APPEND wa TO passenger_list.

ENDMETHOD. ENDCLASS.

REPORT sapbc411d_… .TYPES: tpassenger(20).TABLES: sflight.DATA: begin of wa, ...CLASS c_flight DEFINITION.

PUBLIC SECTION.METHODS: book IMPORTING passenger TYPE tpassenger

carrid LIKE sflight-carrid,connid LIKE sflight-connid,fldate LIKE sflight-fldate.

PRIVATE SECTION.DATA: passenger_list TYPE STANDARD TABLE OF wa.

ENDCLASS.CLASS c_flight IMPLEMENTATION.

METHOD book.MOVE carrid TO wa-carrid, ...APPEND wa TO passenger_list.

ENDMETHOD. ENDCLASS.

You must implement all of the methods that you declare in a class in its implementation part. Each method implementation must be enclosed in the METHOD <meth> … ENDMETHOD statements in the same way that a function module definition is enclosed in the FUNCTION … ENDFUNCTION statements.

When you implement a method, you do not need to list its interface parameters again, since you have already specified them in the method declaration. The interface parameters of methods are treated like local variables within the method implementation. You can also declare other local data using the DATA statement.

Like function modules, methods allow you to use the RAISE <exception> and MESSAGE RAISING statements to trigger exceptions.

When you implement static methods, remember that they can only use the static attributes of the class. Instance methods can use both static attributes and instance attributes (see also the online documentation for the CLASS statement).

Page 140: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-22

© SAP AG

R

Calling MethodsCALL METHOD <method> EXPORTING <formal_e> = <actual_e>

IMPORTING <formal_i> = <actual_i> CHANGING <formal_c> = <actual_c> RECEIVING r = h EXCEPTIONS <exc_i> = rc_i.

CALL METHOD <method> EXPORTING <formal_e> = <actual_e> IMPORTING <formal_i> = <actual_i> CHANGING <formal_c> = <actual_c> RECEIVING r = h EXCEPTIONS <exc_i> = rc_i.

REPORT sapbc411d_flight.CLASS c_flight DEFINITION.

PUBLIC SECTION.METHODS: book IMPORTING ...

PRIVATE SECTION. ...ENDCLASS.

CLASS c_flight IMPLEMENTATION.METHOD book.

...ENDMETHOD.

ENDCLASS.

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

carrid = 'LH'connid = '0400'fldate = '19980202'.

REPORT sapbc411d_flight.CLASS c_flight DEFINITION.

PUBLIC SECTION.METHODS: book IMPORTING ...

PRIVATE SECTION. ...ENDCLASS.

CLASS c_flight IMPLEMENTATION.METHOD book.

...ENDMETHOD.

ENDCLASS.

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

carrid = 'LH'connid = '0400'fldate = '19980202'.

You call methods using the above statement. The exact way in which you address the method <method> depends on where in the program the call occurs. Within the implementation part of a class, you can call methods in the same class directly using the name <method>.

CALL METHOD <method> … If you are calling the method from outside the class, the visibility section of the method determines whether the call is possible. You can call visible instance methods from outside the class using CALL METHOD <ref>-><method> where <ref> is a reference variable whose value points to an instance of the class. You can call visible static methods from outside the class using CALL METHOD <class>=><method> where <class> is the name of the class.

When you call a method, you must specify all non-optional input parameters in the EXPORTING and CHANGING additions of the CALL METHOD statement. You can (but do not have to) receive the IMPORTING and RECEIVING parameters. It is also up to the caller whether to handle any exceptions triggered in the method using the EXCEPTIONS addition. However, you are recommended to do s.

You pass and receive values using the same syntax as with function modules, namely: <formal parameter> = <actual parameter> following the corresponding addition.

Page 141: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-23

© SAP AG

R

Constructor

Classes can define a constructor, which is automatically called at the CREATE OBJECT statement.

The name is always CONSTRUCTOR (reserved name).

The constructor can only have IMPORTING parameters.

CLASS c DEFINITION.PUBLIC SECTION.

METHODS CONSTRUCTOR [ IMPORTING VALUE(arg1) TYPE type … ].

ENDCLASS.

CLASS c DEFINITION.PUBLIC SECTION.

METHODS CONSTRUCTOR [ IMPORTING VALUE(arg1) TYPE type … ].

ENDCLASS.

PROGRAM … .DATA o1 TYPE REF TO …

CREATE OBJECT o1 EXPORTING arg1 = v1 arg1 = v2.

PROGRAM … .DATA o1 TYPE REF TO …

CREATE OBJECT o1 EXPORTING arg1 = v1 arg1 = v2.

Constructors are special methods that give objects and classes a particular initial state. The state of an object or class is determined by its instance attributes or static attributes. You can preassign values to attributes using the VALUE addition in the DATA statement. If, on the other hand, you want to define the initial state of an object dynamically, you need to use a constructor.

The CONSTRUCTOR method is called after an object has been fully created in the CREATE OBJECT <obj> statement (see also the online documentation for the CREATE statement).

Page 142: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-24

© SAP AG

R

BookingBooking__Mgr

Flight Hotel Rental Car

IBook

InterfacesInterfaces define the interaction between objects

Polymorphism is independent of classes and inheritance

Classes can implement more than one interface

Interface references provide uniform access

By their visibility, the components of a class define the external points of contact for a class. For example, the public components define a point of contact that can be addressed by any other user.

Interfaces are standalone components that you can implement in classes to extend the class-specific contact points. They provide a uniform way of addressing different classes. Interfaces are the basis for polymorphism, since their methods can behave differently in the different classes in which they are implemented. Interface references allow users to address different classes using the same structure.

The above example shows a booking manager application that you can use to book flights, hotel rooms, and rental cars. An interface (Ibook) allows you to extend the classes flight, hotel, and rental car, and implement the booking procedure in each of the different classes by addressing the same interface.

Page 143: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-25

© SAP AG

R

Interfaces: Model

All users

Class c1

Privatecomponentsa2, m2, e2

Methodimplementation

Subclasses of c1

Protected componentsa3, m3, e3, …

Public components

CLASS c1 DEFINITION.PUBLIC SECTION.

INTERFACES i1 …DATA a1 …

PROTECTED SECTION.

PRIVATE SECTION.

ENDCLASS.

CLASS c1 IMPLEMENTATION.

METHOD i1~m1. … ENDMETHOD.

ENDCLASS.

INTERFACE i1.DATA: a1. ...METHOD: m1. ...

ENDINTERFACE.

i1~a1.i1~m1.

a1,...

The left-hand side of the diagram shows the definition of a local interface i1 and the declaration and implementation parts of a local class c1 that implements interface i1 in its public section. The implementation part of the class definition contains the implementation of the interface method i1~m1.

The right-hand side shows the structure of the class with the components in their respective visibility sections, and the implementation of the methods. The interface components extend the public components of the class. All users can address both the class-specific public components and the interface components.

Page 144: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-26

© SAP AG

R

Defining Interfaces

INTERFACE i_reservation.METHODS: book IMPORTING passenger TYPE tpassenger,

cancel IMPORTING passenger TYPE tpassenger ENDINTERFACE.

INTERFACE i_reservation.METHODS: book IMPORTING passenger TYPE tpassenger,

cancel IMPORTING passenger TYPE tpassenger ENDINTERFACE.

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

ENDINTERFACE.

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

ENDINTERFACE.

Like classes, you can define interfaces either globally in the R/3 Repository, or locally in an ABAP program. The definition of a local interface <interface> is always enclosed in the statements INTERFACE <interface> … ENDINTERFACE. Interfaces are abstract descriptions of attributes sharead by different classes. They contain the same components as classes (attributes, method definitions, events, constants), but do not have an implementation part. Instead, interface methods are implemented by the class that implements the interface.

The components of interfaces do not have to be explicitly assigned to a visibility section, since the interface itself is assigned to a visibiltiy section of the class that implements it, and all of its components automatically assume the same visibility.

Interfaces allow you to implement abstract functions. In the above example, the methods 'book' and 'cancel' could appear in both the classes 'flight' and 'hotel'. However, the actual implementation is different in each class. While you need to know the departure city, arrival city, and flight time to book or cancel a flight, you need the duration of a guest's stay to book or cancel a hotel room.

Interfaces allow you to define common components of different classes in one place. Classes that implement interfaces must implement all of their methods.

The question now remains as to how interfaces are linked to objects. This is explained on the next page.

Page 145: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-27

© SAP AG

R

Implementing Interfaces

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

ENDINTERFACE.

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

ENDINTERFACE.

INTERFACE i_reservation.METHODS: book IMPORTING passenger TYPE tpassenger,

cancel IMPORTING passenger TYPE tpassenger ENDINTERFACE.

CLASS c_flight DEFINITION.PUBLIC SECTION.

INTERFACES: i_reservation....

ENDCLASS.CLASS c_flight IMPLEMENTATION.

METHOD i_reservation~book.… (Booking code specific to this class)

ENDMETHOD. ENDCLASS.

INTERFACE i_reservation.METHODS: book IMPORTING passenger TYPE tpassenger,

cancel IMPORTING passenger TYPE tpassenger ENDINTERFACE.

CLASS c_flight DEFINITION.PUBLIC SECTION.

INTERFACES: i_reservation....

ENDCLASS.CLASS c_flight IMPLEMENTATION.

METHOD i_reservation~book.… (Booking code specific to this class)

ENDMETHOD. ENDCLASS.

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

Page 146: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-28

© SAP AG

R

INTERFACE i_reservation.METHODS: book ...

cancel...ENDINTERFACE.... Klassendefinition und -implementation ...

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

ohotel TYPE REF TO c_hotel.

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

INTERFACE i_reservation.METHODS: book ...

cancel...ENDINTERFACE.... Klassendefinition und -implementation ...

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

ohotel TYPE REF TO c_hotel.

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

Generic Programming Using Interface References

You can access the functions described in interfaces using interface references. Instead of creating a reference variable with reference to a class, you can create them with reference to interfaces. This kind of reference variable can contain references to objects of classes that implement the corresponding interface.

Using an interface reference <iref>, a user can address all of the visible interface components <icomp> of the obejct to which the reference is pointing using the form <iref>-<icomp>. In other words, the user can access those components that have been added to the class by its implementing the interface.

In the example, the expression ires = oflight means that ires now points to the same object as the class reference in oflight. However, it can only access the methods of the object oflight that are declared in the interface. The interface thus provides a restricted view of the methods of the object oflight.

You can access the interface component book using CALL METHOD ires->book. Similarly, you can access an attribute defined in an interface using <iref_variable>-><attr>.

Note: You can book both a flight and a hotel room by calling the method 'book'. The actual method that is called depends on the target of the interface reference. You can thus program generically by 'redirecting' the reference variable.

Page 147: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-29

© SAP AG

R

Interfaces - ExampleINTERFACE i_reservation.

METHODS: book IMPORTING passenger TYPE tpassenger,cancel IMPORTING passenger TYPE tpassenger.

ENDINTERFACE.

INTERFACE i_reservation.METHODS: book IMPORTING passenger TYPE tpassenger,

cancel IMPORTING passenger TYPE tpassenger.ENDINTERFACE.

CLASS c_flight DEFINITION....INTERFACES: i_reservation.

ENDCLASS.CLASS class_flight IMPLEMENTATION.

...METHOD i_reservation~book.

...ENDMETHOD.METHOD i_reservation~cancel.

...ENDMETHOD.

ENDCLASS.

CLASS c_flight DEFINITION....INTERFACES: i_reservation.

ENDCLASS.CLASS class_flight IMPLEMENTATION.

...METHOD i_reservation~book.

...ENDMETHOD.METHOD i_reservation~cancel.

...ENDMETHOD.

ENDCLASS.

START-OF-SELECTION.DATA: ires TYPE REF TO i_reservation.DATA: oflight TYPE REF TO c_flight, ohotel TYPE REF TO c_hotel.CREATE OBJECT: oflight, ohotel.ires = oflight.CALL METHOD ires->book EXPORTING passenger = 'Miller'.ires = ohotel.CALL METHOD ires->book EXPORTING passenger = 'Miller'.

START-OF-SELECTION.DATA: ires TYPE REF TO i_reservation.DATA: oflight TYPE REF TO c_flight, ohotel TYPE REF TO c_hotel.CREATE OBJECT: oflight, ohotel.ires = oflight.CALL METHOD ires->book EXPORTING passenger = 'Miller'.ires = ohotel.CALL METHOD ires->book EXPORTING passenger = 'Miller'.

CLASS c_hotel DEFINITION....INTERFACES: i_reservation.

ENDCLASS.CLASS class_hotel IMPLEMENTATION.

...METHOD i_reservation~book.

...ENDMETHOD.METHOD i_reservation~cancel.

...ENDMETHOD.

ENDCLASS.

CLASS c_hotel DEFINITION....INTERFACES: i_reservation.

ENDCLASS.CLASS class_hotel IMPLEMENTATION.

...METHOD i_reservation~book.

...ENDMETHOD.METHOD i_reservation~cancel.

...ENDMETHOD.

ENDCLASS.

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

Page 148: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-30

© SAP AG

R

Business planeBusiness plane

EventsControllerController

PassengerPassenger

PilotPilot

LH Munich

IF altitude = 0.RAISE EVENT touch_Down.

ENDIF.

Mr SmithLanded=1Landed=1

Pilot MillerRelax!Relax!

Mrs JonesApplause!Applause!

Objects can announce that their state has changed by triggering events. Events usually contain export parameters, but no import parameters, since the object only wants to announce its change of state - it is not concerned about any further processing.

In the above example, the class business plane can trigger the event 'touch_down', which has been registered by other classes, and is then handled by them. For example, the air traffic controller checks off the plane as landed, the pilot can relax, and passenger Jones applauds.

Unlike 'normal' methods, where the caller controls the procedure and knows the method that has been called, an object that triggers an event does not know who will handle it.

Page 149: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-31

© SAP AG

R

EventsTrigger

CLASS c1 DEFINITION.PUBLIC SECTION.

EVENTS e1 EXPORTING VALUE (p1)TYPE i.

METHODS: m1.

PRIVATE SECTION. DATA: a1 TYPE i.

ENDCLASS.

CLASS C1 IMPLEMENTATION.METHOD m1.a1 = ...RAISE EVENT e1 EXPORTING p1 = a1 ENDMETHOD.

ENDCLASS.

CLASS c2 DEFINITION.PUBLIC SECTION.

METHODS: m2 FOR EVENT e1 OF c1IMPORTING p1.

PRIVATE SECTION. DATA: a2 TYPE i.

ENDCLASS.

CLASS C1 IMPLEMENTATION.METHOD m2.

a2 = p1....

ENDMETHOD.ENDCLASS.

Handler

In order to trigger an event, a class must declare it in its declaration part and trigger it in its methods. You declare events in a class or interface using the statement EVENTS <evt> EXPORTING … VALUE (<ei>) TYPE type [OPTIONAL]. To declare a static event, use the statement CLASS-EVENTS <evt> ...

The EXPORTING parameters are always passed by value. If a class contains an instance event, any methods of the class can trigger it. Static events can be triggered by any static method. To trigger an event in a method, use the statement RAISE EVENT <evt> EXPORTING … <ei> = <fi>...

In the EXPORTING addition, you must specify the actual parameter <fi> for any formal parameter <ei> that is not defined as optional.

Events are handled by special methods. To handle an event, a method must be declared as an event handler method for it, and must have registered for the event at runtime.

Page 150: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-32

© SAP AG

R

Defining Events

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

CLASS c_button DEFINITION.PUBLIC SECTION.

EVENTS: e_clicked EXPORTING VALUE(doubleclick) TYPE I.ENDCLASS.

CLASS c_button IMPLEMENTATION.METHOD mouse_click.

RAISE EVENT e_clicked EXPORTING doubleclick = 0.ENDMETHOD.

ENDCLASS.

CLASS c_button DEFINITION.PUBLIC SECTION.

EVENTS: e_clicked EXPORTING VALUE(doubleclick) TYPE I.ENDCLASS.

CLASS c_button IMPLEMENTATION.METHOD mouse_click.

RAISE EVENT e_clicked EXPORTING doubleclick = 0.ENDMETHOD.

ENDCLASS.

Events may be components of classes and interfaces. Like all other components, the event has the visibility of the visibility section in which it is defined.

You can only use the EVENTS statement in the declaration part of a class or definition. The EXPORTING addition defines the event interface. The exporting parameters define the view that the trigger has of the event.

Events can be triggered by the methods of the same class using the RAISE EVENT statement. When the event is triggered, the interface parameters are passed to the interface of the event handler method using the EXPORTING addition of the RAISE EVENT statement. The interface of an event handler methods contains a list of IMPORTING parameters with the same names as their corresponding EXPORTING parameters. This is generated automatically from the interface of the event.

Page 151: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-33

© SAP AG

R

Defining an Event Handler

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

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

CLASS c_window DEFINITION.PUBLIC SECTION.

METHODS: okclicked FOR EVENT e_clicked OF c_buttonIMPORTING doubleclick,

cancelclicked FOR EVENT e_clicked OF c_buttonIMPORTING doubleclick,

ENDCLASS.

CLASS c_window DEFINITION.PUBLIC SECTION.

METHODS: okclicked FOR EVENT e_clicked OF c_buttonIMPORTING doubleclick,

cancelclicked FOR EVENT e_clicked OF c_buttonIMPORTING doubleclick,

ENDCLASS.

Any class can contain event handler methods for events of other classes or interfaces. You declare event handler methods for instance methods using the statement METHODS <name> FOR EVENT <e> of <c|if> IMPORTING … <form_par> where <e> is an event declared in class <c> or interface <if>.

The interface of an event handler method may only contain formal parameters defined in the declaration of the event <e>. The attributes of the parameters are also adopted from the event. However, the event handler method does not have to accept all of the parameters passed in the RAISE EVENT statement.

If a class declares an event handler method, it and its instances are, in principle, capable of handling the event <e> that is triggered in an event.

Page 152: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-34

© SAP AG

R

Registering and Triggering Events

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

CREATE OBJECT: okbutton, cancelbutton, h1, h2.

SET HANDLER:h1->okclicked FOR okbutton, " Register for eventh2->cancelclicked FOR cancelbutton.

CALL METHOD okbutton->mouseclick. " Trigger eventCALL METHOD cancelbutton->mouseclick. " Trigger event

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

CREATE OBJECT: okbutton, cancelbutton, h1, h2.

SET HANDLER:h1->okclicked FOR okbutton, " Register for eventh2->cancelclicked FOR cancelbutton.

CALL METHOD okbutton->mouseclick. " Trigger eventCALL METHOD cancelbutton->mouseclick. " Trigger event

Registering a handler and triggering the event

In order for an event handler method to react to an event, you must define at runtime the trigger to which it should react. You do this using the statement SET HANDLER … <hi> … [FOR] … This statement links a list of handler methods with the trigger methods. The triggered event has four possible forms: An instance event defined in a class An instance event defined in an interface A static event defined in a class A static event defined in an interface. The syntax and effect of the SET HANDLER statement differs in each case.

If the event is an instance event, you must use the FOR addition to specify the triggering instance for which you want to register. You can either register a single instance using a reference variable <ref>: SET HANDLER … <hi> for <ref>. Or you can register the handler for all instances as follows: SET HANDLER … <hi>… FOR ALL INSTANCES.

This registration also applies to instances that do not yet exist at the time when you register the event. You cannot use the FOR addition for static events: SET HANDLER … <hi> … The registration automatically applies to the whole class, or to all classes implementing the interface with the static event. The registration also applies to classes that implement the interface but have not yet been loaded at the time of registration.

Page 153: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-35

© SAP AG

R

Events: Handler Table

okbuttonokbuttonReference variable

Handler: h1

okclicked

h1h1

Handler table

h1 okclicked

e1 (Event)Registered handlingobject method

Sender:okbutton

Triggering and handling methods means that certain methods trigger events, while others are registered as handlers and are executed when the event occurs.

Objects can trigger events while executing a method. The event can then be processed by 'interested' objects that have already registered themselves for the event. This registration is noted in an internal handler table. In the above example, objects h1 and h2 have registered for event h1, and will react to it using method m2.

Events allow very flexible programming. Unlike structured programming, where a program explicitly calls an external processing block, a program that triggers an event does not have to know who will react to it.

You declare events and event handler methods in classes. When an event occurs, the system looks for registered objects and calls the corresponding source code of the event handler methods.

Page 154: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-36

© SAP AG

R

Summary

In this unit, you have learned about object-oriented programming with ABAP Objects. Object orientation allows you to create programs that are easier to maintain and have a better structure.

ABAP Objects supports all of the significant characteristics of object orientation, such as encapsulation, interfaces, and events.

Page 155: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 6-37

© SAP AG

R

Preview: Inheritance

PlanePlane

Cargo planeCargo plane

Passenger planePassenger plane

PlanePlanename altitudefuelMaximum fuelActual numberOfPilotssetName ascend refuel

Passenger planePassenger planename altitudefuelMaximum fuelActual

numberOfPilots passengerMaximum passengerActualsetName ascend refuelloadPassenger loadBaggage

Cargo planeCargo planename altitudefuelMaximum fuelActual

numberOfPilots loadMaximum loadActualsetName ascend refuelloadCargo

Inheritance Classes are, as a rule, not fully independent of each other. On the contrary, you can add extra attributes and methods to most classes to make them more specialized. The new class is a subclass of the old class (its superclass). The program code of a superclass is reused in all of its subclasses, and any changes in the code are instantly and automatically effective in the subclasses as well. You can add new methods to subclasses and also overwrite methods that they have inherited from the superclass.

Inheritance and polymorphism are two characteristics of object-oriented programming that distinguish it from conventional programming.

ABAP Objects does not yet support inheritance. It is planned to allow classes to inherit from one superclass only (single inheritance).

Page 156: BC411 - Advanced ABAP Programming

© SAP AG

R

Contexts: Contents

ContextsHow to use contexts

Where to use contexts

Buffering contexts

Maintaining contexts

Page 157: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-2

© SAP AG

R

Unit Objectives

In this unit, you will learn

What a context is

Why you would want to use contexts

How contexts are buffered

How to use a context in an ABAP program

How to create and maintain contexts

Page 158: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-3

© SAP AG

R

What is a Context?

Little basic data Derived data:

Ex.:Table SGEOCITYEx.:Table SGEOCITY

City

Frankfurt

New York

Paris

Madrid

Country

D

USA

F

E

Value

5.00090E01

8.68000E01

6199.5164

Frankfurt Int.Airport

LH0400,AZ0788,UA3504, ...

Derived by

Reading directly

Reading directly

Calculation

Reading another

table

...

Field

Latitude

Longitude

Distance

Airport

Flights

... ... ...

Among all of the data in the R/3 System, there is a relatively small amount of basic data from which you can derive further information.

You often use particular relationships between data to retrieve other data, not only in one program, but in several, each time using the same relationship. This means that the same database operations or calculations are performed repeatedly, even though the required result had already been retrieved or calculated previously.

Contexts provide a way of avoiding this unnecessary system load. Contexts are ABAP Workbench objects, consisting of key fields (input fields), fields that are derived

from the values of the key fields, and the relationships between them. They do not store any actual data. Instead, they provide a static definition of functional dependencies.

In ABAP programs, you work with instances of contexts, which contain the actual data.

Page 159: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-4

© SAP AG

R

REPORT ....* Calculate geographical distance

SELECT longitude latitude FROM sgeocityWHERE city = 'FRANKFURT'AND country = 'DE'.

pi = acos( -1 ).x1 = latitude1 * pi / 180.y1 = longitude1 * pi / 180.x2 = latitude2 * pi / 180. y2 = longitude1 * pi / 180.yd = y2 - y1.distance = 20000 / pi * ACOS( SIN( x1 ) * SIN( x2 ) + COS( x1 )

* COS( x2 ) * COS( yd ) ).

REPORT ....* Calculate geographical distance

SELECT longitude latitude FROM sgeocityWHERE city = 'FRANKFURT'AND country = 'DE'.

pi = acos( -1 ).x1 = latitude1 * pi / 180.y1 = longitude1 * pi / 180.x2 = latitude2 * pi / 180. y2 = longitude1 * pi / 180.yd = y2 - y1.distance = 20000 / pi * ACOS( SIN( x1 ) * SIN( x2 ) + COS( x1 )

* COS( x2 ) * COS( yd ) ).

Setbuffer

Context buffer (main memory)Readbuffer

REPORT yyy.

...* Calculate geographical distance

REPORT zzz.

...* Calculate geographical distance

REPORT xyx.

* Calculate geographical distance

Field Value Field Valuecity Frankfurt city New Yorkcountry D country USAlatitude 5.0009E01 latitudelongitude 8.6800E01 longitudedistance (FRA-NY) 6199.5164

Using Contexts

By using contexts, you can: Reduce the complexity of your application programs because a lot of the processing logic is

transferred to the context program. Make better use of recurring logic. Increase performance by buffering the contexts.

Contexts are intended to store single complex functional relationships that occur frequently within an application. They are not intended for buffering large amounts of data that has to be processed sequentially.

The difference between the context buffer and the normal database and SAP table buffers is that it is only refreshed at set intervals, and does not constantly synchronize itself with changes.

As a rule, you will work with contexts delivered by SAP in your system, using the Context Builder to familiarize yourself with them and to test them.

Page 160: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-5

© SAP AG

R

Structure of a Context

Fields Modules Function moduleFunction module

ContextContext

Table / ViewTable / View

Contexts consist of fields and modules. The fields are divided into key fields and derived fields, and the modules describe the relationships between the fields. Modules are blocks, linked to one another by a defined interface.

A module can be a: - Database table or view - Function module - Context.

When you use a table as a module, all of its fields are adopted in the context. The key fields of the table serve as the input parameters of the module.

When you use a function module, all of its interface parameters are adopted in the context. The names of the context fields are generated automatically, but these default names can be overwritten. The import parameters of the function module serve as the input parameters of the context module, and the export parameters of the function module serve as its output parameters.

When you use a context as a module, all of its fields are adopted in the context. The system generates names for the context fields.

Page 161: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-6

© SAP AG

R

Testing Contexts

Context: DEMO_CITIES

Modules

Geogr. distance

Geogr. position of a cityGeogr. position of a city

Fields ValuesCITY1COUNTRY1CITY2COUNTRY2LONGITUDE1LATITUDE1LONGITUDE2LATITUDE2DISTANCE

MXACAPULCO

Context: Testumgebung

Value unknownValue calculableValue known

Module inactiveModule can be activatedModule is active

Icon Meaning in fields Meaning in modules

In the Context Builder, enter the name of the context that you want to test and choose Test. To test the context, enter values for its key fields (input fields). If you want to use a space as an input field, single-click the stoplight icon next to the relevant field to change its status. Next, select the output fields that you want to see, and choose Calculate values.

To display the relationship between fields and modules, double-click a field or a module. You can also display the current contents of the buffer.

Page 162: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-7

© SAP AG

R

Derivation Schema of a Context

Network graphic

COUNTRY1

CITY1

CITY2

COUNTRY2

LONG1/LAT1

LONG2/LAT2

Country 1

COUNTRY2

City 1CITY1

City 2

CITY2

Country 2

COUNTRY1Georgraphical pos.

SGEOCITY1

Geographical pos. SGEOCITY2

Geographical pos.

DISTANCE

The network graphic shows you the derivation schema of your context. On the left are the key fields (input fields) of the context, including their technical names. On the right are the modules that process the values from the fields. Further to the right, there may be further modules whose input values are supplied by the output values of preceding modules (in this case, DISTANCE).

You can display a module by double-clicking it. To display information about a field, double-click the connecting line that represents it.

Page 163: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-8

© SAP AG

R

Reset every hour on the hour

Constant data

Distance 2303.7715Longitude Latitude7.070000E01 7.40000E01

New York USA

Frankfurt D

Distance 2303.7715

Longitude Latitude5.00160E01 -8.566000E00

Buffering typesP PermanentT TemporaryN No buffering

Buffering Contexts

In the Modules table, you can set one of the following three buffering types for each module: Permanent (P)

The default setting. The system retains the data on the application server even after the end of the transaction. Whenever the context successfully derives a set of results, they (along with the intermediate results) are placed in the buffer. You can display the buffer in the Context Builder. It is automatically reset every hour on the hour, but may also be reset manually, either on the local application server, or on all application servers.

Temporary (T) If you choose this method, the results are only buffered for the duration of the transaction.

No buffering (N) None of the results are buffered. If you choose this method for all modules, using the context carries no performance advantage. However, you still have the advantage of its reusable logic.

The buffer (128 entries for each module) is refreshed according to the last recently used method. You can change the buffer size in the profile parameter rsdb/obj/buffersize, and the refresh interval using the parameter rdisp/bufreftime.

Page 164: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-9

© SAP AG

R

Context Buffer and Context Instances

Presentation

Database

...Roll area 1Context buffer

Contextinstance 1:demo_travel_instance

Roll area n

ApplicationContextinstance 2:demo_travel_instance

ABAPABAPDATA:demo_travel_instance

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

Page 165: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-10

© SAP AG

R

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

REPORT xxx.CONTEXTS: geogr_information.

DATA: geogr_information_inst1 TYPE context_geogr_information.

Creating a Context Instance

In an ABAP program, you work with runtime instances of contexts. While the context definition in the Context Builder is a description, the runtime instances contain actual data.

You declare a context to an ABAP program using the CONTEXTS statement. The context <context> must exist in the Context Builder. The CONTEXTS statement implicitly creates a special data type context_<context>. You can use this type in a DATA statement to create context instances.

The system also creates a data type CONTEXT_T_<context>-f for each field in the context. You can use this data type to create corresponding fields. For an example, see the DEMAND statement.

You can work with several instances of the same context within a program.

Page 166: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-11

© SAP AG

R

Supplying a Context Instance with Key Values I

Presentation

Application

Database

Roll area 1Context buffer

Context instance table

Entry Value Output fields

FrankfurtNew York

Cityfrom CitytoABAPABAP

SUPPLY

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

Important note: The SUPPLY statement involves no database activity.

Page 167: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-12

© SAP AG

R

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

REPORT ....CONTEXTS: geogr_information.

DATA: geogr_information_inst1 TYPE context_geogr_information.

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

Supplying a Context Instance with Key Values II

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

Whenever you send new key fields to a context instance, the old dependent values in the instance are automatically invalidated.

Page 168: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-13

© SAP AG

R

Retrieving Data from a Context Instance I

Presentation

Database3

Roll areaContext buffer

ApplicationEntry Value Output fields

FrankfurtNew York

CityfromCityto

Context instance table2FrankfurtNew York6193FrankfurtAthens1794

DISTANCE6193

1ABAPABAP

DEMAND

The following occurs in a DEMAND statement: 1.) The runtime environment checks whether the context instance already contains valid derived values. This will be the case if you have already executed a DEMAND statement for that instance and not changed the key values in a SUPPLY statement since then. If the instance contains valid values, they are transferred to the corresponding program fields. 2.) If the context instance does not contain valid derived values, the system generates them. To do this, it searches first of all in the context buffer for entries with the same key fields as the context instance. If this is the case, the system transfers the values from the buffer to the context instance and from there into the corresponding program fields. 3.) If the buffer does not contain the required values, the system derives the values itself according to the context definition. During this process, it searches in the context buffer for intermediate results, attempting to minimize the number of database accesses. When it has calculated the values, they are stored in the context buffer, passed to the instance, and assigned to the corresponding program fields. 4.) If the system cannot calculate all of the derived values, it stops processing, initializes the program fields, and, if you have stored a message for that module, displays it. You can control message handling in the program using the MESSAGES option.

Page 169: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-14

© SAP AG

R

DEMAND: <val1> = <f1> ... <valn> = <fn> FROM CONTEXT <instance>[MESSAGES INTO <itab>].

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

city_to TYPE context_typ-city,distance TYPE context_typ-distance.

DATA: geogr_information_inst TYPE context_geogr_information.

SUPPLY city = 'FRANKFURT'country = 'DE'city_1 = 'NEW YORK'country_1 = 'US'TO CONTEXT geogr_information_inst.

DEMAND city = city_fromcity_1 = city_todistance = distanceFROM CONTEXT geogr_information_inst.

Write: / city_from, city_to, distance.

Retrieving Data from a Context Instance II

The DEMAND statement fills the program fields <fn> with the derived values <valn> of context instance <instance> using the process described on the previous page.

Tip: Both the SUPPLY and DEMAND statements are very economical, so reusing them is no problem. In particular, you should always: - Use a SUPPLY statement as soon as you assign values to the relevant key fields. This reduces the danger of the DEMAND statement deriving obsolete data. You do not have to check yourself whether the key fields have changed, since the system does this automatically in each SUPPLY statement. - Use a DEMAND statement directly before using the derived fields. In this way, you can be sure that you are using the right fields. This is a performance advantage in itself.

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

Page 170: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-15

© SAP AG

R

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

SUPPLY city = 'XX'country = 'DE'city_1 = 'NEW YORK'country_1 = 'USA'TO CONTEXT geogr_information_inst.

DEMAND distance = distanceFROM CONTEXT geogr_information_inst.

WRITE: distance.

E No entries found for key XX DE

Message Handling in Contexts: System

Message displayed by contextby context

If a context cannot derive the required data when you execute a DEMAND statement, you can force it to send a user message.

The message handling depends on the modules in which the data retrieval failed. It is based on the following:

For table modules, the message attributes specified in the Context Builder. For function modules, exception handling in the function module using MESSAGE …

RAISING or RAISE. Contexts as modules can always be traced back to tables or function modules.

If you want the system to be responsible for message handling, use the basic form of the DEMAND statement without the MESSAGES addition.

For table modules, the system reacts as though there were a MESSAGE statement after the DEMAND statement, containing the attributes (ID, number) specified for the module in the Context Builder. For function modules, the MESSAGE … RAISING statement in the function module is

executed. If the function module only contains a RAISE statement, a runtime error occurs.

Page 171: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-16

© SAP AG

R

REPORT sapbc411d_context_geogr_info.

DATA: itab LIKE symsg OCCURS 0 WITH HEADER LINE.CONTEXTS c_geogr_information.DATA: geogr_information_inst TYPE context_c_geogr_information.DATA: distance TYPE context_t_geogr_information.

SUPPLY city = 'XX'country = 'DE'city1 = 'NEW YORK'country1 = 'USA'TO CONTEXT geogr_information_inst.

DEMAND distance = distanceFROM CONTEXT geogr_information_instMESSAGES INTO itab.

WRITE: / distance.LOOP AT itab.

WRITE: / itab-msgty, itab-msgid, itab-msgno,itab-msgv1, itab-msgv2.

ENDLOOP

Message Handling in Contexts: Program

Messages displayed by system

E BCTRAIN 007 XX DE

If you want to control message handling in your program, use the MESSAGES addition with the DEMAND statement. The system then clears the table specified in the MESSAGES addition (itab in the example) and fills it with any messages that occur while the context is being processed. These message are not displayed to the user, and the system does not react to their type (for example, by terminating the program in the case of an 'A' message). The messages in the internal table can then be processed later in the program.

This is, for example, important when you want to make input fields on a screen ready for further input following the error, since you must include these fields in your message handling (FIELD statement in screen flow logic, or AT SELECTION-SCREEN event for selection screens).

If there are messages in the message table following the DEMAND statement, SY-SUBRC is unequal to 0.

Page 172: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-17

© SAP AG

R

REPORT ....DATA: context_name LIKE rs33f-frmid.context_name = 'DOCU_TEST1'....CALL FUNCTION 'UPDATE_...' IN UPDATE TASK

EXPORTING ...IMPORTING ...

... CALL FUNCTION 'CONTEXT_BUFFER_DELETE' IN UPDATE TASK

EXPORTING context_id= context_name

EXCEPTIONSOTHERS = 0.

...COMMIT WORK.

Clearing the Context Buffer

You can clear a context buffer on the current application server using the function module CONTEXT_BUFFER_DELETE_LOCAL, and on all application servers using the function module CONTEXT_BUFFER_DELETE. You can use these function modules when you make database changes to ensure that the buffer contents are always up to date.

In the above example, the function module is called as the last step in the update task before the COMMIT WORK.

You can delete the buffer contents either on the current application server or on all application servers from within the Context Builder.

As a rule, contexts should only contain tables whose contents are still usable after one hour. You can deactivate the context buffer for testing Customizing settings.

Page 173: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-18

© SAP AG

R

Creating and Maintaining Contexts

Felder Modules

Module SGEOCITY1

SGEOCITY- CITYSGEOCITY- COUNTRYSGEOCITY- CITYSGEOCITY- COUNTRYSGEOCITY- LONGITUDESGEOCITY- LATITUDESGEOCITY- LONGITUDESGEOCITY- LATITUDESPFLI-DISTANCE

CDEMOCSGEOCITY

Geograp

CITY CITY1COUNTRY1

City1Ctry1Long1Lat1

Geograp

Fields

DISTANCESGEOCITY1

COUNTRYLONGITUDELATITUDE

LATITUDE1LONGITUDE1

Parameters I/O Field name Text

Name Type Table/mod. TextName Reference field/typeCITY1COUNTRY1CITY2COUNTRY2LONGITUDE1LATITUDE1LONGITUDE2LATITUDE2

Context: DEMO_CITIESContext: DEMO_CITIES

DISTANCE

GeograpSGEOCITYSGEOCITY2

You create and maintain contexts using the Context Builder (choose Development → Context Builder from the initial screen of the ABAP Workbench).

Once you have entered the name of your context, you must maintain its attributes, namely a title, the application, and the development class. When you choose Save, the context editor appears. This contains three tables in which you can enter the fields and modules in your context, and maintain the interfaces of the individual modules.

The three tables are all interdependent, and are partially filled by the system. When you enter a module (table, view, function module, or another context), the system automatically enters its input and output fields in the Fields table. It also proposes default names for the fields, but you can change these if you wish. Equally, you do not have to use all of the fields.

All fields must have a reference to the ABAP Dictionary. If you enter a table module, you can specify a message for the system to use in error handling. To display the interface of a module, double-click its name in the Modules list.

Page 174: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-19

© SAP AG

R

Summary I

In this unit you have learned that contexts are ABAP Workbench objects that store the relationships between data, but not the data itself.

You have learned that you can use contexts to:Remove processing logic from application programs, in order to

Reduce complexity

Make souce code reusable

Improve the performance of application programs thanks to context buffering

You have learned how to create and maintain contexts, and about the different buffering types (permanent, temporary, none).

Page 175: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 7-20

© SAP AG

R

You have learned the statements used to declare contexts in programs (CONTEXTS), to provide a context instance with values (SUPPLY), and to retrieve data from a context instance (DEMAND)

You know how messages are handled in contexts

You know how to create or maintain a context

Summary II

Page 176: BC411 - Advanced ABAP Programming

© SAP AG

R

ABAP Open SQL: Inhalt

Performance of business transactions

R/3 and DBMS architecture

SQL

Efficient database programming in ABAP ABAP Open SQL features

ABAP Open SQL programming rules

Page 177: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-2

© SAP AG

R

Unit Objectives

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

List the principal components of the R/3 System and DBMS architectures

Decide when it is appropriate to use Native SQL

Understand and apply the most important functions of ABAP Open SQL and the rules for efficient database programming

Page 178: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-3

© SAP AG

R

SQLSQL

Business transactionBusiness transactionperformance performance

R/3 and DBMS architectureR/3 and DBMS architecture

Efficient ABAP Efficient ABAP database programmingdatabase programming

ABAP Open SQL: Overview

Page 179: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-4

© SAP AG

R

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

database applicationGUI

Business Transaction Performance

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

The following pages illustrate the architecture of the R/3 System and that of a database management system (DBMS).

Page 180: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-5

© SAP AG

R

SQLSQL

R/3 and DBMS architectureR/3 and DBMS architecture

Efficient ABAP Efficient ABAP database programming database programming

ABAP Open SQL: Overview

Business transactionBusiness transactionperformanceperformance

Page 181: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-6

© SAP AG

R

R/3 ArchitectureCentral database(saves all data and application programs)

Application server

Communication with user

Data transfer between databaseand application server

Presentation server (workstation)

Database server

DBMSprocesses

DBcache

...Localdata

WP

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

Page 182: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-7

© SAP AG

R

General DBMS Architecture

R/3 work processR/3 work process

DB work process DB work process

Operating systemOperating system

Database filesDatabase files

R/3 work process

DB work process

Networkcommunication

DB CPUuse

Database cacheDatabaseservice

processes

DB memoryuse

Physical I/O

General DBMS architecture: A database work process provides a service that database clients can call (the client in our case is an R/3 work process). There are different database services for different purposes (starting communications, changing database tables, locking mechanism, archiving,…) There is a large shared memory area containing the DBMS cache and other resources, such as the statement cache and redo information. The database files are stored on a hard disk and managed by the file system.

Within this architecture, there are four factors that affect performance: Physical I/O, that is, reading from and writing to database files. This is the largest bottleneck in the

system. The mark of a well-configured system is the speed of its I/O access. Memory use in the database cache. CPU use on the database host. This is no problem with symmetrical multiprocessors (SMPs). Network communication. Although this is not critical for small amounts of data, it can lead to

problems when larger data volumes are involved. The next pages deal with these four points in further detail.

Page 183: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-8

© SAP AG

R

The Optimizer

Rule based

Cost based

Execution plan

All database systems have an optimizer, whose task it is to generate the execution plan for an SQL statement (for example, index or table scan). There are two kinds of optimizers:

A rule-based optimizer analyzes the structure of an SQL statement (mainly the SELECT and WHERE clauses without values), and the index of the table(s) involved. It then uses a set of analysis rules to decide the most appropriate procedure for executing the statement.

A cost-based optimizer also analyzes some of the values in the WHERE clause and the table statistics. The statistics contain low and high values for the fields, or, in some cases, a histogram of the distribution of the data in the table.

Cost-based optimizers use more information about the table, and usually produce faster access. One of the disadvantages is that the statistics must be periodically updated.

ORACLE databases up to and including Release 7.1 use a rule-based optimizer. From Release 7.2 (R/3 Release 4.0A), they use a cost-based optimizer.

All other database systems use a cost-based optimizer.

Page 184: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-9

© SAP AG

R

SQLSQL

R/3 and DBSM architectureR/3 and DBSM architecture

Efficient ABAP Efficient ABAP database programmingdatabase programming

ABAP Open SQL: Overview

Business transactionBusiness transactionperformanceperformance

Page 185: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-10

© SAP AG

R

ABAP SQL

Open SQLOpenOpen SQLSQL Native SQLNativeNative SQLSQL

DB interfaceDB interfaceEmbeddedEmbedded SQLSQL

SQLSQLSQL

DatabaseDatabase

ABAP contains a set of database statements known as ABAP Open SQL. These are all similar to Standard SQL statements. ABAP Open SQL has the following characteristics:

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

As well as Open SQL, you can use Native SQL statements. This is advisable in cases where Native SQL is more efficient than Open SQL. However, if you use it to change database contents, you may cause data inconsistencies, because Native SQL bypasses the SAP database interface. You must also expect to encounter portability problems. If you do use Native SQL statements, it is better to place them in includes.

SQL statements are passed to the database interface on the applciation server, where they are converted into the relevant form for the database. The converted statements are then passed to the database and are executed.

Page 186: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-11

© SAP AG

R

From SQL Statement to Result Set

SELECTclause

WHERE clause

FROM clause

Search area

Data to be transferred

Relevant data- the search result -

One or more tables

Data to be searched - onlyrestricted when the

search uses an index

SELECT field1 field2 field3 field4FROM ( table INNER JOIN table ON

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

SQL is set-oriented. An SQL statement specifies a set of data required by an application. The SELECT clause specifies the fields that you want to read (projection). Only those fields from the table entries selected are transferred over the network to the application process. The WHERE clause specifies a set of table entries that meet a particular condition. It specifies the result set. The search area is made up of the data entries that have to be searched to satisfy the query. This area is not explicitly specified in the query, but is determined by the optimizer, based on the table indexes.

If the search result is small, the search result and search area will, ideally, be identical. For large search results (more than 20% of the table), using an index is only an extra burden.

Page 187: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-12

© SAP AG

R

SQLSQL

R/3 and DBMS architectureR/3 and DBMS architecture

Efficient ABAP Efficient ABAP database programmingdatabase programming

Efficient ABAP Database Programming

Business transactionBusiness transactionperformanceperformance

Page 188: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-13

© SAP AG

R

Five Rules of Open SQL Programming

Five rulesDBMS-independent where possible

Page 189: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-14

© SAP AG

R

Basis for the Five Rules

ORACLE

INFORMIX

ADABAS

DB2/400 (AS/400)

Microsoft SQL Server (MSS)

Not considered:

DB2/6000

DB2/MVS

ORACLE Parallel Server (OPS)

The rules explained on the following pages are based on the following database management systems:

ORACLE INFORMIX ADABAS DB2/400 (uses EBCDIC code page) Microsoft SQL Server

Page 190: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-15

© SAP AG

R

Rule 1

Keep the result set small

The result set must be stored in the memory of the DBMS (not necessarily in a data packet) and should therefore be as small as possible.

The projection of the result set must be transferred over the network to the application server. Keeping the result set small thus reduces the load on the network.

Page 191: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-16

© SAP AG

R

Exercise: Read all Flights for a Year

Turn to the Exercises appendix for a description of the task

Page 192: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-17

© SAP AG

R

1. Keep the Result Set SmallUse a WHERE condition wherever possible

REPORT sapbc411s_flights_of_one_yearPARAMETERS: param1(4). DATA: BEGIN OF search_string,

param(4), rest value '%',

END OF search_string.

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

connid, ... ENDSELECT.

REPORT sapbc411s_flights_of_one_yearPARAMETERS: param1(4). DATA: BEGIN OF search_string,

param(4), rest value '%',

END OF search_string.

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

connid, ... ENDSELECT.

search_string-param = param1.SELECT * FROM sflight INTO wa_sflight WHERE fldate LIKE search_string.

WRITE: / wa_sflight-carrid, wa_sflight-connid, ...ENDSELECT.

search_string-param = param1.SELECT * FROM sflight INTO wa_sflight WHERE fldate LIKE search_string.

WRITE: / wa_sflight-carrid, wa_sflight-connid, ...ENDSELECT.

Instead, use

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

Do not use the first version listed above. The system has to read the entire contents of the table, place them in the DBMS cache, and transfer them over the network to the database interface. After this, the program throws most of the data away.

Use the second version. Here, the DBMS only reads the data that is really required. Rule: Specify all known conditions in the WHERE clause. The DBMS cannot optimize a statement

without one. Exceptions: Retrieving data for all company codes...

Making a client copy... Programming a utility function...

SELECT statements without a WHERE clause usually indicate a design error in your program, especially when the SELECT applies to an SAP table that expands rapidly (such as BKPF, BSEG, COBK, COEP, LIPK, MKPF, VBAK, VBAP).

Programs that address this kind of table perform well when your system first goes live, but the runtime increases constantly with time, since the tables grow daily, and often considerably.

Hint: The runtime numbers in the examples above and in further examples depend on the database system and the total number of records in the table.

Page 193: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-18

© SAP AG

R

Benefits of Rule 1

R/3 work processR/3 work process

DB work process DB work process

Operating systemOperating system

Database filesDatabase files

R/3 work process

DB work process

Networkcommunication

DB CPUuse

Database cacheDatabaseservice

processes

DB memoryuse

Physical I/O

The benefits of observing rule 1 are that: There are no more physical I/Os on the database than are really necessary. No unneeded data is stored in the database cache, reducing the probability of existing data being

deleted from the cache. The CPU use of the database host is minimized. The network communication between the database and the R/3 work process is restricted to data that

is actually needed by the application.

Page 194: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-19

© SAP AG

R

Rule 2

Minimze the amount of data transferred between the database and the application

server

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

Page 195: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-20

© SAP AG

R

Exercise: Reading the First 10 Flights

Turn to the Exercises appendix for a description of the task

Page 196: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-21

© SAP AG

R

2. Minimize Data Transfer I

REPORT sapbc411d_read_10_flights.

SELECT carrid connid FROM sbook WHERE carrid = 'LH' INTO (wa-carrid, wa-connid).

IF sy-dbcnt > 10.EXIT.

ENDIF.WRITE: / wa-carrid, wa-connid.

ENDSELECT.

REPORT sapbc411d_read_10_flights.

SELECT carrid connid FROM sbook WHERE carrid = 'LH' INTO (wa-carrid, wa-connid).

IF sy-dbcnt > 10.EXIT.

ENDIF.WRITE: / wa-carrid, wa-connid.

ENDSELECT.

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

ENDSELECT.

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

ENDSELECT.

Performance difference: SELECT column... EXIT. ENDSELECT. 300,000 msSELECT column ... UP TO 10 ROWS. 34,000 ms

Use data selectively

Instead, use

In the first version, the processing is ended by the program after the tenth entry. However, the database has already read the first 32K of the table SBOOK (175 entries) and transferred the entries to the database interface.

In the second version, the UP TO 10 ROWS addition ensures that only the first ten entries are read and transferred from the database to the database interface.

Page 197: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-22

© SAP AG

R

2. Minimize Data Transfer

REPORT sapbc411d_select_fieldlist.

TABLES: SBOOK.SELECT * FROM sbook

WHERE carrid ne 'BA'. WRITE: / wa-carrid, wa-connidENDSELECT.

REPORT sapbc411d_select_fieldlist.

TABLES: SBOOK.SELECT * FROM sbook

WHERE carrid ne 'BA'. WRITE: / wa-carrid, wa-connidENDSELECT.

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

WRITE: / wa-customid, wa-class, ...ENDSELECT.

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

WRITE: / wa-customid, wa-class, ...ENDSELECT.

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

Field list or SELECT * ?

Instead, use

Page 198: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-23

© SAP AG

R

Client/Server Architecture and ABAP Runtime I

SELECT * FROM SBOOK

ApplAppl..serverserver

ApplAppl..serverserver

DatabaseDatabaseserverserver

REPORT XYZ

Data transfer from DB server to appl. server

10000 SBOOK records of 97 bytes each require 30transfers of 32K packetsfrom the database serverto the application server

Report result

Each entry in the table SBOOK is 97 bytes long. If you want to read 10,000 entries from the database, you need to transfer 970,000 bytes from the database to the application server.

The database server and application servers communicate using packets of up to 32,000 bytes (depending on the network and communication hardware).

This means that you would need around 30 transfers (970,000 / 32,000) for the 10,000 SBOOK entries.

Page 199: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-24

© SAP AG

R

Client/Server Architecture and ABAP Runtime II

SELECT COL1 FROM SBOOK

Appl.Appl.serverserver

Appl.Appl.serverserver

DatabaseDatabaseserverserver

REPORT XYZ

Data transfer from DBserver to application server

10000 SBOOK entries of97 bytes each requires 30

transfers of 32K packetsfrom the database serverto the application server

Report result

By only reading the database fields that you actually need, you reduce the amount of data tranferred and the corresponding network load.

If you only read the fields booking number (CUSTOMID) and flight class (CLASS), you only need to transport 90,000 bytes (9 * 10,000), which only requires three packets. You thus save 27 packets of 32,000 bytes each (384,000 bytes) that no longer have to be transported.

Naturally, the real figures differ from those quoted here. The SQL Trace for this operation shows 22 and 4 transfers respectively. The difference is caused by the adminsitration information that also has to be transported.

Note: The disadvantages of the SELECT list are that you cannot use it with generic functions, and you have to adjust it if you change the definition of the table in the ABAP Dictionary.

Page 200: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-25

© SAP AG

R

2. Minimize Data Transfer II

Referencing table fields

Instead, useInstead, use

REPORT sapbc411d_update_set.DATA: wa_sflight like sflight.

SELECT * INTO wa_sflight FROM sflight WHERE carrid ='LH'.

wa_sflight-seatsocc = wa_sflight-seatsocc + 1. UPDATE sflight from wa_sflight.

ENDSELECT.

REPORT sapbc411d_update_set.DATA: wa_sflight like sflight.

SELECT * INTO wa_sflight FROM sflight WHERE carrid ='LH'.

wa_sflight-seatsocc = wa_sflight-seatsocc + 1. UPDATE sflight from wa_sflight.

ENDSELECT.

REPORT sapbc411d_update_set.

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

REPORT sapbc411d_update_set.

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

Performance difference: SELECT * ... ENDSELECT. 500,000 ms (100 entries)UPDATE ... SET ... 56,700 ms

Both of the above examples update a field whose value has increased. In the first version, all data records that satisfy the WHERE condition are read from the database, transferred to the database, and then transferred back again.

In the second version, only the statement is sent to the database (no data is transferred). You should use this variant wherever possible. However, it only supports the following simple operations: field = value field = field + value field = field - value where value is an ABAP field or a field from the same row of the database table.

You can only use the last two variants with numeric fields.

Page 201: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-26

© SAP AG

R

Exercise: Summation

Turn to the Exercises appendix for a description of the task

Page 202: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-27

© SAP AG

R

COUNT, SUM, MAX, MIN, AVG

Use aggregate functions

REPORT sapbc411d_cumulate_loccuram....

SUM = 0.SELECT loccuram FROM sbook into wa_sbook

WHERE fldate like '1998%'.SUM = SUM + wa_sbook-loccuram.

ENDSELECT.WRITE: / sum.

REPORT sapbc411d_cumulate_loccuram....

SUM = 0.SELECT loccuram FROM sbook into wa_sbook

WHERE fldate like '1998%'.SUM = SUM + wa_sbook-loccuram.

ENDSELECT.WRITE: / sum.

Instead, useInstead, use

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

WRITE: / sum.

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

WRITE: / sum.

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

2. Minimize Data Transfer 4

You can use the following aggregate functions in a SELECT statement: COUNT, SUM, MAX, MIN, and AVG. These functions allow you to summarize one or more columns of a database table in your result set.

In the first version above, all of the flight entries are read from the database, and the sum is calculated on the application server.

In the second version, the sum is calculated in the database, and only the result (a single value) is transported to the application server.

Page 203: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-28

© SAP AG

R

2. Minimize Data Transfer 5

Database may approximate differently from the ABAP runtime system

Databases use null values, ABAP does notAVG (1, 3, 0, 0) = 1

AVG (1, 3, null, null) = 2

Use the correct data type for the target fieldUse type 'F' (floating point) for the AVG function

For the SUM function, use a data type that can store numbers large enough to avoid an arithmetic overflow

Aggregate functions III - Differences

Unlike the ABAP runtime system, database do not use NULL values. A NULL value in the database means that a fields has not contents. ABAP does not include NULL values in SY-DBCNT, and conesequently, they are not included in AVG calculations.

Always use a type F field for the result of an AVG calculation, since the result invariably contains decimals.

Page 204: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-29

© SAP AG

R

Benefits of Rule 2

R/3 work processR/3 work process

DB work process DB work process

Operating systemOperating system

Database filesDatabase files

R/3 work process

DB work process

Networkcommunication

DB CPUuse

Database cacheDatabaseserviceprocesses

DB memoryuse

Physical I/O

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

application server.

Page 205: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-30

© SAP AG

R

Rule 3

Minimize the number of transfers between database

and application

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

Page 206: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-31

© SAP AG

R

3. Minimize the Number of Transfers 1

Use array operations - INSERT

REPORT ... LOOP AT itab.

INSERT INTO dbtab VALUES itab. ENDLOOP.

REPORT ... LOOP AT itab.

INSERT INTO dbtab VALUES itab. ENDLOOP.

REPORT ... INSERT dbtab FROM TABLE itab

ACCEPTING DUPLICATE KEYS.IF sy-subrc = 4.

... Error handling ...ENDIF.

REPORT ... INSERT dbtab FROM TABLE itab

ACCEPTING DUPLICATE KEYS.IF sy-subrc = 4.

... Error handling ...ENDIF.

Instead, useInstead, use

To insert several entries into a database table, use the variant INSERT … FROM TABLE. In the first version shown above, the application passes single entries to the database to be added to the table.

In the second version, the entire internal table itab is passed to the database and processed in a single operation.

If you suspect that some of the entries in itab already exist in the database (duplicate keys), you can use the ACCEPTING DUPLICATE KEYS addition. This ensures that the INSERT statement does not terminate when a duplicate key occurs. Instead, it sets SY-SUBRC to a value unequal to zero. In the simplest case, you would not react to the error. If, on the other hand, you want to ensure that all of the entries are inserted in the database table, use the statement UPDATE dbtab FROM TABLE itab.

Page 207: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-32

© SAP AG

R

Exercise: Reading from More than One Table

Turn to the Exercises appendix for a description of the task

Page 208: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-33

© SAP AG

R

3. Minimize the Number of Transfers 2

Joins implemented as views in the ABAP Dictionary

Joins in ABAP Open SQL

SELECT * FROM t1 WHERE ...SELECT * FROM t2 WHERE ...SELECT * FROM t3 WHERE ...SELECT * FROM t4 WHERE ...SELECT * FROM t5 WHERE ......ENDSELECT.

ENDSELECT.ENDSELECT.SELECT * FROM t6 WHERE ...SELECT * FROM t7 WHERE ...SELECT * FROM t8 WHERE ......ENDSELECT.

ENDSELECT.ENDSELECT.

ENDSELECT.ENDSELECT.

Use joins

If you use nested SELECT statements, you must expect an adverse effect on performance, especially if the outer table contains a large number of entries. The inner SELECT statement is processed in each loop pass of the outer SELECT statement. Using other techniques also means that less data has to be transferred from the database to the application server.

Insetad of nested SELECT statements, use one of the techniques listed above to read from more than one database table.

Database views and joins in ABAP Open SQL are covered in this unit. For more information about FOR ALL ENTRIES and cursor management, refer to the appendix.

Page 209: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-34

© SAP AG

R

3. Minimize the Number of Transfers 3

ABAP Dictionary viewREPORT sapbc411d_select_view. SELECT * FROM sflight.

WRITE: / sflight-carrid,... SELECT * FROM sbook WHERE carrid = sflight-carrid

AND connid = sflight-connidAND fldate = sflight-fldate.

IF SY_SUBRC NE 0.WRITE: sbook-bookid,...

ENDIF.ENDSELECT.

ENDSELECT.

REPORT sapbc411d_select_view. SELECT * FROM sflight.

WRITE: / sflight-carrid,... SELECT * FROM sbook WHERE carrid = sflight-carrid

AND connid = sflight-connidAND fldate = sflight-fldate.

IF SY_SUBRC NE 0.WRITE: sbook-bookid,...

ENDIF.ENDSELECT.

ENDSELECT.

SELECT * FROM sflightsbookview. *View in ABAP Dictionary

WRITE: / sflightsbookview-price,sflightsbookview-paymentsum, ...

ENDSELECT.

SELECT * FROM sflightsbookview. *View in ABAP Dictionary

WRITE: / sflightsbookview-price,sflightsbookview-paymentsum, ...

ENDSELECT.

Instead, use

To use the technique illustrated in the second example, you must first create a view in the ABAP Dictionary.

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

Page 210: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-35

© SAP AG

R

REPORT sapbc411d_select_view.SELECT f~carrid f~connid ... INTO (sflight-carrid, ...)

FROM sflight AS f INNER JOIN sbook AS bON f~carrid = b~carridAND f~connid = b~connidAND f~fldate = b~fldate.WRITE: / sflight-price, sflight-paymentsum, ...

ENDSELECT.

REPORT sapbc411d_select_view.SELECT f~carrid f~connid ... INTO (sflight-carrid, ...)

FROM sflight AS f INNER JOIN sbook AS bON f~carrid = b~carridAND f~connid = b~connidAND f~fldate = b~fldate.WRITE: / sflight-price, sflight-paymentsum, ...

ENDSELECT.

Inner join in the FROM clauseSELECT <fieldlist> INTO <target>

FROM <dbtab1> [AS <alias1>]INNER JOIN <dbtab2> [AS <alias2>]ON <alias1>~<dbtab1-field1> = <alias2>~<dbtab2-field1> AND <alias1>~<dbtab1-field2> = <alias2>~<dbtab2-field2> AND ...WHERE ......

ENDSELECT.

3. Minimize the Number of Transfers 4

You can also read from more than one table using an inner join in the FROM clause of your SELECT statement.

The above example repeats the example from the last page, and reads bookings from table SBOOK for flights in table SFLIGHT.

If the field list contains field names that occur in both tables of the inner join, you must differentiate them by preceding them with an alias name followed by a tilde. You can use the table name as the alias name. You specify the alias name in the FROM clause using the AS <aliasname> construction.

As well as being written simply, joins have the advantage that only one statement is executed in the database. However, they have the disadvantage that redudant data from the outer table appears in the result set if there is a 1:n relationship between the outer and inner tables. This can considerably increase the amount of data transferred from the database. For this reason, you should use a field list with a join to identify only those fields that you really need.

The runtime of a join statement is highly dependent on the database optimzer, especially when the join involves more than two tables. However, it is usually in any case quicker than using nested SELECT statements.

Page 211: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-36

© SAP AG

R

Inner join

AALHLHQF...

SFLIGHT:CARRID CONNID ... DISTANCECARRID CONNID ... DISTANCE

SBOOK:CARRID CONNID ... BOOKIDCARRID CONNID ... BOOKID

Join condition

AA 0017 2,572 AA 0017 1AA 0017 2,572 AA 0017 2AA 0017 2,572 AA ... ... ...

Join result table in the databaseJoin result table in the databaseCARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID

QF 0598 1,689 QF 0598 10

0017040004020598...

2,5726,658 3,1621,689...

AAAAAAQF...

00170017...0598...

12...10...

3. Minimize the Number of Transfers 5

Note: The result set containsno entries for airlineLH.

In an inner join, the system creates a temorary table containing all of the combinations of lines from table SFLIGHT and SBOOK whose values meet the logical condition (join condition) specified in the ON <condition> clause. The system then applies the WHERE condition to this set, the result of which is the actual result set. To make the above table easier to understand, it is assumed that the two tables are linked by the CARRID field.

The result of the inner join is the same, regardless of whether the condition occurs in the ON or in the WHERE clause. However, you cannot have an empty ON clause.

You cannot use an INNER JOIN for pool or cluster tables. Inner joins always bypass the table buffer and read directly from the database. For this reason, it is better to use a view from the ABAP Dictionary when accessing tables that are mostly only read.

Page 212: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-37

© SAP AG

R

3. Minimize the Number of Transfers 6

Left outer join in the FROM clause

REPORT sapbc411d_select_view....SELECT f~carrid f~connid ... INTO (sflight-carrid, ...)

FROM sflight AS f LEFT OUTER JOIN sbook AS bON f~carrid = b~carridAND f~connid = b~connidAND f~fldate = b~fldate WHERE f~fldate = '19981119'.WRITE: / sflight-price, sflight-paymentsum, ...

ENDSELECT.

REPORT sapbc411d_select_view....SELECT f~carrid f~connid ... INTO (sflight-carrid, ...)

FROM sflight AS f LEFT OUTER JOIN sbook AS bON f~carrid = b~carridAND f~connid = b~connidAND f~fldate = b~fldate WHERE f~fldate = '19981119'.WRITE: / sflight-price, sflight-paymentsum, ...

ENDSELECT.

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

ENDSELECT.

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

Page 213: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-38

© SAP AG

R

AALHLHQF...

SFLIGHT:SFLIGHT:CARRID CONNID ... DISTANCECARRID CONNID ... DISTANCE

SBOOK:SBOOK:CARRID CONNID ... BOOKIDCARRID CONNID ... BOOKID

Join condition

AA 0017 ... 2,572 AA 0017 ... 1AA 0017 ... 2,572 AA 0017 ... 2AA 0017 ... 2,572 AA ... ... ...

Join result table in the databaseJoin result table in the databaseCARRID CONNID ... DISTANCE CARRID CONNID ... BOOKID

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

0017040004020598...

2,5726,658 3,1621,689...

AAAAAAQF...

00170017...0598...

12...10...

Left outer join3. Minimize the Number of Transfers 7

Note:The result set always containsthe entire outertable

The left outer join contains all combinations of lines from the tables SFLIGHT and SBOOK whose values meet the join condition specified as ON <condition> (just as in the inner join). The lines in the left-hand table SFLIGHT that do not meet the condition are then added to the join table, and the fields from the right-hand table are filled with NULL values. Thus the result set contains all of the entries from the left-hand table. The WHERE condition is then applied to this temporary table, eliminating any unwanted entries from the result set.

Certain restrictions have been applied to the left outer join to ensure that the result set of a given join is always the same on all of the database platforms supported by SAP. For example, you may not specify conditions for the right-hand table in the WHERE condition. For further information, refer to the keyword documentation in the ABAP Editor for FROM.

Page 214: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-39

© SAP AG

R

Exercise: Reading Maximum and Minimum Values

Turn to the Exercises appendix for a description of the task

Page 215: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-40

© SAP AG

R

SELECT carrid connid fldate seatsoccINTO (f-carrid, f-connid, f-fldate, f-seatsocc) FROM sflight AS fWHERE seatsocc IN

( SELECT MAX( seatsocc ) FROM sflightWHERE carrid = f~carrid AND CONNID = f~connid

ORDER BY carrid connid fldate. )WRITE: sflight-carrid, sflight-connid,...ENDSELECT.

SELECT carrid connid fldate seatsoccINTO (f-carrid, f-connid, f-fldate, f-seatsocc) FROM sflight AS fWHERE seatsocc IN

( SELECT MAX( seatsocc ) FROM sflightWHERE carrid = f~carrid AND CONNID = f~connid

ORDER BY carrid connid fldate. )WRITE: sflight-carrid, sflight-connid,...ENDSELECT.

REPORT sapbc411s_select_subquery.DATA: f LIKE sflight, f1 LIKE sflight.SELECT carrid connid fldate max( seatsocc )FROM sflightINTO (f-carrid,f-connid, f-fldate, f-seatsocc) GROUP BY by carrid connidORDER BY carrid connid.

SELECT carrid connid fldate FROM sflightINTO (f1-carrid, f1-connid, f1-fldate) WHERE carrid = f-carridAND connid = f-connidAND seatsocc = f-seatsocc.

WRITE: / f1-carrid, f1-connid, f1-fldate, f-seatsocc. ENDSELECT.

ENDSELECT.

REPORT sapbc411s_select_subquery.DATA: f LIKE sflight, f1 LIKE sflight.SELECT carrid connid fldate max( seatsocc )FROM sflightINTO (f-carrid,f-connid, f-fldate, f-seatsocc) GROUP BY by carrid connidORDER BY carrid connid.

SELECT carrid connid fldate FROM sflightINTO (f1-carrid, f1-connid, f1-fldate) WHERE carrid = f-carridAND connid = f-connidAND seatsocc = f-seatsocc.

WRITE: / f1-carrid, f1-connid, f1-fldate, f-seatsocc. ENDSELECT.

ENDSELECT.

Subquery in the WHERE clause3. Minimize the Number of Transfers 8

A subquery is a SELECT statement within a SELECT statement, specified in the WHERE condition to check whether data from a database table or view meets certain conditions.

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

Page 216: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-41

© SAP AG

R

Exercise: Reading Grouped Data with Conditions

Turn to the Exercises appendix for a description of the task

Page 217: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-42

© SAP AG

R

3. Minimize the Number of Transfers 9

Having Clause

SELECT connid fldate count(*) AVG( luggweight ) INTO (connid, fldate, avg) FROM sbookWHERE carrid = 'LH' AND fldate > '19981201'GROUP BY connid fldateHAVING AVG( luggweight ) > 20.

... ENDSELECT.

REPORT sapbc411s_select_having.

SELECT connid fldate count(*) AVG( luggweight ) INTO (connid, fldate, count, avg) FROM sbookGROUP BY connid fldate WHERE carrid = 'LH'

AND fldate > '19981201'CHECK avg > 20. ...

ENDSELECT.

In the first example above, the system reads all of the table entries that meet the WHERE condition and transfers them from the database to the application server to process them further.

The second example uses a HAVING clause. This allows you to apply a logical condition to the groups defined in the GROUP BY clause. In this way, the result set is selected fully in the database, considerably reducing the amount of data transferred over the network.

Page 218: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-43

© SAP AG

R

Benefits of Rule 3

R/3 work processR/3 work process

DB work process DB work process

Operating systemOperating system

Database filesDatabase files

R/3 work process

DB work process

Networkcommunication

DB CPUuse

Database cacheDatabaseserviceprocesses

DB memoryuse

Physical I/O

The benefits of observing rule 3 are that: The number of data transfers between the database and application server, and thus the network load,

is minimized. The number of PREPARE and REOPEN operations in the database is reduced, leading to less CPU

use (especially when you avoid using nested SELECT statements).

Page 219: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-44

© SAP AG

R

Rule 4

Minimize the search overhead

As already explained at the beginning of this unit, the hit list is determined from the search area. The

search area is determined by the database optimizer, based on the database indexes and how they are used.

You should always try to minimize the search area by formulating the WHERE condition as exactly as possible and, if necessary, creating secondary indexes for database tables.

Page 220: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-45

© SAP AG

R

TabelleIndex A

Block 2

Block 3

Block 1

Satz 4

Satz 2

Satz 5Satz 1Satz 6

Satz 7

Satz 3

Index B

4. Minimize the Search Overhead 1Tables and Indexes

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

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

Page 221: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-46

© SAP AG

R

4. Minimize the Search Overhead 2

SELECT * FROM sbookWHERE carrid = 'AA'

AND connid = '0017'AND fldate = '19981205'.

... Processing...ENDSELECT.

SELECT * FROM sbookWHERE carrid = 'AA'

AND connid = '0017'AND fldate = '19981205'.

... Processing...ENDSELECT.

General rule I

Use the 'EQ' operator as much as possible

The fields in the WHERE condition of the above example that use the EQ operator are the first three key fields of table SBOOK. This allows the system to process the statement very quickly using the primary index.

An index field can only be used to process a statement if all of the fields that precede it in the index are specified using 'EQ' in the WHERE or ON condition. Statements that use the first n fields of an index can be processed very quickly.

Note: The sequence of fields in the WHERE clause is irrelevant - it is their sequence in the index that matters.

Page 222: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-47

© SAP AG

R

4. Minimize the Search Overhead 3

REPORT sapbc411d_select_many_eq.SELECT carrid connid fldate bookid

custtype orderdate FROM sbook into ...WHERE carrid = 'LH'AND fldate = '19981119'AND orderdate = '19981118'.

... Processing ...ENDSELECT.

REPORT sapbc411d_select_many_eq.SELECT carrid connid fldate bookid

custtype orderdate FROM sbook into ...WHERE carrid = 'LH'AND fldate = '19981119'AND orderdate = '19981118'.

... Processing ...ENDSELECT.

SELECT f~carrid f~connid f~fldate b~bookidb~custtype b~orderdate INTO (carrid, connid,fldate, bookid, custtype) FROM sflight AS fINNER JOIN sbook as bON f~carrid = b~carridAND f~connid = b~connidAND f~fldate = b~fldateWHERE f~carrid = 'LH' AND fldate = '19981119' AND orderdate = '19981118'.

... Processing ...ENDSELECT.

SELECT f~carrid f~connid f~fldate b~bookidb~custtype b~orderdate INTO (carrid, connid,fldate, bookid, custtype) FROM sflight AS fINNER JOIN sbook as bON f~carrid = b~carridAND f~connid = b~connidAND f~fldate = b~fldateWHERE f~carrid = 'LH' AND fldate = '19981119' AND orderdate = '19981118'.

... Processing ...ENDSELECT.

SBOOK key:mandtcarridconnidfldatebookid

Use 'EQ' as often as possible

In the first example, the WHERE conditition does not contain the second field of the primary index (CONNID). This means that the primary index cannot be used effectively. The database can only use the fields MANDT and CARRID, which are not particularly selective.

If a secondary index exists for the field ORDERDATE, a cost-based optimizer would recognize this as a quicker option, since the ORDERDATE field is far more selective than the MANDT and CARRID fields.

In the second example, the first three key fields of SBOOK are specified in the join condition, allowing the database to use the first part of the primary index to access the data. This makes the data selection far more selective, leading to shorter runtime.

You would only need to use the second example in situations where it is not possible to create a suitable secondary index.

Page 223: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-48

© SAP AG

R

4. Minimize the Search Overhead 4

1 2 3 4

Key of tableSBOOK

Primary index

MandMand CarridCarrid ConnidConnid FldateFldate

MandMand CarridCarrid ConnidConnid FldateFldate

Secondaryindex CarridCarrid FldateFldate OrderdateOrderdate

The system creates a primary index for every table in the database. This key corresponds to the structure of the key fields in the table.

When using the primary index, the system analyzes all of the AND conditions. However, the fields specified can only be used if they correspond to the structure of the index. For example, if you include MANDT, CARRID, and FLDATE in the WHERE condition, a primary index search will only use the fields MANDT and CARRID, since you have not specified the field CONNID.

If, on the other hand, you have created a secondary index with the above structure, a cost-based optimizer would use it, recognizing that the ORDERDATE field is far more selective.

Page 224: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-49

© SAP AG

R

4. Minimize the Search Overhead 5

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

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

Replace inner OR with an IN expression

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

General rule II

Some database optimizers do not process OR conditions, and cannot therefore use an index to process field f1.

Instead, use the IN operator. The optimizer converts the entire expression into a set of 'EQ' expressions, and can therefore use the index.

Page 225: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-50

© SAP AG

R

4. Minimize the Search Overhead 6

Selective fields at the beginning

non-selective: MANDT, BUKRSvery selective: BUCHUNGSNUMMER, BELNR, MATNR, KUNNR,

Small indexes

Avoid overlap (Disjunctive indexes)

Up to 3 indexes per table is OK

Avoid complex WHERE conditions with IN or OR conditions for index fields

NOT conditions in the SELECT statement cannot be processed using the index

Check how the system uses your indexes

Index design

While table design follows a logical pattern, index design is subject to more technical considerations. When you design a table, it is a good idea to place fields that represent an organizational structure (client, company code…) at the beginning of the structure. When you design an index, the opposite is true.

For an index to work efficiently, you need to place selective fields (for example, object number) at the beginning. Client and company code are not very selective fields.

You should construct your index from as few fields as possible, since some optimizers can combine two or more smaller indexes to process a query, but this does not work with large indexes.

Your table indexes should be as disjunctive as possible (that is, with as few common fields as possible). The more similar your table indexes, the greater the possibility that the optimizer will choose the wrong one.

Each index that you create makes it slower to insert entries in the table. Updates are slower if you add index fields. For this reason, tables to which you often add data (transaction data tables) should have as few indexes as possible. On the other hand, tables from which you normally only read can have more indexes. As a rule, you should not experience problems with up to three indexes for a table.

Complex conditions using IN and OR conditions cause the most problems for optimizers. Statements including NOT conditions cannot be processed using an index.

Use the 'Explain SQL' function in the SQL Trace to check which index the database uses.

Page 226: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-51

© SAP AG

R

4. Minimize the Search Overhead 7

Applicationserver

Databaseserver

Cursor cache

Data blockbuffer

AA0017 NewYork SanAA0064 San FranciscoLH0400 Frankfurt New

Shared SQLPoolSELECT C1 FROM SPFLISELECT C3 FROM SBOOKSELECT C2 FROM LIPSSELECT * FROM MARA

Oracle: globalmemory area

Secondaccess

AA0017 New York San FranAA0064 San Francisco New LH0400 Frankfurt New York

Cursor cache

First access

To improve performance, SQL statements are cached both at application server and at database server level.

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

Page 227: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-52

© SAP AG

R

4. Minimize the Search Overhead 8

DB memoryuse

DB CPUuse

R/3 work processR/3 work process

DB work process DB work process

Operating systemOperating system

Database filesDatabase files

R/3 work process

DB work process

Network Communication

Database cacheDatabaseserviceprocesses

Physical I/O

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

Page 228: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-53

© SAP AG

R

Rule 5

Reduce the database load

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

Page 229: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-54

© SAP AG

R

5. Reduce the Database Load 1

Buffer tablesAvoid reading data repetitivelyCheck for SELECT before changesORDER BY vs. SORTLogical databases

==> improves Scalability

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

This topic discusses in more detail how you can reduce the database load in your system.

Page 230: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-55

© SAP AG

R

What is table buffering?

When should you buffer tables?

What must you bear in mind when programming SQL access to buffered tables?

- ABAP Open SQL & table buffering

5. Reduce the Database Load 2

Page 231: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-56

© SAP AG

R

Appl.server

Databaseserver

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

PROGRAM XYZ

RESULT

Table buffer

21

3

45

Read data from database if it isnot already in thetable buffer

Table buffering - concept

5. Reduce the Database Load 3

Data transfer from database server to application server andtable buffer

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

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

You can also check the quality of the buffer in Transaction ST02 by choosing the required table.

Page 232: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-57

© SAP AG

R

Why buffer tables?

Appl.server

Databaseserver

SELECT SINGLE col1 .. FROM T001

PROGRAM XYZ

Table buffer

8 8 -- 600 ms600 ms

0.2 0.2 -- 1 ms1 ms

5. Reduce the Database Load 4

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

Page 233: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-58

© SAP AG

R

key1 key2 key3 Daten

key1 key2 key3 Daten

key1 key2 key3 Daten

key1 key2 key3 Daten

Resident buffering(100%)

Generic buffering1 key field

Generic buffering2 key fields

Partial buffering(single entry)

001001001001002002002002002002003003003003003003003003

001001001001002002002002002002002002003003003003003003003003003003003

001001001001001002002002002002002002002002002003003003003003003003003003003003003003

AA

BB

AABBBC

DC

AAABBCCCDDD

AA

BB

BAAAABBBC

DC

AAABBCCCCDDDD

42

31

513681230

53

2362423581234

Buffering types

5. Reduce the Database Load 5

There are three types of buffering: Resident buffering (100%): The first time the table is accessed, the entire table is loaded into the table

buffer. Generic buffering: In this method, you must specify a generic key (first n key fields) in the technical

attributes of the table in the ABAP Dictionary. This splits the table contents into generic areas. When you access data with one of the generic keys, the whole generic area is loaded into the buffer. Client-dependent tables are often buffered generically by client.

Partial buffering (single entry): Individual entries are read from the database and stored in the table buffer.

Page 234: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-59

© SAP AG

R

Application server A

Communication system

Database management system

Database isup to date

Local buffer isup to date

...

DDLOG

UPDATE T001...

Database

R/3 DB interface

Table buffer

Buffer Synchronization I

5. Reduce the Database Load 6

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

Page 235: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-60

© SAP AG

R

5. Reduce the Database Load 7

Synchronizing the buffer II

Application server A

Table buffer

Communication system

Database management system

Applciation server BBuffer isNOT up-to-date

Database isup-to-date

Local buffer is up-to-date

...

DDLOG

UPDATE T001...

Database

Table bufferR/3 DB interface

DDLOG

INSERT DDLOGINSERT DDLOG

If you have a distributed system with more than one application server, the buffer on application server B is not updated immediately.

The update statement is executed by the R/3 database interface, which writes an entry in table DDLOG logging the change to table T001.

Page 236: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-61

© SAP AG

R

Application server A Application server B Bufferinvalid

Database is up-to-date

Local buffer isup-to-date

...

SELECT DDLOGSELECT DDLOG

Buffer synchronized every 1-2 minutes

R/3 DB interface R/3 DB interface

5. Reduce the Database Load 8

Synchronizing the buffer III

Table buffer Table buffer

DDLOG DatabaseDDLOG

Database management system

Communication system

Each application server ('B' here in the example), periodically reads the contents of table DDLOG to invalidate the contents of its buffer if necessary.

The table buffer in a distributed system is automatically synchronized every 60 seconds (parameter rsdisp/buferftime).

Within this time, users on application server B can read 'old' data. The buffer data is not marked as invalid until after the synchronization. Once this has happened, the data, if required again, is reread from the database.

Page 237: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-62

© SAP AG

R

key1 key2 key3 Data

key1 key2 key3 Data

key1 key2 key3 DAta

key1 key2 key3 Data

Resident buffering(100%)

Generic buffering1 key field

Generic buffering2 key fields

Partial buffering(single entry)

001001001001002002002002002002003003003003003003003003

001001001001002002002002002002002

001001001001001002002002002002002002002002

When is the buffer invalid?

All changesinvalidate the buffer

Changes invalidatethe correspondinggeneric area

Changes using a work area invalidatethe individual entry.Other changes invalidate theentire table.

5. Reduce the Database Load 9

AA

BB

AABBBCC

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

Page 238: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-63

© SAP AG

R

When should you buffer tables?

You should buffer a table ifYou frequently read from it

It is relatively small(few entries, or few, short columns)

You mostly only read from it

You rarely change it (a few times a day or month)

Candidates for bufferingControl and Customizing tables

'Small' master data tables(100 material master records -> few changes)

5. Reduce the Database Load 10

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

Page 239: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-64

© SAP AG

R

Buffering tables

1.) Where?On the technical settings screen for a table in the ABAP Dictionary.

2.) Buffering typesFull (resident = 100%)

Generic (with the number of key fields for the generic key)

Single entry (partial buffering)

5. Reduce the Database Load 11

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

Page 240: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-65

© SAP AG

R

SQL statements that bypass the buffer

SELECT ... BYPASSING BUFFER

SELECT ... DISTINCT

SELECT ... COUNT, SUM, AVG, MIN, MAX

SELECT ... ORDER BY f1 ... fn

SELECT ... GROUP BY / HAVING

SELECT ... FOR UPDATE

SELECT ... JOIN

WHERE clause with IS NULL expression

WHERE clause with subquery

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

5. Reduce the Database Load 12

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

Page 241: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-66

© SAP AG

R

5. Reduce the Database Load 13

Avoid repeatedly reading dataIt causes unnecessary database load

It may produce different results each time

Reading data repetitively

Avoid reading the same data more than once in your applications. This is partly for runtime reasons, and partly because the R/3 System allows 'dirty reads' (exception: Oracle database).

This means that reading the same data twice can cause different results. Examine whether you can read data into an internal table, and then read the second time from the internal table instead of the database table.

Page 242: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-67

© SAP AG

R

5. Reduce the Database Load 14

ORDER BY... Does not necessarily mean that a certain index will be used in the database

… Often causes a large database overhead

Do you really need the data in a particular order?

ORDER BY or SORT?

There are two ways to read data in a particular order: 1. Using the ORDER BY addition to the SELECT statement. This ensures that the data is returned

correctly sorted from the database. 2. By sorting at application server level, using the SORT statement to sort the data in an internal

table. This reduces the load on the database system. Try to avoid using ORDER BY. This shifts the cost of sorting the data from the database server to

the application server. You cannot use the ORDER BY addition to force the database system to use a particular index. If the sort order is the same as the index used by the database, ORDER BY entails no costs. In this

case, ORDER BY is more efficient.

Page 243: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-68

© SAP AG

R

5. Reduce the Database Load 15

Predefined, optimized database accessSimplified list creation

Centrally optimized

But: Use the 'correct' logical database!

Logical databases

The advantage of logical databases is that they remove the coding required for data retrieval from your application program, simplifying the process of creating lists in executable (type 1) programs.

Note that you must use a logical database with an appropriate structure, otherwise the performance gains can rapidly become the complete opposite! For an example, refer to the program SAPBC411D_SELECT_VS_LDB in development class SAPBC411.

Page 244: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-69

© SAP AG

R

5. Reduce the Database Load 16

DB memoryuse

DB CPUuse

R/3 work processR/3 work process

DB work process DB work process

Operating systemOperating system

Database filesDatabase files

R/3 work process

DB work process

Networkcommunication

Database cacheDatabaseserviceprocesses

Physical I/O

The benefits of observing rule 5 are that you: Cause fewer I/O operations in the database

Minimize the memory use in the database Minimize the CPU use in the database Reduce the network communication

The consequence of all of this is that the database load is reduced .

Page 245: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-70

© SAP AG

R

ABAP Tuning Checklist - IDoes the program contain SELECT * statements?

Convert the statements into SELECT <col1><col2> statements, or use a projection view

Does the program contain CHECK statements for table fields within the SELECT … ENDSELECT loop?

Replace the CHECK statement with a suitable WHERE clauseDo SELECT statements on non-key fields use a suitable database index, or is the table buffered?

If you only (or mostly) read from the table, create an index for it in the ABAP Dictionary, or buffer it. Does the program use nested SELECT statements? Convert the nested select statements into database views or joins in the select statement.

Page 246: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-71

© SAP AG

R

ABAP Tuning Checklist - II

Does the program contain SELECT statements without a WHERE clause for tables that grow constantly (BSEG, MKPF, VBAK) ?

Program design is wrong

Are SELECT statements for master data buffered?

Does the program use SELECT… APPEND ITAB… ENDSELECT to fill internal tables

Change the program to fill the internal table using SELECT … INTO TABLE.

Does the program use SELECT… ORDER BY… statements?

Unless there is a suitable index with the same fields as the order by clause, read the data into an internal table and sort it there.

Page 247: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-72

© SAP AG

R

ABAP Tuning Checklist - III

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

Page 248: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-73

© SAP AG

R

Summary I

In this unit, you have learned the five rules for more efficient database programming.

Rule 1

Keep the result set small

Rule 2

Minimize the amount of data transferred

Rule 3

Minimize the number of data transfers

Page 249: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-74

© SAP AG

R

Rule 4

Minimize the search overhead

Rule 5

Reduce the database load

Summary II

Page 250: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 8-75

© SAP AG

R

By observing these rules, you can minimize the following:

The network communication between the database and application server

The memory use on the database server

The CPU use on the database server

The number of physical accesses to database files.

Summary III

Page 251: BC411 - Advanced ABAP Programming

© SAP AG

R

Exceptions and Message Handling: Contents

Defining exceptions in function modules and methods

Exception handling

Page 252: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 9-2

© SAP AG

R

Unit Objectives

Trigger exceptions in function modules and methods

Catch exceptions in ABAP programs

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

Page 253: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 9-3

© SAP AG

R

Exceptions

ExceptionsPLANE_OVERLOAD

Z_FREESEAT

.

.

.IF SEATSOCC > SEATSMAX.* RAISE plane_overload.

MESSAGE ... RAISINGplane_overload.

ENDIF.

Call

Function module/method

.

.

.CALL FUNCTION / CALL METHOD

EXPORTING ...IMPORTING ...EXCEPTIONS ...Plane_overload = 0101error_message = 0202others = 03 03 .

CASE sysy--subrcsubrc.WHEN 1....

ENDCASE.

When you create function modules and methods, you can define exceptions in the interface. You trigger them in your programs using one of the following statements: RAISE <exception> or MESSAGE ... RAISING <exception>.

The effect of these statements depends on whether the calling program is to handle the exceptions itself (EXCEPTIONS addition set in the call) or not:

If the calling program is to handle the exception, program control passes directly back to the caller with not program termination and no message. The export parameters have their old values.

If the calling program is not to handle the exception, the function module terminates in a runtime error when the RAISE statement occurs. If you use MESSAGE… RAISING… the system displays the message and does not trigger a runtime error.

You can address the general exception ERROR_MESSAGE for any function module or method call. This is the exception that is triggered when an error message occurs in the function module or method; it catches all E and A type messages (in batch input programs, these errors are logged), but ignores I, W, and S messages. You can use the OTHERS exception to catch any exceptions that you have not specifically queried.

Page 254: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 9-4

© SAP AG

R

Catching Runtime Errors

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

CATCH SYSTEM-EXCEPTIONS conversion_errors = 5 others = 6.pack = char.

ENDCATCH.IF sy-subrc = 5.

WRITE 'Conversion error'.ELSEIF sy-subrc = 6.

WRITE 'Other catchable runtime error'.ENDIF.

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

You can catch system exceptions (ABAP runtime errors) in the processing block between the CATCH and ENDCATCH statements. If a catchable runtime error occurs within this block:

The system jumps from the ABAP statement in which the error occurred directly to the ENDCATCH statement, irrespective of the number of control structure levels (IF, DO, LOOP, SELECT, CATCH…) that it has to bypass. The contents of the fields involved in the statement that caused the error cannot be guaranteed after the ENDCATCH statement.

The return value <rcn>, assigned to the system exception <excptn> is placed in the system field SY-SUBRC. If there is more than one expression <excptn> = <rcn>, the <rcn> of the first expression is returned. This is particularly important if you specify two different ERROR classes that contain the same runtime error.

CATCH… ENDCATCH may occur anywhere where IF …. ENDIF may also occur, that is, it may not span more than one event block.

Page 255: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 9-5

© SAP AG

R

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

<excpt>

System Exceptions

Error classError class

IndividualIndividualruntime errorruntime error

OTHERSOTHERS

arithmetic_errorsconversion_errors...

bcd_zero_divideconvt_to_number...

All catchable runtime errors

<rc1> ... <rcn> must be numeric literals. <excpt1> ... <exeptn> can be:

- The error ID of the relevant runtime error (for example DBCONVT_NO_NUMBER) For a list of catchable runtime errors, refer to the online documentation for the CATCH statement.

- One of the predefined ERROR classes Catchable runtime errors are assigned to ERROR classes. If you specify a class, the system catches all of the runtime errors assigned to it. For a list of error classes, refer to the online documentation for the CATCH statement.

- OTHERS If you specify OTHERS, the system catches all catchable runtime errors.

The system only catches runtime errors within the current call level. If a PERFORM or CALL FUNCTION statement occurs between CATCH and ENDCATCH, the system does not catch any runtime errors that occur in the corresponding subroutine or function module.

Page 256: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 9-6

© SAP AG

R

Nested CATCH… ENDCATCH Structures

CATCH SYSTEM-EXCEPTIONS compute_int_zerodivide = 1arithmetic_errors = 2.

.

.CATCH SYSTEM-EXCEPTIONS

file_access_errors = 5..

DO 10 TIMES.COMPUTE i = 1 / 0.

ENDDO..ENDCATCH...

ENDCATCH.

Sets sy-subrc

Continuesprocessing

You can nest CATCH… ENDCATCH structures to any depth. If a system exception occurs within a CATCH…ENDCATCH blocks, the system jumps to the ENDCATCH statement.

In the above example, the exception arithmetic_errors occurs in the inner CATCH… ENDCATCH block (division by zero). This exception is handled in the outer block. The runtime system looks for the exception in the current block first. If it does not find it, it looks in the next-higher block.

In the above example, the system exception arithmetic_errors exists in the outer block. The system therefore carries on processing at the ENDCATCH statement of the outer block.

Page 257: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 9-7

© SAP AG

R

Summary

You can trigger exceptions in function modules and methods using RAISE <excpt> or MESSAGE … RAISING <excpt>. The first variant leads to a runtime error if the calling program does not handle the exception.

You can also catch system exceptions and exceptions of function modules and methods globally and handle them using CATCH… ENDCATCH blocks.

Page 258: BC411 - Advanced ABAP Programming

© SAP AG

R

ABAP Modularization UnitsMemory modelInternal and external subroutinesFunction modulesMethodsScreens (CALL SCREEN)ModulesEventsLists (LEAVE TO LIST PROCESSING)Selection screens (CALL SELECTION SCREEN)Transactions (LEAVE TO / CALL TRANSACTION)Programs (SUBMIT)ContextsMacrosInclude programs

Page 259: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-2

© SAP AG

R

Unit Objectives

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

Explain how the memory model works

Explain parameter passing techniques

Identify how data is visible within different modularization units

Compare the different modularization techniques

Page 260: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-3

© SAP AG

R

Modularization Units

Taskstructuring

Taskstructuring

Internal subroutineInternal subroutineExternal subroutineExternal subroutineFunction moduleFunction moduleMethodMethod

Screen (CALL SCREEN)Screen (CALL SCREEN)

ModuleModuleEventEvent

List (LEAVE TO LIST PROCESSING)List (LEAVE TO LIST PROCESSING)Selection screen (CALL SELECTION SCREEN)Selection screen (CALL SELECTION SCREEN)

TransactionTransactionReport (SUBMIT)Report (SUBMIT)Dialog module (obsolete)Dialog module (obsolete)

ContextContext

Source codestructuring

Source codestructuring MacroMacro

Include programInclude program

There are two kinds of modularization units: Those that allow you to structure tasks, and those that allow you to structure your source code.

This unit concentrates on the visibility of data within modularization units. For this purpose, the list of 'classic' modularization units has been expanded to include screens, selection screens, and other objects.

Page 261: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-4

© SAP AG

R

Memory Areas: Logical Model I

R/3R/3 instance 1instance 1

R/3 database

R/3 instance n

R/3 instance n

System areasSystem areas

User 1 User 2 User n...

Lock table

SAP System

The memory model shows how different ABAP modularization units are implemented in the R/3 System.

The database is a central resource in the R/3 System. Each system has only one database. All components (server instance, client instances, spool processes, and so on) that are connected to

this database or that work with the same database, comprise an R/3 System. An instance is a part of an R/3 System that provides one or more services. You can start and stop a

single instance without affecting other instances or the R/3 System as a whole. Each R/3 database can have several SAP instances.

There is a single lock table that applies to all instances. Each R/3 instance contains a range of system areas, such as the cross-transaction application buffer,

context buffer, and so on. Each application server can support several active users. The following pages examine in more detail the area used by a single user.

Page 262: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-5

© SAP AG

R

Memory Areas: Logical Model II

User 1: R

/3 terminal session n

User 1: R

/3 terminal session n

System areasSystem areas

User 1: R/3 terminal session 1User 1: R/3 terminal session 1

External session 1

Program 1

AB

AP m

emory

Program 2

Internal session 1

Internal session n

External session n

Program 1A

BA

P mem

ory Program 2

Internal session 1

Internal session n

...

11

22 22

SAP Memory (SET /GET parameters)

When a user logs onto an instance (application server) in an R/3 System, he or she begins a new terminal session. You can open a further terminal session using RFC (CALL FUNCTION … DESTINATION).

All of the windows that you open in a terminal session belong to that session. The first window is opened automatically when you log on. You can create further windows by choosing System -> Create session or entering /o plus a transaction code in the command field. Existing windows remain unchanged when you create new ones. Each window is represented in the R/3 System by an external session.

Each of the statements CALL TRANSACTION, CALL DIALOG, and SUBMIT creates a new internal session. For example, if you enter /nSE38 in your first window, the system executes the statement CALL TRANSACTION 'SE38', and generates an internal session.

You can use SAP memory and ABAP memory to pass data between programs. SAP memory is a user-specific memory area for storing field values. Its contents are retained for the

duration of your terminal session, and can be used in all sessions. All external sessions can access SAP memory. It is therefore not so useful for passing data between internal sessions.

For further information about ABAP memory, refer to the Data clusters appendix.

Page 263: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-6

© SAP AG

R

Visibility Area of a Program

User 1: R

/3 session n

System areasSystem areas

User 1: R/3 session 1

External session 1

Program 1

AB

AP m

emory

Internal session 1

External session n

...

Lock tableLock table

R/3 DatabaseR/3 Database

SAP memoryVisibilityarea of theprogram

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

Page 264: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-7

© SAP AG

R

Internal Session

System areaSystem area

Program <pgm>

Ext. subroutine 1

Current list systemCurrent list systemRoll area

Ext. subroutine 2

Function group 1/class definitionExt. subroutine 1

Ext. subroutine 2

Function group n/class definitionExt. subroutine 1

Ext. subroutine 2

Main program group

Additional program group 1

Additionalprogram group 2

1

1 CALL FUNCTION / CALL METHOD

1

Internal session

When the system starts an internal session, it creates the main program group. Additional program groups are created when you call a function module from a function group that has not yet been loaded (CALL FUNCTION) or when you call a method of a class definition that has not yet been loaded (CALL METHOD). A program group can contain several programs. The first program in a program group is the main program.

When you call an external subroutine (PERFORM form(prog) or PERFORM form IN PROGRAM prog), the corresponding program (if it has not already been loaded) is loaded into the same program group as the calling program. If, on the other hand, the subroutine is in a function group or class definition that has not yet been loaded, the system creates a new program group as it would in a CALL FUNCTION or CALL METHOD statement.

Page 265: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-8

© SAP AG

R

Table Work Areas / Common Parts

Common part C1Common part C1

Main programPROGRAM /FUNCTION POOL

Table work areaTable work areaRoll area

Additional program 1<prog>

Additional program 2<prog>

Program group

Common part C2Common part C2

Table work areas (created using the TABLES) statement and common data areas (DATA BEGIN/END OF COMMON PART…) are created once for each program group and shared by all programs within the group.

Note: The above illustration shows a single program group with its shared data areas. You should avoid using TABLES and COMMON PART wherever possible, since they can lead to

undetected changes in subroutines, modules, events, and screens. Use typed variables instead. The only situations in which you still need to use the TABLES statement is with logical databases

and when you use ABAP Dictionary fields on screens. Otherwise, TABLES and COMMON PART are obsolete.

Page 266: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-9

© SAP AG

R

The Dangers of Working with Common Data Areas, Call Hierarchies I

. . .TABLES: SPFLI.

PERFORM TEST01(PROG2).

CALL FUNCTION'TEST_FB' ...

CALL METHOD o1->m1

. . .TABLES: SPFLI.

PERFORM TEST01(PROG2).

CALL FUNCTION'TEST_FB' ...

CALL METHOD o1->m1

PROG1

ABAP. . .TABLES: SPFLI.FORM TEST01.CALL SCREEN 0100.ENDFORM.

. . .TABLES: SPFLI.FORM TEST01.CALL SCREEN 0100.ENDFORM.

PROG2

ABAP . . .TABLES: SPFLI.FUNCTION TEST_FB.PERFORM

TEST01(PROG2).

ENDFUNCTION.CLASS IMPLEMENTATION.

METHOD: m1 ...ENDMETHOD.

ENDCLASS.

. . .TABLES: SPFLI.FUNCTION TEST_FB.PERFORM

TEST01(PROG2).

ENDFUNCTION.CLASS IMPLEMENTATION.

METHOD: m1 ...ENDMETHOD.

ENDCLASS.

ABAP

SPFLI

PROG1_0100

111222

SPFLISPFLI SPFLISPFLI

F Group/ Class

When you first call a function module, a method, or an external subroutine, the system assigns their data areas firmly to the main program of the program group. Subsequent calls from other program groups do not change this initial assignment. This means that the main program whose data is shared by an external subroutine can depend on the call sequence.

The same applies to screne calls from the called form routine. In the example, the screen PROG1_0100 from the main program of the program group is displayed.

When the subroutine TEST01 is called, the system does not reserve any memory for table SPFLI in program PROG2. PROG1 and PROG2 share the table work area.

Page 267: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-10

© SAP AG

R

The Dangers of Working with Common Data Areas, Call Hierarchies II

. . .TABLES: SPFLI.

CALL FUNCTION'TEST_FB'

.

.PERFORM

TEST01(PROG2).

. . .TABLES: SPFLI.

CALL FUNCTION'TEST_FB'

.

.PERFORM

TEST01(PROG2).

PROG1

ABAP. . .TABLES: SPFLI.FORM TEST01.CALL SCREEN 0100.ENDFORM.

. . .TABLES: SPFLI.FORM TEST01.CALL SCREEN 0100.ENDFORM.

PROG2

ABAP. . .TABLES: SPFLI.FUNCTION TEST_FB.PERFORM

TEST01(PROG2).

ENDFUNCTION.

. . .TABLES: SPFLI.FUNCTION TEST_FB.PERFORM

TEST01(PROG2).

ENDFUNCTION.

ABAP

SPFLI

FGROUP_0100

111

SPFLISPFLI SPFLISPFLI

...

F group / Class

222

When you call a function module, the table work areas of the function group are not linked to the calling program. Instead, you must transfer data using the interface of the function module.

When you call an external subroutine from a function module, the table work areas of the subroutine are linked to the main program of the function group.

In the above example, when the subroutine TEST01 is called, the system, once again, does not reserve any memory in program PROG2 for table SPFLI. The main program of the additional program group and PROG2 share the table work area.

The same applies to screens that you call from form routines. In the example, the system uses screen 0100 and its status from the main program of the function group.

To prevent errors, avoid using TABLES work areas.

Page 268: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-11

© SAP AG

R

Subroutines, Function Modules, and Methods

Each has anexplicitinterface

Taskstructuring

Taskstructuring

Internal subroutineInternal subroutine

External subroutineExternal subroutine

Function moduleFunction module

MethodMethod

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

Page 269: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-12

© SAP AG

R

Calling a Function Module, Method, or External Subroutine

External session 1 -> Window 1External session 1 -> Window 1

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

Internal session 1

Main program of TA/program

FunctionFunctiongroup 1group 1

ExternalPERFORM 1

AB

AP

Mem

ory

(ses

sion

-spe

cific

)Internal session 2

Main programof called

TA/programFunctionFunctiongroup 1group 1

Functiongroup 3

Functiongroup 2

CALLMETHOD 1

When you call a function module or method, the system loads the corresponding function group or class definition and initializes its global data. The global data is shared by all function modules or methods in the function group or class within the same internal session.

In a new internal session (created with CALL TRANSACTION, for example), the system creates new global data for function group 1. This means that the global data for function modules called in the second session is different to that used by function modules in the first internal session.

The system behaves in the same way if an external subroutine or a method of an instance is called in a further internal session. The system always creates new global data in the new session.

Page 270: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-13

© SAP AG

R

PROGRAM / REPORT / FUNCTION POOL / CLASS POOLPROGRAM / REPORT / FUNCTION POOL / CLASS POOL

Local data

Statements

Global data

ReadUSINGVALUE

CHANG.VALUE

USING CHANGING TABLES

Mainprogram

Inter-face

Subroutine

Write

Interfaces in Subroutines

When you write a subroutine, you name its formal parameters and determine how they will be passed. The formal parameters are the explicit interface for data exchange with the subroutine.

Internal subroutines can access the data in the main program (global data). You declare local data in subroutines. This data is only visible within the subroutine, and only occupies memory space while the subroutine itself is running. As well as data, you can declare statics.

The STATICS statement allows you to declare data within a procedure (form, function module, or method) that is visible locally but has a static lifetime. This means that instead of lasting for the runtime of the procedure, they are retained for the entire duration of the calling program. They are not recreated each time you call the procedure. Instead, the existing variable, with its existing value, is taken from the stack. This allows you to build a local memory for forms, function modules, and methods.

You can create a local copy of a global field or table work area using the GLOBAL statement. When you leave the subroutine, the system restores the old values of the LOCAL objects.

Page 271: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-14

© SAP AG

R

Methods for Passing ParametersForm in subroutine (FORM)Form in subroutine (FORM)

By valueUSING VALUE

CHANGING VALUE

By referenceUSING/TABLES

CHANGING/TABLESRead Write

Form in calling program (PERFORM)Form in calling program (PERFORM)By valueUSING

CHANGING

By referenceUSING/TABLES

CHANGING/TABLESReadWrite

Cost No parameters 1One parameter 1.3

1.72.1

Two parameters 1.52.32.9

Three parameters 1.72.93.7

Cost No parameters 1One parameter 1.3

1.72.1

Two parameters 1.52.32.9

Three parameters 1.72.93.7

112233

112233

112233

11 By reference 22 By value 33 By value, returning value

When you write a subroutine, you define how its parameters will be passed. When you call a subroutine, you use CHANGING to define the actual parameters that may be

changed in the subroutine. Calling a subroutine without parameters requires hardly any runtime. The more parameters you pass,

the greater the runtime. Passing parameters by reference requires less time than passing them by value. The costs for passing a single parameter by value depend on its size (of a structure, for example).

Page 272: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-15

© SAP AG

R

FUNCTION POOL/ CLASS POOLFUNCTION POOL/ CLASS POOL

Local data

Statements

Global data

IMPORTING EXPORTING TABLES CHANGING

Main program/class definition

Interface

Function module/method

EXCEP-TIONS

Interfaces in Function Modules / Methods

When you define a function module, you specify its IMPORTING, EXPORTING, CHANGING, and TABLES parameters. Methods only have IMPORTING, EXPORTING, and CHANGING parameters. Programs can only exchange data with function modules and methods using their interfaces. There is no general access to the data in the calling program.

Function modules can address the data (global data) of their main program (function group). Methods can access the global data within their class.

You can define local data in function modules and methods. This data is only visible within the function module or method, and only occupies memory space while the relevant procedure is actually running.

When you define a function module or method, you can also define exceptions for error handling.

Page 273: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-16

© SAP AG

R

Screens, Modules, and Events

Task structuring

Task structuring

ScreenScreen

ModuleModule

EventEvent

Screens are always assigned to the main program of the active program group. This program must contain the screen modules.

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

Page 274: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-17

© SAP AG

R

Interfaces of Screens, Modules, and Events

PROGRAM/FUNCTION POOL/CLASS POOLPROGRAM/FUNCTION POOL/CLASS POOL

Flow logic

I/O fields

Global data

Statements

Statements

Module

Event

Screen

Samenames

No localdata

The interface of a screen consists of its input/output fields. Data transfer between screens and ABAP programs is automatic as long as the screen fields and ABAP fields have the same names.

Modules have no local data. Instead, they always use the global data of the main program (module pool).

Events have no local data. Instead, they always use the the global data of the main program (executable program, type 1). Note: Events that read data from tables in logical databases (GET <table>) are implemented internally as subroutines. Data declarations within these events therefore only declare local fields.

Page 275: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-18

© SAP AG

R

Screen/List/Selection Screen

ScreenScreen (CALL SCREEN)(CALL SCREEN)

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

Sel. screenSel. screen (CALL SELECTION(CALL SELECTION--SCREEN)SCREEN)

TaskstructuringTaskstructuring

Page 276: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-19

© SAP AG

R

CALL SCREEN

External session 1 -> Window 1External session 1 -> Window 1

SAP Memory (User-specific, notsession-specific)

SAP Memory (User-specific, notsession-specific)

Internal session 1

AB

AP

Mem

ory

sess

ion-

spec

ific)

Scre

en s

tack

screen 1

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1

Main program

of TA/report

Functiongroup 1A

BA

P M

emor

y (s

essi

on-s

peci

fic)

Scre

en s

tack screen 2B

efor

e ca

llA

fter c

all

screen 1

SAP Memory (User-specific, notsession-specific)

SAP Memory (User-specific, notsession-specific)

Mainprogram

of TA/report Function

group 1

Each internal session has a screen stack. Each CALL SCREEN statement adds a new screen to the stack and cretes a new list system (refer to

the List System page). The CALL SCREEN statement calls a screen belonging to the main program of the main or

additional program group, depending on which is active.

Page 277: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-20

© SAP AG

R

Implicit Exit / LEAVE SCREEN

External session 1 -> Window 1External session 1 -> Window 1

SAP Memory (user-specific, notsession-specific)

SAP Memory (user-specific, notsession-specific)

AB

AP

Mem

ory

(ses

sion

-spe

cific

)

Scre

en s

tack

screen 1

External session 1 -> Window 1External session 1 -> Window 1

Main program

of TA/report

Functiongroup 1A

BA

P M

emor

y (s

essi

on-s

peci

fic)

Scre

en s

tack

screen 1B

efor

e ca

llA

fter c

all

screen 2

SAP Memory (user-specific, notsession-specific)

SAP Memory (user-specific, notsession-specific)

Main program

of TA/report

Functiongroup 1

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

Page 278: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-21

© SAP AG

R

List SystemBasic list

List level 0

Detail listList level 1

Detail listList level 2

... ...

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

.

.

.

. ...

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

Page 279: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-22

© SAP AG

R

Several List Systems

List system 1 List system 2

Called screenCalled screen

LEAVE TOLIST-PROCESSING

CALL SCREEN

LEAVE TOLIST-PROCESSING

Not necessarilydisplayed

Starting screenStarting screen

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

Page 280: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-23

© SAP AG

R

Several List Systems - Example I

. . .TOP-OF-PAGE. ... ...CALL FUNCTION

'WRITE_TEXT'..

CALL FUNCTION'CALL_SCREEN_AND_WRITE'

. . .TOP-OF-PAGE. ... ...CALL FUNCTION

'WRITE_TEXT'..

CALL FUNCTION'CALL_SCREEN_AND_WRITE'

SAPBC411D_CALL_FM_WRITE

...

FUNCTION WRITE_LIST....WRITE: text.

ENDFUNCTION.TOP-OF-PAGE. ...

FUNCTION WRITE_LIST....WRITE: text.

ENDFUNCTION.TOP-OF-PAGE. ...

Function group 1

List system (SAPBC411D_CALL_FM_WRITE)

11

The program SAPBC411D_CALL_FM_WRITE calls the function module WRITE_LIST. Since there are no further CALL SCREEN statements, SAPBC411D_CALL_FM_WRITE remains the main program responsible for the screen. The WRITE statement in the function module therefore writes in the list system of the main program. The TOP-OF-PAGE event is also assigned to the main program. The list displayed by the function module is therefore not a standalone list.

The same would apply if you called a method of a class instead of a function module.

Page 281: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-24

© SAP AG

R

Several List Systems - Example II

. . .TOP-OF-PAGE. ... ...CALL FUNCTION

'WRITE_TEXT'..

CALL FUNCTION'CALL_SCREEN_AND_WRITE'

. . .TOP-OF-PAGE. ... ...CALL FUNCTION

'WRITE_TEXT'..

CALL FUNCTION'CALL_SCREEN_AND_WRITE'

...

List System (function group 2)

FUNCTION call_screen_and_write....CALL SCREEN 200. "Create new list

"systemPROCESS BEFORE OUTPUT.MODULE suppress_dialog.

PROCESS AFTER INPUT.MODULE leave_to_list.MODULE back.

MODULE suppress_dialog OUTPUT.SUPPRESS DIALOG.ENDMODULE.MODULE LEAVE_TO_LIST INPUT.

LEAVE TO LIST-PROCESSING.WRITE: ...

ENDMODULE.MODULE BACK.

LEAVE TO SCREEN 0.ENDMODULE.TOP-OF-PAGE. ...

FUNCTION call_screen_and_write....CALL SCREEN 200. "Create new list

"systemPROCESS BEFORE OUTPUT.MODULE suppress_dialog.

PROCESS AFTER INPUT.MODULE leave_to_list.MODULE back.

MODULE suppress_dialog OUTPUT.SUPPRESS DIALOG.ENDMODULE.MODULE LEAVE_TO_LIST INPUT.

LEAVE TO LIST-PROCESSING.WRITE: ...

ENDMODULE.MODULE BACK.

LEAVE TO SCREEN 0.ENDMODULE.TOP-OF-PAGE. ...

222

((SAPLFKT2_0200)

Function group 2

SAPBC411D_CALL_FM_WRITE

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

Page 282: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-25

© SAP AG

R

LEAVE TO SCREEN

External session 1 -> Window 1External session 1 -> Window 1

SAP Memory (user-specificnot session-sepecific)

SAP Memory (user-specificnot session-sepecific)

Internal session 1

Main program

of TA/reportA

BA

P M

emor

y (s

essi

on-s

peci

fic)

Scre

en s

tack

screen 1

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1

AB

AP

Mem

ory

(ses

sion

-spe

cific

)

Scre

en s

tack

Bef

ore

call

Afte

r cal

l

screen 2

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

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

screen 1

screen 3Main

program of TA/report

Functiongroup 1

Functiongroup 1

The LEAVE TO SCREEN statement replaces the active screen on the stack with the screen that you are calling.

This has the same effect as using the statements SET SCREEN <nnnn> and LEAVE SCREEN. LEAVE SCREEN differs from CALL SCREEN in that you cannot return to the calling screen

(screen 2 in the example). In the case of LEAVE TO SCREEN 0, the system processes any code occurring after the CALL

SCREEN statement if you are working in CALL mode. Otherwise, it exits to the transaction menu.

Page 283: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-26

© SAP AG

R

CALL SELECTION-SCREEN

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1

Mainprogram

of TA/report

Functiongroup 1A

BA

P M

emor

y (s

essi

on-s

peci

fic)

screen 1

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1

AB

AP

Mem

ory

(ses

sion

-spe

cific

)

Bef

ore

call

Afte

r cal

lscreen 1

screen 2Main

programof TA/report

Functiongroup 1

SAP Memory (user-specific not session-specific)

SAP Memory (user-specific not session-specific)

SAP Memory (user-specific not session-specific)

SAP Memory (user-specific not session-specific)

Scre

en s

tack

Scre

en s

tack

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

The selection screen must be defined in the current main program.

Page 284: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-27

© SAP AG

R

Transaction / Program

Transaction (LEAVE TO / CALL TRANSACTIONTransaction (LEAVE TO / CALL TRANSACTION

Program (SUBMIT )Program (SUBMIT )Taskstructuring

Taskstructuring

Page 285: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-28

© SAP AG

R

CALL TRANSACTION ‘TA01’ /SUBMIT PROG01 AND RETURN

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1

Main programof calling

transaction or programA

BA

P M

emor

y (s

essi

on-s

peci

fic)

Bef

ore

call

Afte

r cal

l

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1Main program of

calling transaction or

programAB

AP

Mem

ory

(ses

sion

-spe

cific

)

New internal session 2

Main program of called TA01

orprogram PROG01

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

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

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

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

CALL TRANSACTION and SUBMIT … AND RETURN both open a new internal session that contains a new program context with the program data.

The new session is placed on top of the stack of internal sessions. CALL DIALOG behaves in the same way. Each step in the call chain (CALL TRANSACTION, SUBMIT, CALL DIALOG) creates its own

internal session.

Page 286: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-29

© SAP AG

R

Implicit Exit / LEAVE PROGRAM

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1Main programof transactoin

or programPROG01A

BA

P M

emor

y (s

essi

on-s

peci

fic)

Internal session 2

Main program ofended TA01

or program PROG01

External session 1 -> Window 1External session 1 -> Window 1

Internal session 1

AB

AP

Mem

ory

(ses

sion

-spe

cific

)SAP Memory (user-specific,

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

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

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

not session-specific)

Mainprogram

Bef

ore

exiti

ng

Afte

r exi

ting

When a program ends, the top entry is removed from the stack of internal sessions. Control passes back to the point at which the program was called.

The same occurs when you use the explicit statement LEAVE PROGRAM.

Page 287: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-30

© SAP AG

R

External session 1 -> Window 1External session 1 -> Window 1

LEAVE TO TRANSACTION ‘TA01’

Internal session 3

Main programof callingprogram

AB

AP

Mem

ory

(ses

sion

-spe

cific

)External session 1 -> Window 1External session 1 -> Window 1

AB

AP

Mem

ory

(ses

sion

-spe

cific

)

New internal session 1

Main program of TA01

Internal session 1

Internal session 2

Main program 2

Main program 1

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

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

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

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

Bef

ore

call

Afte

r cal

l

LEAVE TO TRANSACTION deletes all of the sessions in the stack and creates a new session containing the called transaction.

Like LEAVE TO SCREEN, it does not allow you to return to the caller.

Page 288: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-31

© SAP AG

R

SUBMIT PROG01

External session 1 -> Window 1External session 1 -> Window 1

Internal session 2

Main programof callingprogram

AB

AP

Mem

ory

(ses

sion

-spe

cific

)External session 1 -> Window 1External session 1 -> Window 1

AB

AP

Mem

ory

(ses

sion

-spe

cific

)

New internal session 2

Main program of

programPROG01

Internal session 1

Main program 1

Internal session 1

Main program 1

SAP Memory (user-specific, notsession-specific)

SAP Memory (user-specific, notsession-specific)

SAP Memory (user-specific, notsession-specific)

SAP Memory (user-specific, notsession-specific)

Bef

ore

call

Afte

r cal

l

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

Page 289: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-32

© SAP AG

R

Context

Taskstructuring

Taskstructuring Context (SUPPLY/DEMAND)Context (SUPPLY/DEMAND)

Refer to the Contexts unit.

Page 290: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-33

© SAP AG

R

Structuring Source Code

Include programsInclude programs

MacrosMacros

Source codestructuringSource codestructuring

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

Page 291: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-34

© SAP AG

R

Include Programs

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

INCLUDE bc411d_test_transactiontop.

INCLUDE bc411d_test_transactioni01.

INCLUDE bc411d_test_transactiono01.

INCLUDE bc411d_test_transactionf01.

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

INCLUDE bc411d_test_transactiontop.

INCLUDE bc411d_test_transactioni01.

INCLUDE bc411d_test_transactiono01.

INCLUDE bc411d_test_transactionf01.

INCLUDE prog.

You use include programs to create shared program sections or to divide programs into smaller parts that are easier to maintain.

The INCLUDE statement has the same effect as copying the source code of the include program into the main program at the point where it occurs. The syntax check also checks the contents of include programs. Includes are not loaded dynamically at runtime, they are expanded when the program is generated.

Include programs do not have a parameter interface. They provide a library function for complex ABAP programs. They are used in the main programs of function modules and in module pools (see example) to group together parts of the program that logically belong together. The ABAP Workbench supports complex program development by creating include programs by forward navigation and assigning unique names to them.

Include programs cannot run independently, but msut be embedded in other programs. You can embed includes within other includes, but recursive calls are not allowed.

You can use the where-used list function in the Repository Browser to find the programs in which a particular include is used.

Page 292: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-35

© SAP AG

R

Macros

DATA: RESULT TYPE I,N1 TYPE I VALUE 5,N2 TYPE I VALUE 6.

DEFINE OPERATION.RESULT = &1 &2 &3.OUTPUT &1 &2 &3 RESULT.

END-OF-DEFINITION.

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

END-OF-DEFINITION.

OPERATION 4 + 3 .OPERATION 2 ** 7.

DATA: RESULT TYPE I,N1 TYPE I VALUE 5,N2 TYPE I VALUE 6.

DEFINE OPERATION.RESULT = &1 &2 &3.OUTPUT &1 &2 &3 RESULT.

END-OF-DEFINITION.

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

END-OF-DEFINITION.

OPERATION 4 + 3 .OPERATION 2 ** 7.

DEFINE <macro>.<statements>

END-OF-DEFINITION

Output: The result of 4 + 3 is 7The result of 2 ** 7 is 128

You define macros using the statement block shown above. You must specify full statements between the DEFINE and END-OF-DEFINITION statements. The

statements may contain up to nine placeholders &1, &2, … , &9. The definition of a macro must appear in the program before it is called.

You run a macro using the statement <macro> [<p1> <p2> … <p9>]. When the program is generated, the macro is replaced by the corresponding statements, and the

placeholders &i are replaced by the parameters <pi>. Macros may call other macros, but may not call themselves.

The above example contains definitions for two macros, OPERATION and OUTPUT. OUTPUT is nested within OPERATION. OPERATION is called three times with different parameters. Note how the placeholders &1, &2 … are replaced.

The disadvantage of macros is that the macro call is often difficult to interpret, especially if the definition and call are a long way apart in the program. Another disadvantage is that the Debugger does not step through macros. Instead, it executes them in a single step.

Page 293: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 10-36

© SAP AG

R

Summary

In this unit, you have learnedHow the different modularization units fit into the memory model

How you can pass parameters in ABAP

What data is visible within modularization units

How to evaluate the different modularization units, based on comparison criteria

Page 294: BC411 - Advanced ABAP Programming

© SAP AG

R

Dynamic Program Generation: Contents

Dynamic ABAP Programming

Generating temporary and persistent programs at runtime

Page 295: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-2

© SAP AG

R

Unit Objectives

Generate programs at runtimeStore generated programs temporarily in a subroutineStore generated programs permanently in the R/3 Repository

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

Page 296: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-3

© SAP AG

R

Dynamic ABAP Programming

Dynamic statements

Field symbols

Generating programs from programs

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

Program Program (subrountine) 2(subrountine) 2GENERATE

<f>

Program 1Program 1

Dynamic programming means specifying the type, length, offset, number of lines, or name of a program object at runtime.

ABAP supports various kinds of dynamic programming: Dynamic extension of internal tables Dynamic offset and length specification (in MOVE, WRITE TO, formal parameters, and field

symbols) Dynamic specification of program object names (the name of a table, modularization unit, sort

criterion, control level criterion, and so on) Dynamic specification of type and data declarations

You can use the following techniques: Dynamic statements

Certain statements allow dynamic programming. For example, you can specify a function module name at runtime in the CALL FUNCTION statement. Field symbols (dynamic ASSIGN, dynamic type specification, ASSIGN COMPONENT) Program generation from within a program

You can store ABAP code in an internal table and generate it into a program at runtime.

Page 297: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-4

© SAP AG

R

Dynamic Programming - ExamplesTABLES: SFLIGHTDATA: fm_name(30) TYPE c VALUE 'POPUP_TO_CONFIRM_STEP',

screen_no(4) TYPE n VALUE '0100',tab_name(30) TYPE c VALUE 'SFLIGHT',upro_name(30) TYPE c VALUE 'MY_FORM',prog_name(30) TYPE c VALUE 'sapbc411d_demo',

CALL FUNCTION 'POPUP_TO_CONFIRM_STEP'.CALL FUNCTION fm_name.

CALL SCREEN '0100'.CALL SCREEN screen_no.

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

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

TABLES: SFLIGHTDATA: fm_name(30) TYPE c VALUE 'POPUP_TO_CONFIRM_STEP',

screen_no(4) TYPE n VALUE '0100',tab_name(30) TYPE c VALUE 'SFLIGHT',upro_name(30) TYPE c VALUE 'MY_FORM',prog_name(30) TYPE c VALUE 'sapbc411d_demo',

CALL FUNCTION 'POPUP_TO_CONFIRM_STEP'.CALL FUNCTION fm_name.

CALL SCREEN '0100'.CALL SCREEN screen_no.

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

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

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

Page 298: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-5

© SAP AG

R

Specifying Names at Runtime

SQLSELECT (<itab1>)FROM (<c>) INTO ...WHERE (<itab2>).

Sorting and control level processingin internal tablesSORT <itab> BY (<c>).AT NEW (<c>).AT END OF (<c>).

ReportSUBMIT (<c>).

Subroutine callsPERFORM (<c>) IN PROGRAM (<c>).

ParenthesesParentheses

Function modulesCALL FUNCTION <fm>.

Authorization checksAUTHORITY-CHECKOBJECT <obj> ID <name>FIELD <field>.

Screen CALL SCREEN <scr>.

TransactionCALL TRANSACTION <tc>.

MessageMESSAGE ID <id> TYPE <m_type>NUMBER <no>.

Variable instead of text literalVariable instead of text literal

If you often need to specify variable program object names in ABAP statements, you can use variables instead of text literals.

Certain statements also allow you to specify program object names dynamically using the parenthesis syntax, namely:

The SELECT, FROM, WHERE, GROUP BY and ORDER BY clauses of the SELECT statement. Sort criteria and control level criteria in internal tables. The SUBMIT statement. The long form of the PERFORM statement, that is, PERFORN (<c>) IN PROGRAM (<c>) for

external performs, or PERFORM (<c>) IN PROGRAM for internal calls. Note that some ABAP statements have a short form that does not support dynamic programming,

but a long form that does (for example, PERFORM, MESSAGE).

Page 299: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-6

© SAP AG

R

Generating Programs from Within Progams

Subroutine poolSubroutine pool

GENERATE SUBROUTINE POOLGENERATE SUBROUTINE POOL

REPORT ztest.FORM display.WRITE 'Generated program'.ENDFORM.

<itab><itab>REPORT ztest.WRITE 'Generated program'.

<itab><itab>

INSERT REPORTINSERT REPORT

external PERFORMexternal PERFORM SUBMITSUBMIT

ABAPRepositoryRepository

Generating temporary programs Generating persistent programs

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

You can create either temporary or persistent programs.

Page 300: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-7

© SAP AG

R

Generating Temporary Programs

REPORT sapbc411d_subroutine_pool.TYPES: editor_line_type(72) TYPE c.DATA: source_table TYPE STANDARD TABLE OF editor_line_type

WITH KEY TABLE LINE WITH HEADER LINE,program_name LIKE sy-cprog.

APPEND: 'REPORT test.' TO source_table,'FORM display.' TO source_table,'WRITE ''I am temporary''.' TO source_table,'ENDFORM.' TO source_table.

GENERATE SUBROUTINE POOL source_table NAME program_name.PERFORM display IN PROGRAM (program_name).

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

To store your source code, create an internal table with the same line type as the ABAP Editor. The statement GENERATE SUBROUTINE POOL <itab> NAME <program> generates a

temporary program from the internal table <itab>. The program is created automatically, and its program name is returned to the field <program_name>. You can run the generated code from the program that generated it using an external perform.

Page 301: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-8

© SAP AG

R

Generating Persistent Programs

TYPES: editor_line_type(72) TYPE c.DATA: source_table TYPE STANDARD TABLE OF editor_line_type

WITH KEY TABLE LINE WITH HEADER LINE,program_name LIKE sy-cprog.

APPEND: 'REPORT zgenprog.' TO source_table,'WRITE ''I'm persistent''.' TO source_table.

INSERT REPORT 'ZGENPROG' FROM source_table.SUBMIT zgenprog AND RETURN.

INSERT REPORT <program> FROM <itab>.SUBMIT <program> [AND RETURN].

You can generate a persistent program in the R/3 Repository from the coding in your internal table using the statement INSERT REPORT <program> FROM <itab>.

The attributes are set automatically by the system. You can change them afterwards using the function module 'TR_TADIR_INTERFACE'.

Page 302: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 11-9

© SAP AG

R

Summary

You can program dynamically in ABAP using dynamic statements, field symbols, and program generation.

Generating programs from other programs is a very powerful form of dynamic programming. You can keep your generated coding either temporarily or permanently.

Page 303: BC411 - Advanced ABAP Programming

© SAP AG 1999

This section contains supplementary material to be used for reference

This material is not part of the standard course

Therefore, the instructor might not cover this during the course presentation

Appendix

Page 304: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 12-2

© SAP AG

R

Further Information about Internal Tables and Extracts

Internal Tables and Extracts

Accessing Table Entries Directly (Release 4.5A)

Page 305: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 12-3

© SAP AG

R

Internal Tables and Extracts (1)

AT FIRST. . ENDAT.AT NEW f1. . ENDAT.AT NEW f2. . ENDAT.

AT END OF f2. . ENDAT.AT END OF f1. . ENDAT.

AT LAST. . ENDAT.ENDLOOP.

<Statements><Statements>

<Statements>

<Statements>

<Statements><Statements>

<Single entry processing>

TYPES:BEGIN OF line_type.f1, f2, f3.

END OF line_type.DATA: itab TYPE STANDARD TABLE

OF line_typeWITH KEY f1WITH HEADER LINE.

GET dbtab. APPEND dbtab TO itab.END-OF-SELECTION.SORT itab BY f1.LOOP AT itab.

FIELD-GROUPS: header, fg.

INSERT: f1 INTO header,f2, f3 INTO fg.

GET dbtab. EXTRACT fg.END-OF-SELECTION.SORT BY f1.LOOP.

Internal tableInternal table ExtractExtract

There are two steps in defining the record type of an extract dataset: Declare the required record type (FIELD-GROUPS).

The field group HEADER must be included. Above all, it must contain all of the fields by which you may later want to sort.

Assign the required fields to the field groups (INSERT … INTO… ). In the EXTRACT satement, the fields of the header and those of the relevant field group are

supplied with values from the relevant work areas. The field group HEADER and the one specified in the EXTRACT statement are written to the EXTRACT dataset as a record.

If you process an internal table or extract dataset using the LOOP statement, you can use the AT FIRST, AT NEW, AT END OF, and AT LAST statements for control level processing. The statement blocks that follow each of these AT… statements must be concluded with an ENDAT statement. The processing blocks are called whenever the field <field> or a higher-level field in the hierarchy changes its contents. Note that AT FIRST, AT NEW, AT END OF, and AT LAST are control structures, and not events. This means that the sequence in which they occur is decisive for the program flow.

The extract dataset or internal table must be sorted by group criteria.

Page 306: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 12-4

© SAP AG

R

Internal Tables and Extracts (2)Internal tableInternal table ExtractExtract

☺ Several internal tables

☺ Control level sums at beginning of a control level (AT FIRST, AT NEW f)

☺ Many operations (insert, change, delete, single entry access,…)

☺ Changes possible at any time

Single line type per internal table

Line type is static

Control level processing only according to the sequence of fields in the table structure

SUM operation has high costs

Only one EXTRACT dataset

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

Few operations (only append, sort, and sequential processing)

Extract cannot be extended after SORT or LOOP

☺ More than one line type possible

☺ Line type is dynamic (INSERT is not a declarative statement)

☺ Control level processing according to the sort sequence (regardless of the sequence of fields in the header)

☺ (SUM(f)) optimized

There is only one extract dataset in each roll area. Extracts only allow control level processing at the end of a control level. The only operations allowed for extracts are append (EXTRACT), SORT, and sequential processing

(LOOP). After the first SORT or LOOP, you can no longer extend the extract with the EXTRACT statement. Operations such as insert and delete are not allowed.

Extracts allow you to use more than one record type (FIELD-GROUPS), whose fields can be defined dynamically (INSERT is not a declarative statement). Internal tables have a single line type, which you define statically.

The control level processing hierarchy for an internal table is the sequence in which the fields occur in the table definition. It is therefore static, and, in particular, depends on the criteria according to which the internal table has been sorted. All of the fields to the right of the field <field> are filled with '*' during AT … ENDAT processing. Control level processing for extracts does not depend on the field sequence, but is dynamic. This means that you can resort the dataset, after which a completely new control level processing is possible. The processing sequence corresponds to the sort key of the extract dataset, that is, the sequence of the fields from the field group HEADER according to which the extract was sorted.

The SUM function is optimized for extracts, but not for internal tables (see following pages).

Page 307: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 12-5

© SAP AG

R

Internal Tables and Extracts (3)Internal tableInternal table ExtractExtract

LOOP AT itab.AT END OF itab-carrid.SUM. WRITE itab-seatsmax.

ENDAT. AT LAST.SUM. WRITE itab-seatsmax.

ENDAT.ENDLOOP.

LOOP.AT END OF itab-carrid.WRITE SUM(itab-seatsmax).

ENDAT. AT LAST.WRITE SUM(itab-seatsmax).

ENDAT.ENDLOOP.

CARRID SEATSMAXAA 140

Internal table itab

Work area itab

LH 320

LH 270SQ 340

590LH *********

...

...

...

...

CARRID SEATSMAXAA 140

Extract

LH 320

LH 270SQ 340

...

...

...

...

590

SUM(itab-seatsmax)

With internal tables, you can use the SUM statement within an AT… ENDAT block to calculate a sum for the current control level or the total sum (in AT FIRST or AT LAST). The system calculates the sums of all fields with data types P, I, and F, and places them in the corresponding fields of the work area or header line.

With extracts, you can address the fields SUM(<numfield>) and CNT(<headerfield>) within the AT END OF … ENDAT and AT LAST … ENDAT processing blocks:

SUM(<numfield>) calculates the sum for each group. The required work fields are generated automatically, and initialized with zero each time the control level changes.

CNT(<headerfield>) increases by one each time the contents of the header field in question change. In control level processing, <header field> must come lower in the sort order than the field on which the control level processing is based.

With extracts, the compiler notes the combination of control levels and fields for which sums are required. The control level sums are calculated in the LOOP … ENDLOOP block. With internal tables, the control level sum is not calculated until the SUM statement. Consequently, the cost of control level sums with internal tables increases quadratically.

Page 308: BC411 - Advanced ABAP Programming

© SAP AG

R

Accessing Table Entries Directly (Release 4.5) Contents

Aim: To be able to access internal tables without copyingReading and writing table entries without copying to and from a work area

Means: ASSIGNING addition in READ and LOOP„ “INTO wa”” addition can usually be replaced with the ASSIGNING addition

LOOP AT itab ... ASSIGNING <fs> ...

Corresponds to a LOOP with READ ASSIGNING as its first statement

After the loop, the field symbol corresponds to the last line of the table

Control levels and LOOP ... ASSIGNING

No copying to output area

SUM not possible

Until now, access to internal tables has been by means of the header line or a work area (wa). This has always resulted in high copying costs, especially with deep structures (where a component of the line type is itself an internal table).

The ASSIGNING addition in the READ and LOOP statements allows you to access a table entry directly using a field symbol. There is an example of this on the next page, and a further example in the tips and tricks section of the runtime analysis transaction (SE30) under the entry “Filling nested internal tables”.

Note that the field symbol always works directly with the body of the table. You cannot change the key components of an internal table.

If you work without a work area or header line, there are no copying costs when you use control level processing. On the other hand, there is no area in which you can place the result of a SUM statement.

The LOOP AT <itab> … ASSIGNING statement is always quicker than LOOP AT <itab>… INTO <wa> for tables with more than 10 entries, regardless of the width of the table line.

Page 309: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 13-2

© SAP AG

R

Structure of Deep Tables

* Bottom-up algorithm* Entries: 50 (outer table)

10 (inner table)* Line width: 500 (outer)

4 (inner)

DO 50 TIMES.CLEAR wa.DO 10 TIMES.

APPEND n TO wa-inttab.ADD 1 TO n.

ENDDO.APPEND wa TO itab.

ENDDO.

* Top-down algorithm* Entries: 50 (outer table)

10 (inner table)* Line width: 500 (outer)

4 (inner)

DO 50 TIMES.APPEND INITIAL LINE TO itab.ENDDO.

LOOP AT itab ASSIGNING <fs>.DO 10 TIMES.

APPEND n TO <fs>-inttab.ADD 1 TO n.

ENDDO.ENDLOOP.

The ASSIGNING variant now makes it possible to fill an internal table using the top-down strategy, that is, the outer table is filled, followed by the inner table.

The ASSIGNING variant is always quicker with deep tables, since there are no associated copying costs.

For a full example, refer to the demonstration program SAPBC411D_TESTFRAME_NESTED_TAB in development class SAPBC411.

Page 310: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 13-3

© SAP AG

R

Accessing Table Entries Directly (Release 4.5A)

Aim: To be able to access internal tabes without copyingReading and writing table entries without copying to and from a work area

Means: ASSIGNING addition in READ and LOOP“INTO wa” addition can usually be replaced with the ASSIGNING addition

LOOP AT itab ... ASSIGNING <fs> ...

Corresponds to a LOOP with READ ASSIGNING as its first statement

After the loop, the field symbol corresponds to the last line of the table

Control levels and LOOP ... ASSIGNING

No copying to output area

SUM not possible

Until now, access to internal tables has been by means of the header line or a work area (wa). This has always resulted in high copying costs, especially with deep structures (where a component of the line type is itself an internal table).

The ASSIGNING addition in the READ and LOOP statements allows you to access a table entry directly using a field symbol. There is an example of this on the next page, and a further example in the tips and tricks section of the runtime analysis transaction (SE30) under the entry “Filling nested internal tables”.

Note that the field symbol always works directly with the body of the table. You cannot change the key components of an internal table.

If you work without a work area or header line, there are no copying costs when you use control level processing. On the other hand, there is no area in which you can place the result of a SUM statement.

The LOOP AT <itab> … ASSIGNING statement is always quicker than LOOP AT <itab>… INTO <wa> for tables with more than 10 entries, regardless of the width of the table line.

Page 311: BC411 - Advanced ABAP Programming

© SAP AG

R

Further Information About ABAP Open SQL: Contents

The FOR ALL ENTRIES addition in the SELECT statement

Explicit cursors

Disjunctive normal form

The NOT operator

SELECT before changes

Restart logic

Page 312: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 14-2

© SAP AG

R

Rule 3: Minimize the Number of Transfers 1

FOR ALL ENTRIES IN

REPORT sapbc411d_select_view.SELECT * FROM sflight INTO TABLE sflight_itab.

SELECT carrid ...INTO CORRESPONDING FIELDS OF sbook FROM sbook

FOR ALL ENTRIES IN sflight_itabWHERE carrid = sflight_itab-carridAND connid = sflight_itab-connidAND fldate = sflight_itab-fldate.

WRITE: / ...ENDSELECT.

REPORT sapbc411d_select_view.SELECT * FROM sflight INTO TABLE sflight_itab.

SELECT carrid ...INTO CORRESPONDING FIELDS OF sbook FROM sbook

FOR ALL ENTRIES IN sflight_itabWHERE carrid = sflight_itab-carridAND connid = sflight_itab-connidAND fldate = sflight_itab-fldate.

WRITE: / ...ENDSELECT.

This example uses the Open SQL statement FOR ALL ENTRIES, which allows you to process a set of entries in the database. Unlike a nested SELECT statement, where the inner SELECT loop accesses the database entry by entry, FOR ALL ENTRIES uses an array fetch to read from the database for all of the entries in an internal table.

SELECT FOR ALL ENTRIES reads all of the database entries corresponding to the lines in an internal table using a single database access (or at most, a few).

The advantage of using SELECT FOR ALL ENTRIES is that only the relevant data is read, regardless of how selective the condition in the outer loop. This minimizes the amount of data transferred.

Page 313: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 14-3

© SAP AG

R

Rule 3: Minimize the Number of Transfers 2

Explicit cursor

REPORT sapbc411d_select_view....OPEN CURSOR c1 FOR SELECT * FROM sflight WHERE cond1 ORDER BY PRIMARY KEY.OPEN CURSOR c2 FOR SELECT * FROM sbook WHERE cond2 ORDER BY PRIMARY KEY.DO.

FETCH NEXT CURSOR c1 INTO sflight.IF sy-subrc <> 0. EXIT. ENDIF.IF sy-index = 1.

FETCH NEXT CURSOR c2 INTO sbook.ENDIF.WHILE sy-subrc = 0 AND sflight-carrid = sbook-carrid

AND ...... tue etwas...FETCH NEXT CURSOR c2 INTO sbook.

ENDWHILEIF sy-subrc <> 0. EXIT. ENDIF.

ENDDO. CLOSE CURSOR: c1, c2.

REPORT sapbc411d_select_view....OPEN CURSOR c1 FOR SELECT * FROM sflight WHERE cond1 ORDER BY PRIMARY KEY.OPEN CURSOR c2 FOR SELECT * FROM sbook WHERE cond2 ORDER BY PRIMARY KEY.DO.

FETCH NEXT CURSOR c1 INTO sflight.IF sy-subrc <> 0. EXIT. ENDIF.IF sy-index = 1.

FETCH NEXT CURSOR c2 INTO sbook.ENDIF.WHILE sy-subrc = 0 AND sflight-carrid = sbook-carrid

AND ...... tue etwas...FETCH NEXT CURSOR c2 INTO sbook.

ENDWHILEIF sy-subrc <> 0. EXIT. ENDIF.

ENDDO. CLOSE CURSOR: c1, c2.

OPEN CURSOR <cursor> FORSELECT * FROM <dbtab> WHERE <cond> ORDER BY PRIMARY KEY.

FETCH NEXT CURSOR <cursor> INTO <dbtab>.

OPEN CURSOR <cursor> FORSELECT * FROM <dbtab> WHERE <cond> ORDER BY PRIMARY KEY.

FETCH NEXT CURSOR <cursor> INTO <dbtab>.

The OPEN CURSOR statement allows you to open a cursor in any of the relevant tables, which you can then process in parallel.

The advantage of this is that only one cursor is opened for the inner table, and not every fetch for that cursor results in an access to the inner table (the database interface reads several entries at once by array fetch and buffers them).

Furthermore, this method allows you to determine the access path yourself.

Page 314: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 14-4

© SAP AG

R

Rule 4: Minimize the Search Overhead

Use the disjunctive normal form (DNF)(F0 = x1 and F1 = y1 and F2 = z1)

OR (F0 = x2 and F1 = y2 and F2 = z2)OR (F0 = x3 and F1 = y3 and F2 = z3)OR (F0 = x4 and F1 = y4 and F2 = z4)OR (F0 = x5 and F1 = y5 and F2 = z5)

General rule

SELECT * FROM sflight WHERE carrid = 'LH' AND ( connid = '0400' OR

fldate = '19981129' ) ENDSELECT.

SELECT * FROM sflight WHERE carrid = 'LH' AND ( connid = '0400' OR

fldate = '19981129' ) ENDSELECT.

SELECT * FROM sflight WHERE ( carrid = 'LH' AND connid = '0400' )

OR ( carrid = 'LH' AND fldate = '19981129' )ENDSELECT.

SELECT * FROM sflight WHERE ( carrid = 'LH' AND connid = '0400' )

OR ( carrid = 'LH' AND fldate = '19981129' )ENDSELECT.

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

Page 315: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 14-5

© SAP AG

R

Rule 4: Minimize the Search Overhead

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

... Processing ...ENDSELECT.

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

... Processing ...ENDSELECT.

No index supportBut: Rule 1 still applies!

Caution when using the NOT operator

SELECT * FROM sbook WHERE carrid = 'LH' AND cancelled NE 'X'

... Processing ...ENDSELECT.

SELECT * FROM sbook WHERE carrid = 'LH' AND cancelled NE 'X'

... Processing ...ENDSELECT.

If you use the NOT operator, the database cannot use an index. However, using it can still prevent unnecessary data being transferred between the database and the application server (see rule 1).

It is sometimes possible to reformulate an expression to avoid the NOT operator. In the above example, you could write: SELECT ... WHERE carrid = 'LH' AND cancelled NE '0000000006'.

Page 316: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 14-6

© SAP AG

R

SELECT before changes

SELECT * FROM dbtab WHERE ...IF sy-subrc = 0.

UPDATE dbtab ...ELSE.

INSERT dbtab ...ENDIF.

SELECT * FROM dbtab WHERE ...IF sy-subrc = 0.

UPDATE dbtab ...ELSE.

INSERT dbtab ...ENDIF.

INSERT dbtab ...IF sy-subrc <> 0.

UPDATE ...ENDIF.

INSERT dbtab ...IF sy-subrc <> 0.

UPDATE ...ENDIF.

Instead, useInstead, use

Rule 5: Reduce the Database Load 1

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

Page 317: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 14-7

© SAP AG

R

Rule 5: Reduce the Database Load

Frequent way of processing large amounts of datastart = space.DO.

SELECT * UP TO 1000 ROWS FROM t1WHERE key > startORDER BY PRIMARY KEY.... Process entry from t1(--> insert, update, delete)

ENDSELECT.IF sy-subrc = 0.

COMMIT WORK.start = t1-key.

ELSE. EXIT. ENDIF.ENDDO.

Frequent way of processing large amounts of datastart = space.DO.

SELECT * UP TO 1000 ROWS FROM t1WHERE key > startORDER BY PRIMARY KEY.... Process entry from t1(--> insert, update, delete)

ENDSELECT.IF sy-subrc = 0.

COMMIT WORK.start = t1-key.

ELSE. EXIT. ENDIF.ENDDO.

Restart logic

Verwenden Sie besser:OPEN CURSOR ... WITH HOLD ... FOR

SELECT * FROM ...

Verwenden Sie besser:OPEN CURSOR ... WITH HOLD ... FOR

SELECT * FROM ...

Instead, useInstead, use

Why partition processing? To allow a commit, 1.) To avoid the Oracle error '1555 Snapshot too old' 2.) To avoid timeouts due to long runtime 3.) To allow you to process large datasets 4.)To avoid long runtime

You can avoid the first error by using the statement OPEN CURSOR … WITH HOLD, although this only works if you perform a full table scan and have a commit after each n database entries.

You can only solve the problem of long runtimes by using COMMIT WORK. This resets the time slice.

If the available memory is too small for the amount of data you want to process, you can use the PACKAGE SIZE n addition in the SELECT statement to read it in suitably-sized packets.

Page 318: BC411 - Advanced ABAP Programming

© SAP AG

R

Further Information About Modularization Units: Contents

Comparison criteria

Page 319: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-2

© SAP AG

R

Position in Elementary Modularization UnitsPosition in Elementary Modularization Units

SubroutineSubroutine

Function moduleFunction module

ScreenScreen

ModuleModule

EventEvent

InterfaceInterface

Position in Memory ModelPosition in Memory Model

Data typesData types

Parameter specificationParameter specification

ChecksChecks

Default valuesDefault values

Changes to interfaceChanges to interface

Passing methodPassing method

Comparison Criteria I

Method Method

In fitting the modularization units into the memory model, the following questions arise: What does the modularization unit do? What, if anything, is created when you call the modularization unit? Which data areas, if any, are shared with other programs?

Modularization units allow you to specify a data type when you declare them. Parameter assignment can depend either on their position or on a keyword. You can pass parameters by value, by value and return, or by address. Parameters for which you define default values in the interface or program are optional. You can

also define optional parameters without default values. If your modularization unit has optional parameters, you do not need to adjust all of its calls when

you change the interface.

Page 320: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-3

© SAP AG

R

Comparison Criteria II

Shared data areasShared data areas

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

Local memoryLocal memory

DialogsDialogs

CallsCalls

Calling unitCalling unit

Call typeCall type

Cost* Runtime* Memory occupied

Cost* Runtime* Memory occupied

There are two kinds of shared data area - those that arise automatically, and those that have to be declared explicitly (COMMON).

The Data passed (other than interface) field is only filled where a particular type is typical for a modulariaztion unit. The global ABAP memory can be used for practically all units, but is only really appropriate for a few.

A local memory can be used for a series of calls to the same modularization unit, or for calls to units in a single group (for example, a function group).

The calling unit category (for example, in CALL SCREEN), shows the program to which the screen is assigned. The screen modules must be stored in this program.

When you call a modularization unit with its own dialogs (for example, transactions), you can specify values for the screen fields. The screens can then be processed without being displayed.

When examining the costs of a modularization unit, you must regard the runtime in the context of the type of memory occupation (for example, new roll area).

Page 321: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-4

© SAP AG

R

Comparison Criteria III

Administration FunctionAdministration Function

DocumentationDocumentation

CatalogCatalog

Directory of calling programsDirectory of calling programs

Test frameworkTest framework

Reusability / UseReusability / Use

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

program. The reusability section describes how a modularization unit can be used.

Page 322: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-5

© SAP AG

R

Internal Subroutine I

InterfaceInterface

Passing methods ValueValue and returnAddress

Checks Type check where types specified

Parameter specification Position in call

Data types All data types

Default values No

Changes to interface Calls need to be updated

Passing methods ValueValue and returnAddress

Checks Type check where types specified

Parameter specification Position in call

Data types All data types

Default values No

Changes to interface Calls need to be updated

Part of a main program (main or additional program group)Main program and subroutines have common data areas

Part of a main program (main or additional program group)Main program and subroutines have common data areas

Position in memory modelPosition in memory model

SubroutineSubroutine

Position in elementary modularization unitsPosition in elementary modularization units

Internal subroutines are called within the same main program. When you pass a data type, the actual parameter is used in place of the formal parameter. The

system checks whether the type of the actual parameter is compatible with that of the formal parameter (refer to the Types unit).

Page 323: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-6

© SAP AG

R

Internal Subroutine II

Calling unit ProgramCall type Static or dynamicCost/runtime Factor 1 (depends on number of parameters)Memory occupied Main program

Calling unit ProgramCall type Static or dynamicCost/runtime Factor 1 (depends on number of parameters)Memory occupied Main program

CallCall

DialogsDialogs

Possibly selected fields from the main programPossibly selected fields from the main programLocal memoryLocal memory

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

Global data of main programGlobal data of main program

Shared data areasShared data areas

Own dialogs Screens always belong to main program of the program group

User interface/Input possibilities

Own dialogs Screens always belong to main program of the program group

User interface/Input possibilities

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

Page 324: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-7

© SAP AG

R

Internal Subroutine III

Program structure

Repeatedly-used statements (local)

Program structure

Repeatedly-used statements (local)

Reusablilty / UseReusablilty / Use

Administration FunctionsAdministration Functions

Documentation Main program

Catalog Yes

Directory of calling programs

Test framework No

Documentation Main program

Catalog Yes

Directory of calling programs

Test framework No

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

Page 325: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-8

© SAP AG

R

External Subroutine I

InterfaceInterfacePassing methods Value

Value and returnAddress

Checks Type check where types specified

Parameter specification Position in call

Data types All data types

Default values No

Changes to interface Calls need to be updated

Passing methods ValueValue and returnAddress

Checks Type check where types specified

Parameter specification Position in call

Data types All data types

Default values No

Changes to interface Calls need to be updated

SubroutineSubroutine

Position in elementary modularization unitsPosition in elementary modularization units

Position in memory modelPosition in memory model

Part of a main program (main or additional program)Call may load a new programPrograms in a program group have shared data andtable work areas

Part of a main program (main or additional program)Call may load a new programPrograms in a program group have shared data andtable work areas

External subroutines are called from another main program. When you pass data types, the actual parameter must be fully compatible with the formal parameter.

If you do not pass a type, the actual parameter must be at least as long as the formal parameter.

Page 326: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-9

© SAP AG

R

External Subroutine II

Calling unit ProgramCall type Static or dynamicCost/runtime Factor 6, a new program may be loaded whenMemory occupied the routine is called

Calling unit ProgramCall type Static or dynamicCost/runtime Factor 6, a new program may be loaded whenMemory occupied the routine is called

CallCall

Yes - global data of the main programYes - global data of the main programLocal memoryLocal memory

Table work areasCOMMON areasGlobal data of the main program

Table work areasCOMMON areasGlobal data of the main program

Shared data areasShared data areas

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

DialogsDialogs

Own dialogs No - screens belong to the main programof the program group

User interface/Input possibilities

Own dialogs No - screens belong to the main programof the program group

User interface/Input possibilities

Table work areas are automatically shared between the calling and called programs. You can also create common data areas using the DATA statement.

The costs of running an external subroutine from a subroutine pool are higher for the first call than for subsequent calls. In the first call, the entire program has to be loaded.

Page 327: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-10

© SAP AG

R

External Subroutine III

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

Reusability / UseReusability / Use

Administration functionsAdministration functions

Documentation Subroutine pool

Catalog No

Directory of Repository Infosystem,Calling programs Where-used list

Test framework No

Documentation Subroutine pool

Catalog No

Directory of Repository Infosystem,Calling programs Where-used list

Test framework No

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

Page 328: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-11

© SAP AG

R

Function Module I

InterfaceInterfacePassing methods Value/address (IMPORTING)

Value/address (EXPORTING)Value/address (CHANGING)Address (TABLES)

Checks Type checks (reference fields)Length checks (ref. fields/structures)

Parameter specification Keyword-oriented

Data types All data types

Default values Yes

Changes to interface May require changes to calls

Passing methods Value/address (IMPORTING)Value/address (EXPORTING)Value/address (CHANGING)Address (TABLES)

Checks Type checks (reference fields)Length checks (ref. fields/structures)

Parameter specification Keyword-oriented

Data types All data types

Default values Yes

Changes to interface May require changes to calls

Function moduleFunction module

Position in elementary modularization unitsPosition in elementary modularization units

Position in memory modelPosition in memory model

Part of a main program (function group)Call may generate a new program groupProgram groups share an internal session

Part of a main program (function group)Call may generate a new program groupProgram groups share an internal session

You can specify whether the EXPORTING, IMPORTING, and CHANGING parameters should be passed by value or reference.

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

Page 329: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-12

© SAP AG

R

Function Module II

Calling unit ProgramCall type Dynamic, usually by specifying a literalCost/runtime Factor 12, a new program may be loaded memory occupied when the function is called

Calling unit ProgramCall type Dynamic, usually by specifying a literalCost/runtime Factor 12, a new program may be loaded memory occupied when the function is called

CallCall

Yes - global data in the function groupYes - global data in the function groupLocal memoryLocal memory

Output listOutput listShared data areasShared data areas

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

DialogsDialogs

Own dialogs Yes. Screens belong to the main program(function group) of the program group

User interface/Input possibilities

Own dialogs Yes. Screens belong to the main program(function group) of the program group

User interface/Input possibilities

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

Page 330: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-13

© SAP AG

R

Function Module III

Administration functionAdministration function

Documentation Yes

Catalog Yes

Directory of Repository Infosystem,calling programs Where-used list in

Function Builder

Test framework Yes

Documentation Yes

Catalog Yes

Directory of Repository Infosystem,calling programs Where-used list in

Function Builder

Test framework Yes

Application-specific or cross-application Advantages: - Administration functions

- Exception handling

Application-specific or cross-application Advantages: - Administration functions

- Exception handling

Reusability / UseReusability / Use

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

Page 331: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-14

© SAP AG

R

Screen, CALL SCREEN, CALL SELECTION-SCREEN I

InterfaceInterface

Passing methods Input/output fields, automatic fieldtransport where screen fields andABAP fields have the same names

Checks

Parameter specification

Data types

Default values

Changes to interface

Passing methods Input/output fields, automatic fieldtransport where screen fields andABAP fields have the same names

Checks

Parameter specification

Data types

Default values

Changes to interface

Screens always belong to the main program of thecurrent program groupThe called screen is loaded into the current roll area

Screens always belong to the main program of thecurrent program groupThe called screen is loaded into the current roll area

Position in memory modelPosition in memory model

ScreenScreen

Position in elementary modularization unitsPosition in elementary modularization units

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

Page 332: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-15

© SAP AG

R

Screen, CALL SCREEN, CALL SELECTION-SCREEN II

Calling unit ProgramCall type Static or dynamicCost/runtime 148Memory occupied Loaded into roll area

Calling unit ProgramCall type Static or dynamicCost/runtime 148Memory occupied Loaded into roll area

CallCall

Yes - global data of the ABAP programYes - global data of the ABAP programLocal memoryLocal memory

Global data of the ABAP programGlobal data of the ABAP program

Shared data areasShared data areas

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

DialogsDialogs

Own dialogs

User interface/input possibilities

Own dialogs

User interface/input possibilities

SPA/GPA memorySPA/GPA memory

The called screen is loaded into the current roll area.

Page 333: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-16

© SAP AG

R

Screen, CALL SCREEN, CALL SELECTION-SCREEN III

Administration functionsAdministration functions

Documentation Screen documentation

Catalog Screen Painter

Directory of calling programs No

Test framework Yes

Documentation Screen documentation

Catalog Screen Painter

Directory of calling programs No

Test framework Yes

Local screen chain

Dialog box on a screen

Customer modifications (Adding extra fields)

Dialogs from function modules

Local screen chain

Dialog box on a screen

Customer modifications (Adding extra fields)

Dialogs from function modules

Reusability / UseReusability / Use

The called screen is loaded into the current roll area.

Page 334: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-17

© SAP AG

R

Module I

Position in the memory modelPosition in the memory model

Modules are part of the main programMain program and modules have shared data areaModules are part of the main programMain program and modules have shared data area

ModuleModule

Position in elementary modularization unitsPosition in elementary modularization units

InterfaceInterface

Passing methods Automatic field transport betweenscreen and ABAP fields with the same names

Checks

Parameter specification

Data types

Default values

Changes to interface

Passing methods Automatic field transport betweenscreen and ABAP fields with the same names

Checks

Parameter specification

Data types

Default values

Changes to interface

You call modules from the flow logic of a screen.

Page 335: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-18

© SAP AG

R

Module II

Calling unit ScreenCall type StaticCost/runtimeMemory occupied Main program

Calling unit ScreenCall type StaticCost/runtimeMemory occupied Main program

CallCall

Yes - possibly selected fields of main programYes - possibly selected fields of main programLocal memoryLocal memory

Yes - global data of the main programYes - global data of the main program

Shared data areasShared data areas

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

DialogsDialogs

Own dialogs

User interface/Input possibilities

Own dialogs

User interface/Input possibilities

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

Page 336: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-19

© SAP AG

R

Module III

Within a module pool

Can be called from any screen

Within a module pool

Can be called from any screen

Reusability / UseReusability / Use

Administration functionsAdministration functions

Documentation Main program (module pool)

Catalog No

Directory of Repository Infosystem,calling programs Where-used list in

Repository BrowserTest framework No

Documentation Main program (module pool)

Catalog No

Directory of Repository Infosystem,calling programs Where-used list in

Repository BrowserTest framework No

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

Page 337: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-20

© SAP AG

R

Event I

Position in the memory modelPosition in the memory model

Events always belong to the main program of an activeprogram group The main program and the events have a shared dataarea

Events always belong to the main program of an activeprogram group The main program and the events have a shared dataarea

EventEvent

Position in elementary modularization unitsPosition in elementary modularization units

InterfaceInterface

Passing methods

Checks

Parameter specification

Data types

Default values

Changes to interface

Passing methods

Checks

Parameter specification

Data types

Default values

Changes to interface

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

Page 338: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-21

© SAP AG

R

Event II

Yes - possibly selected fields of the main programYes - possibly selected fields of the main programLocal memoryLocal memory

Yes - global data of the main programYes - global data of the main program

Shared data areasShared data areas

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

DialogsDialogs

Own dialogs

User interface/Input possibilities

Own dialogs

User interface/Input possibilities

Calling unit ABAP runtime systemCall typeCost/runtimeMemory occupied Main program

Calling unit ABAP runtime systemCall typeCost/runtimeMemory occupied Main program

CallCall

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

Page 339: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-22

© SAP AG

R

Event III

Logical databases

Interactive programming

Page layout

Logical databases

Interactive programming

Page layout

Reusability / UseReusability / Use

Administration functionsAdministration functions

Documentation Main program

Catalog No

Directory of Where-used list in calling programs Repository Browser

Test framework No

Documentation Main program

Catalog No

Directory of Where-used list in calling programs Repository Browser

Test framework No

Page 340: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-23

© SAP AG

R

Dialog Module I

Screen - program - moduleScreen - program - module

Position in elementary modularization unitsPosition in elementary modularization units

Position in memory modulePosition in memory module

Standalone programCall creates a new internal sessionSeveral internal sessions share one external session withone shared ABAP memory

Standalone programCall creates a new internal sessionSeveral internal sessions share one external session withone shared ABAP memory

InterfaceInterface

Passing methods Name-oriented, value of SY-SUBRC passed automatically

Checks NoneParameter specification EXPORTING/IMPORTING/USING itab

Data types All data types except object references

Default values NoChanges to interface Some adjustment of calls required

Passing methods Name-oriented, value of SY-SUBRC passed automatically

Checks NoneParameter specification EXPORTING/IMPORTING/USING itab

Data types All data types except object references

Default values NoChanges to interface Some adjustment of calls required

When you call a dialog module, the system opens a new internal session (roll area). A dialog module consists of a module pool and its associated screnes. The name of the module pool and the number of the initial screen are stored in table TDCT.

When you call the dialog module, you name the objects that you want to pass to it (EXPORTING) and the objects that you want the dialog module to return (IMPORTING). Data is transferred by the ABAP runtime system using global ABAP memory. The data transfer is fieldname-oriented.

Since CALL DIALOG opens a new internal session, you cannot pass references. References can only point to data objects in the same roll area.

Page 341: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-24

© SAP AG

R

Dialog Module II

Calling program ProgramCall type Dynamic, usually as a literalCost/runtime Factor 8000Memory occupied Own roll area

Calling program ProgramCall type Dynamic, usually as a literalCost/runtime Factor 8000Memory occupied Own roll area

CallCall

NoNoLocal memoryLocal memory

NoNo

Shared data areasShared data areas

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

SPA/GPA memoryGlobal ABAP memorySPA/GPA memoryGlobal ABAP memory

DialogsDialogs

Own dialogs Yes

User interface/ USING <tab>Input possibilities

Own dialogs Yes

User interface/ USING <tab>Input possibilities

As well as specifying the data objects that you want to transfer when you call the dialog module, you can also pass data between the calling program and the module using SPA/GPA memory or ABAP memory.

The USING <tab> parameter allows you to pass an internal table containing input values for screen fields.

Since data is always passed to and from dialog modules by value, calling a dialog module can be very expensive if you need to pass large table work areas or internal tables.

You can use the global ABAP memory as a local memory.

Page 342: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-25

© SAP AG

R

Dialog Module III

Administration FunctionsAdministration Functions

Documentation Program documentation

Catalog Table TDCT Repository Infosystem

Directory of Where-used list calling programs in Repository Browser

Test framework No

Documentation Program documentation

Catalog Table TDCT Repository Infosystem

Directory of Where-used list calling programs in Repository Browser

Test framework No

Reusable subdialogs

Rarely-used functions removed to their own roll areaLarge amounts of memory must be available temporarily (internal tables)Call can be expensive (passing internal tables)

Reusable subdialogs

Rarely-used functions removed to their own roll areaLarge amounts of memory must be available temporarily (internal tables)Call can be expensive (passing internal tables)

Reusability / UseReusability / Use

Table TDCT contains a list of all dialog modules.

Page 343: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-26

© SAP AG

R

Transaction I

Screen - program - moduleScreen - program - module

Position in elementary modularization unitsPosition in elementary modularization units

Position in the memory modelPosition in the memory model

Standalone programCall creates a new internal sessionSeveral internal sessions share one external session

Standalone programCall creates a new internal sessionSeveral internal sessions share one external session

InterfaceInterface

Passing methods

Checks

Parameter specification

Data types

Default valuesChanges to interface Requires some changes to calls

Passing methods

Checks

Parameter specification

Data types

Default valuesChanges to interface Requires some changes to calls

When you call a transaction using CALL TRANSACTION, the system opens a new internal session (roll area). If you have an internal session n where n >= 0, LEAVE TO TRANSACTION closes all open internal sessions 0 … n and runs the new transaction in session 0.

Each transaction is assigned to a module pool with screens. The difference between transactions and dialog modules is in the call. Transations can be called directly by the user as well as from a program (CALL mode). Dialog modules, on the other hand, can only be called from a program. The system field SY-CALLD indicates whether a program has been activated in CALL mode.

The interface of a transaction is made up of the input/output fields of its screens.

Page 344: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-27

© SAP AG

R

Transaction II

NoNoLocal memoryLocal memory

NoNo

Shared data areasShared data areas

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

SPA/GPA memoryGlobal ABAP memorySPA/GPA memoryGlobal ABAP memory

Calling unit ProgramCall type DynamicCost/runtime 8000Memory occupied Own roll area

Calling unit ProgramCall type DynamicCost/runtime 8000Memory occupied Own roll area

CallCall

DialogsDialogs

Own dialogs YesUser interfaces/ a) SPA/GPA values and

AND SKIP FIRST SCREEN additionInput possibilities b) USING <tab>

Own dialogs YesUser interfaces/ a) SPA/GPA values and

AND SKIP FIRST SCREEN additionInput possibilities b) USING <tab>

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

Page 345: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-28

© SAP AG

R

Transaction III

Administration functionsAdministration functions

Documentation Transaction documentation

Catalog Table TSTC, Repository Infosystem

Directory of Where-used list in calling programs Repository Browser

Test framework No

Documentation Transaction documentation

Catalog Table TSTC, Repository Infosystem

Directory of Where-used list in calling programs Repository Browser

Test framework No

Uses an existing transaction

Customer modifications, simple variants, call original transaction

Uses an existing transaction

Customer modifications, simple variants, call original transaction

Reusability / UseReusability / Use

Table TSTC contains all transactions.

Page 346: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-29

© SAP AG

R

Program, SUBMIT I

Selection screen - program- event Selection screen - program- event

Position in elementary modularization unitsPosition in elementary modularization units

Position in memory modelPosition in memory model

Standalone programCall generates a new internal sessionSeveral internal sessions share an external session withshared ABAP memory

Standalone programCall generates a new internal sessionSeveral internal sessions share an external session withshared ABAP memory

InterfaceInterfacePassing methods Value (for selection screen

fields)

Checks Selection screen

Parameter specification Keyword-oriented

Data types Selection tables, single values

Default values Yes - report

Changes to interface Some changes to calls required

Passing methods Value (for selection screen fields)

Checks Selection screen

Parameter specification Keyword-oriented

Data types Selection tables, single values

Default values Yes - report

Changes to interface Some changes to calls required

When you start a report using the SUBMIT AND RETURN statement, the system opens a new internal session (roll area). When the program ends, the new session n+1 is closed and the system carries on processing in session n-1 (as long as n > 0). If you use SUBMIT without RETURN, the existing session containing the calling program is replaced by a new internal session in which the new report is then run.

The interface of the program consists of the selection screen fields. These can be selection tables or single values, which you can pass in the WITH addition.

Unlike other modularization units, the report that you call cannot pass values back to the calling program.

Page 347: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-30

© SAP AG

R

Program, SUBMIT II

NoNoLocal memoryLocal memory

NoNo

Shared data areasShared data areas

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

SPA/GPA memoryGlobal ABAP memorySPA/GPA memoryGlobal ABAP memory

Calling unit ProgramCall type Static or dynamicCost/runtime 10 000Memory occupied Own roll area

Calling unit ProgramCall type Static or dynamicCost/runtime 10 000Memory occupied Own roll area

CallCall

DialogsDialogs

Own dialogs YesUser interface/ Filling the selection screen

Input possibilities

Own dialogs YesUser interface/ Filling the selection screen

Input possibilities

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

Page 348: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-31

© SAP AG

R

Program, SUBMIT III

Administration functionsAdministration functions

Documentation Program documentation

Catalog ABAP development

Directory of ABAP Dictionarycalling programs Repository Information System

Test framework No

Documentation Program documentation

Catalog ABAP development

Directory of ABAP Dictionarycalling programs Repository Information System

Test framework No

Uses an existing report

Enables you to keep display functions (interactive program)in a separate program

Uses an existing report

Enables you to keep display functions (interactive program)in a separate program

Reusability / UseReusability / Use

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

Page 349: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-32

© SAP AG

R

LEAVE TO LIST PROCESSING I

InterfaceInterface

Passing methods

Checks

Parameter specification

Data structures

Default values

Changes to interface

Passing methods

Checks

Parameter specification

Data structures

Default values

Changes to interface

List screen - eventsList screen - events

Position in elementary modularization unitsPosition in elementary modularization units

Position in the memory modelPosition in the memory model

List always belong to the main program of the main program groupEvents are part of the main programPart of a program

List always belong to the main program of the main program groupEvents are part of the main programPart of a program

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

Page 350: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-33

© SAP AG

R

LEAVE TO LIST PROCESSING II

Global program dataGlobal program data

Shared data areasShared data areas

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

Calling unit Program (module)Call typeCost/runtime Factor 2Memory occupied Part of program

Calling unit Program (module)Call typeCost/runtime Factor 2Memory occupied Part of program

CallCall

Local memoryLocal memory

DialogsDialogs

Own dialogsUser interface/

Input possibilities

Own dialogsUser interface/

Input possibilities

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

Page 351: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 15-34

© SAP AG

R

LEAVE TO LIST PROCESSING III

Display functions are implemented within the module poolDisplay functions are implemented within the module pool

Reusability / UseReusability / Use

Administration functionAdministration function

Documentation

Catalog

Directory ofcalling programs

Test framework

Documentation

Catalog

Directory ofcalling programs

Test framework

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

Page 352: BC411 - Advanced ABAP Programming

© SAP AG

R

String Processing: Contents

String comparisons

String operations

Page 353: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-2

© SAP AG

R

Unit Objectives

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

List the string comparisons supported in ABAP

Use string operations

Page 354: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-3

© SAP AG

R

String ProcessingA B

REPLACE

TRANSLATE

SHIFT

CONDENSE

A B A P

A B+A

A B A

A B A

A B A

A B A

a b a

ASEARCH

CONCATENATE

OVERLAY

SPLIT

sysy--subrcsubrc sysy--fdposfdpos g/kg/k

A B

A A A A A B A PA B P

String processing in ABAP uses the following statements: SEARCH Search in a string REPLACE Replace the first occurrence of a string TRANSLATE Replace all characters SHIFT Shift a string by one place CONDENSE Remove spaces CONCATENATE Join a sequence of strings OVERLAY Overlay two strings SPLIT Split a string In all string operations, the operands are treated like type C fields, regardless of their actual field type. They are not converted.

The following string processing statements set the system field SY-SUBRC: SEARCH, REPLACE, SHIFT <string1> UP TO <string2>, CONCATENATE, OVERLAY, SPLIT. SEARCH also sets the system field SY-FDPOS (offset of the found string).

Apart from SEARCH, all string processing statements differentiate between upper- and lowercase. The standard function STRLEN returns the occupied length of a string.

Page 355: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-4

© SAP AG

R

Searching in a StringSEARCH <f> FOR <searchstring>.SEARCH <itab> FOR <searchstring>.

REPORT sapbc411d_string_processing.

DATA: string(100) TYPE cVALUE 'Abap object '.

SEARCH string FOR 'X'.SEARCH string FOR 'ObjecT'.SEARCH string FOR '. .'.SEARCH string FOR 'OBj*'.SEARCH string FOR '*ect'.

System field:Sy-fdpos:

A b a p o b e c tj

0 1 2 3 4 5 6 7 8 9 10 11

The system searches the field <f> for the string <searchstring>. <searchstring> can be one of the following: 'string' A string (trailing spaces are ignored) '.str.' Any characters between the periods (spaces included in the search) '*str' A word ending in ‘str’, including ‘str’ itself 'str*' A word beginning with ‘str’, including ‘str’ itself

The offset of the found string is placed in the system field SY-FDPOS. If the search string is not found, SY-FDPOS contains the value 0.

You can use SEARCH <itab> as well as SEARCH <f>. The system then searches for the search string within the internal table <itab>. This variant sets SY-TABIX with the line index of the line containing the search string, as well as SY-SUBRC and SY-FDPOS.

Page 356: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-5

© SAP AG

R

Manipulating Strings

B b B p +

B b A p +

A B A P +

REPLACE 'A' WITH 'B' INTO <f>.

TRANSLATE <f> USING 'AB'.

TRANSLATE <f> TO CASE.

A b A p +

A b A p +

A b A p +CONDENSE <f> [NO-GAPS].

A b A p +

A b A p +

b A p +SHIFT <f> [BY <n> PLACES] [mode].

A b A p +

UPPERLOWER

REPLACE <string1> WITH <string2> INTO <f>. The first occurrence of <string1> in <f> is replaced by <string2>. In other words, <f> is both the source and target field.

TRANSLATE <f> USING <string>. All letters in <f> are replaced according to <string>. <string> contains the search and replacement characters in pairs. In the above example, each occurrence of ‘A’ in <f> is replaced with ‘B’.

TRANSLATE <f> TO UPPER | LOWER CASE. All lowercase letters in <f> are converted to uppercase (or all uppercase letters are converted to lowercase).

SHIFT <f>.[BY <n> PLACES] [mode]. <f> is shifted one position to the left. The first letter is no longer displayed, and a trailing space appears at the right-hand end. SHIFT <f> has the following additions: ... RIGHT. Shifts <f> one position to the right. ... CIRCULAR. Shifts <f> cyclically to the left, that is, the outermost character on the left-hand side is moved to the right hand end. ... RIGHT CIRCULAR. Shifts <f> cyclically to the right.

CONDENSE <f> Series of spaces are replaced with a single space. If you use the NO-GAPS addition, all spaces are deleted. Note: You can delete leading and trailing spaces using SHIFT <f> LEFT DELETING TRAILING SPACE or SHIFT <f> RIGHT DELETING TRAILING SPACE.

Page 357: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-6

© SAP AG

R

Joining and Splitting StringsA P

CONCATENATE <f1> ... <fn> INTO <f>[... SEPARATED BY <seperator>].

A B

OVERLAY <f1> WITH <f2>.

SPLIT <f> AT <separator> INTO <f1> ... <fn>.TABLE <itab>.

A B A P

X B A X

A B A P

A B A P

A B A P

A P

+

CONCATENATE <f1> ... <fn> INTO <f> [SEPARATED BY <separator>]. The fields <f1> … <fn> are joined together and placed in <f>. Trailing spaces are ignored in the component fields. You can use the SEPARATED BY <separator> addition to separate <f1> … <fn> by the contents of <separator>.

OVERLAY <f1> WITH <f2>. <f2> overlays <f1> at all positions where <f2> contains the value SPACE. <f2> remains unchanged.

SPLIT <f> AT <separator> INTO <f1> ... <fn> | INTO TABLE <itab>. <f> is split wherever <separator> occurs, and placed in the fields <f1> … <fn> or into the lines of an internal table <itab>.

Page 358: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-7

© SAP AG

R

String Comparisons

CA

CS

CP

CO

U/LU/L BlanksBlanks

REPORT sapbc411d_string_processing.

DATA: string(100) TYPE c VALUE 'Abap Object '.

IF string CO 'Objetc Abap'. "trueIF string CO 'ABAP '. "falseIF string CO 'ie'. "false

IF string CA 'ie'. "trueIF string CA 'o'. "false

IF string CS 'ej '. "falseIF string CS 'je'. "true

IF string CP '*b*'. "trueIF string CP '+b#*'. "falseIF string CP 'A+AP# *'. "true

The above table shows the cases in which upper- and lowercase and the full length of the left-hand operand are considered in a comparison.

Each of the operators above has a corresponding negation. These are, in pairs: CO/CN, CA/NA, CS/NS, CP/NP.

In the logical expression <string1> operator <string2>, the operators have the following meanings: CO: 'Contains Only' <string1> only contains characters from <string2>. CN: 'Contains Not Only' <string1> does not contain characters from <string2>. It is equivalent to NOT <string1> CO <string2> CA: 'Contains Any' <string1> contains at least one character from <string2> NA: 'Contains Not Any' <string1> contains no characters from <string2> CS: 'Contains String' <string1> contains the string <string2> NS: 'Contains Not String' <string1> does not contain the string <string2> CP: 'Contains Pattern' <string1> contains the pattern <string2> NP: 'Contains Not Pattern' <string1> does not contain the pattern <string2>

The system field sy-fdpos contains the offset of the character that satisfies the condition, or the length of <string1>.

For further details, refer to the online documentation in the ABAP Editor for the relevant statement.

Page 359: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 16-8

© SAP AG

R

Summary

You can process strings using the following statements:

SEARCHREPLACE TRANSLATESHIFT CONDENSE CONCATENATEOVERLAY SPLIT

Page 360: BC411 - Advanced ABAP Programming

© SAP AG

R

Bit Processing: Contents

Sets as bit patterns

SET BIT/GET BIT

Assigning values to type X fields

Bit calculations

Bit comparisons

Page 361: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-2

© SAP AG

R

Unit Objectives

to write programs that

Use a data object with type X to represent a set of n elements

Set and read bits within type X data objects

Perform bit calculations using BIT-NOT, BIT-AND, BIT-OR, and BIT-XOR

Compare a field of any type with a type X field using the O, Z, and M operators

At the end of this unit, you will be able

Page 362: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-3

© SAP AG

R

Sets as Bit Patterns

Monday Tuesday WednesdayThursday Friday Saturday Sunday

00 11 00 00 00 00 11

Type XType Xwith length ‘smallest number >= (n/8)'with length ‘smallest number >= (n/8)'

Set containing n elements

Bit patterns provide a very efficient way of processing sets. You can represent a set of n elements using a field with type X, whose length is the integer part of n/8 (there are 8 bits in a byte) plus one byte for the remaining elements. So, for example, if your set contains 16 elements, you need a type X field with length 2 bytes, and if it contains 17 elements, the length of the field would be 3 bytes.

If the ith element of the basic set is contained in a set, the corresponding (ith) byte of the X field is set to 1, otherwise to 0.

The ith bit (1 <= i <= n) of the X field corresponds to the jth bit (1 <= j <= 8) in the kth byte of the X:

i = (k-1)*8+j, where k and j can be calculated from i using the following: k = (i DIV 8) + 1, for i > 8 k = (i DIV 8) , for i <=8 j = (i MOD 8) The 13th bit in the X field is therefore the 5th bit in the second byte. The 17th bit is the first bit in the third byte.

Page 363: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-4

© SAP AG

R

SET BIT and GET BIT

GET BIT <i> OF <hex> INTO <g>.

00 00 00 11 00 00 11 00 00 00 ...

1 2 3 4 5 6 7 8 9 10

SET BIT <i> OF <hex> [TO <f>].

DATA: hex(2) TYPE x, g TYPE i,val TYPE i VALUE 1.

SET BIT 4 OF hex. WRITE / hex.SET BIT 7 OF hex TO val. WRITE / hex.GET BIT 4 OF hex INTO g. WRITE / g.GET BIT 7 OF hex INTO g. WRITE / g.

00

16

SET BIT <i> OF <hex> TO <f> sets the ith bit of the X field <hex> to either 0 or 1. <i> is counted from the left of the field, starting with 1.

The TO <f> addition is optional. If you omit it, the ith but in the X field <hex> is set to 1. GET BIT <i> OF <hex> INTO <g> retrieves the value of the ith bit in the X field <hex>.

Page 364: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-5

© SAP AG

R

Assigning Values to X FieldsDATA: hex1(2) TYPE x,

hex2(2) TYPE x VALUE ,c(4) TYPE c VALUE ,i TYPE i VALUE .

hex1 = hex2. WRITE / hex1.hex1 = c. WRITE / hex1.hex1 = i. WRITE / hex1.

'1A4F'

'1A4F'

'6735'

00

1

215

00

2

214

00

3

213

11

4

212

4096

11

5

211

2048

00

6

210

11

7

29

512

00

8

28

00

9

27

11

10

26

64

00

11

25

00

12

24

11

13

23

8

11

14

22

4

11

15

21

2

11

16

20

1

11x AA 44 FF

6735

Bit No.

Value

When you assign a type C field to a type X field, ABAP interprets the C field as a hexadecimal value. One way of making use of this is to specify a text literal with hexadecimal contents for the C field, for example, VALUE '1A4F'.

When you assign a type I field to a type X field, the decimal value of the I field is converted into its corresponding hexadecimal value (6735 decimal equals '1A4F' hex). Caution: The internal representation of integers is platform-dependent. The sequence of the bits in the above example may be reversed. In other words, programming in the above manner may mean that your program will not run on all platforms.

Caution: You must write hexadecimal constants in uppercase. Lowercase letters are interpreted as zeros. For example writing DATA hex2(2) TYPE x VALUE '1a4F' would produce an entirely different result to the declaration in the above example.

Page 365: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-6

© SAP AG

R

Bit Calculations

11 00 00 11 00 00 11 001 2 3 4 5 6 7 8

11 11 11 11 00 00 00 001 2 3 4 5 6 7 8<hex1>

<hex2>

<bit_expression>BIT-NOT <hex2>

<hex1> BIT-AND <hex2><hex1> BIT-OR <hex2><hex1> BIT-XOR <hex2>

COMPUTE <hex> = .<bit_expression>

0 1 1 0 1 1 0 10 1 1 0 1 1 0 11 0 0 1 0 0 0 01 0 0 1 0 0 0 01 1 1 1 0 0 1 01 1 1 1 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 0 1 0

The statement COMPUTE <hex> = <bit expression> analyzes the but expression <bit expression> and places the result into the field <hex>. You can use the four bit operations BIT-NOT, BIT-AND, BIT-XOR, and BIT-OR. The operands are linked bit by bit according to the table below.

The priority is: BIT-NOT before BIT-AND before BIT-XOR before BIT-OR. Parenthetical expressions are allowed.

The operands in <bit expression> and the result field must all be of type X. Link table:

x y BIT-NOT x x BIT-AND y x BIT-XOR y x BIT-OR y __________________________________________________________ 0 0 1 0 0 0 0 1 1 0 1 1 1 0 0 0 1 1 1 1 0 1 0 1

If the operands are not the same length, they are converted to the length of the result field using MOVE X TO X logic. This means that operands shorter than the result field are filled with hex 0 at their right-hand end, and those longer than the result field are truncated at the right-hand end.

Page 366: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-7

© SAP AG

R

Bit Comparisons

11 00 00 11 00 00 11 001 2 3 4 5 6 7 8

11 11 11 11 00 00 00 001 2 3 4 5 6 7 8

O<f> Z <hex>

MDATA: hex1(1) TYPE x, hex2(1) TYPE x.IF hex1 O hex2. "falseIF hex1 Z hex2. "falseIF hex1 M hex2. "true

<f>

<hex>

Bit mask

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

The relational operators O, Z, and M have the following meanings: O (One) The expression is true if all bits in <hex> with the value 1 also have the value 1 in <f>. Z (Zero) The expression is true if all bits in <hex> with the value 1 have the value 0 in <f>. M (Mixed) The expression is true if all bits in <hex> with the value 1 have at least one 1 and at least one 0 in <f>.

You can use bit comparisons to check whether a set contains another set. To do this, you specify a pattern containing the set you want to search for, and use the bit comparison statements to check whether it belongs to the other set.

Page 367: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-8

© SAP AG

R

Example: Representing Flights with an X Field

REPORT sapbc411d_bit_processing.TYPES:week(1) TYPE x.DATA: flight_tab TYPE TABLE OF week

WITH HEADER LINE,every_week TYPE x VALUE 'FE',one_week TYPE x.

* fill flight_tab with bit pattern

* calculate every_week and one_weekLOOP AT flight_tab.every_week = flight_tab BIT-AND every_week.one_week = flight_tab BIT-OR one_week.ENDLOOP.

0 1 1 0 0 1 1 00 1 1 0 0 1 1 01 0 0 1 0 0 1 01 0 0 1 0 0 1 01 1 1 1 0 0 1 01 1 1 1 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 1 1 00 1 1 0 0 1 1 01 0 0 1 0 0 1 01 0 0 1 0 0 1 01 1 1 1 0 0 1 01 1 1 1 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 1 1 00 1 1 0 0 1 1 01 0 0 1 0 0 1 01 0 0 1 0 0 1 01 1 1 1 0 0 1 01 1 1 1 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 1 1 00 1 1 0 0 1 1 01 0 0 1 0 0 1 01 0 0 1 0 0 1 01 1 1 1 0 0 1 01 1 1 1 0 0 1 00 1 1 0 0 0 1 00 1 1 0 0 0 1 0

flight_tab

On which day of the week is there a flight every week:

0 0 0 0 0 0 1 00 0 0 0 0 0 1 0

1 1 1 1 0 1 1 01 1 1 1 0 1 1 0one_week

every_week

On which days of the week is there flightin at least one week:

The above example uses bit operations to indicate whether there is a flight on a particular day of a given week. The basic set contains seven elements - the days of the week. This basic set fits into an X field that is one byte long. The first seven bit positions represent the seven days of the week, and the eighth remains unused. So, for example, if the second bit is set, this indicates that there is a flight on the Tuesday of that week.

To provide an overview of all of the weeks of the year, we use an internal table (flight_tab) with line type X(1).

The variable every_week is initialized with 'FE' (1111 1110). In other words, the relevant bits (one to seven) are all set. Using BIT-AND to compare every_week with each line of the internal table, it is possible to find out the days of the week on which there is a flight in every week of the year, since the relevant bit changes from 1 to 0 if there is not a flight on the corresponding day.

The variable one_week is initialized with '00'. All bits are therefore set to 0. Using BIT-OR to compare one_week with each line of the internal table, it is possible to find out the days of the week on which there is a flight in at least one week of the year, since the relevant bit changes from 9 to 1 if there is a flight on the corresponding day of a given week.

Page 368: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 17-9

© SAP AG

R

Summary

You can use the data type X to represent a basic set of n elements in a single data object.

You can use SET BIT and GET BIT to set or read a single bit of a type X field.

BIT-NOT, BIT-AND, BIT-OR, and BIT-XOR allow you to perform calculations with X fields using normal boolean operations.

O, Z, and M are relational operators for X fields. You can use them to compare the state of a bit in a field of any type with a bit in a bit mask.

Page 369: BC411 - Advanced ABAP Programming

© SAP AG

R

Data Clusters: Contents

EXPORT

IMPORT

DELETE

Page 370: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-2

© SAP AG

R

Unit Objectives

At the end of this unit, you will be able to store data objects under an ID

In a cluster database

In the cross-transaction application buffer (shared buffer)

In ABAP memory

You will be able to use clusters in your programs, and be aware of their advantages and disadvantages.

Page 371: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-3

© SAP AG

R

Data Clusters: Overview

KTNRA NAME1 TDM

Data cluster:

DATABASE

A1A1......AnAn

Export Import

ABAP memory Shared buffer

Fields

Structuredfields

Internaltables

A data cluster is a collection of data objects. A data object can be a field, a structured field, an internal table, or any complex structure made up of several of these components. You process clusters using the ABAP statements EXPORT, IMPORT, and DELETE. You can store them in ABAP memory, in a cluster database, or in the shared buffer.

The following pages explain more about ABAP memory, cluster databases, and the shared buffer.

Page 372: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-4

© SAP AG

R

REPORT xxxTABLES indx.EXPORT optional

<field 1> FROM <field a><field 2> FROM <field b>. .. .<structure 1> FROM <structure a>. .. .<itab 1> FROM <itab a>. .. .

TO DATABASE indx(<ar>)ID <id>.

EXPORT <name> FROM <obj> [<obj>]

TO DATABASE <dbtab>(<ar>) ID <id>.

Syntax: EXPORT to a Cluster Database

In the ABAP Dictionary, you can divide a cluster database into a series of work areas with logically-related data clusters. Work area IDs are two characters long, and may be freely chosen. Within a work area, you identify each cluster by its cluster ID.

To export data, you need a cluster database. The table INDX is an all-purpose cluster database. Cluster databases should be created as transparent tables in the ABAP Dictionary, and must have a standard structure. For further information, refer to the online documentation in the ABAP Editor for the EXPORT statement.

In the EXPORT statement, you list the data objects that belong to your cluster. To export data, specify the name of the cluster database and the work area. You identify the cluster

itself by its cluster ID. If you want a data object in the cluster to have a different name from that in the program, use the optional addition FROM. You can specify the data object in the list in any order. There is no write-protection when you export data - existing clusters are automatically overwritten in a new EXPORT.

The data is stored in compressed form in the cluster database. At the start of your program, declare a work area for your cluster database using the TABLES

statement. Caution: You cannot export the header line of an internal table. The EXPORT statement always

applies to the entire table contents.

Page 373: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-5

© SAP AG

R

REPORT xxxTABLES indx.IMPORT optional

<field 1> TO <field a><field 2> TO <field b>. .. .<structure 1> TO <structure a>. .. .<itab 1> TO <itab a>. .

FROM DATABASE indx(<ar>)ID <id>.

IMPORT <name TO <obj>[<obj>]

FROM DATABASE <dbtab>(<ar>) ID <id>.

DELETE FROM DATABASE INDX(<ar>)ID <id>.

Syntax: IMPORT and DELETE

When you import data, you can list the data objects in any order in the IMPORT statement. You do not need to import all of the data objects from your cluster. If you want the data objects in the program to have different names to those used in the cluster, you can use the optional TO addition.

The IMPORT statement sets the return code field SY-SUBRC, which applies to the entire cluster, not to individual data objects. SY-SUBRC is unequal to zero if the cluster does not exist.

The structure of the fields, structures, and internal tables that you want to import must correspond to the structure of the data objects in the database, otherwise a runtime error occurs. Furthermore, you must import the objects using the same names under which you exported them. If the cluster exists, the return code is set to zero, whether or not objects have been imported.

Caution: The IMPORT statement always imports the body of an internal table. This means that the header line of the table remains unchanged by the import.

The DELETE statement deletes the entire cluster and sets the return code field SY-SUBRC. You cannot delete an individual data object within a cluster.

Page 374: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-6

© SAP AG

R

Key of the Database Table INDX

Cluster area: a1 INDXINDX

1 - 3 4 - 5 6 - 27 28 -31 Position

Client Area Cluster ID Next entry Contents

001 a1 E105 0001 Example

1 - 3 4 - 5 6 - 27 28 -31 Position

Client Area Cluster ID Next entry Contents

001 a1 E105 0001 Example

001 a1 E10 50000f1 f2 f3I1

Next entry: 0000

Next entry: 0001

Next entry: 0002

Next entry: 0003 001 a1 E10 50003l1 Fortsetzgl2 t1 . . .

001 a1 E10 50002

l2 t1 . . .001 a1 E10 50001l1 Continuedl2 I3 . . .

Key

Contents

The database table INDX is an example of a table in which you can store data clusters. In your system, it is installed with a standard key length of 31 bytes.

You can display the structure of the table from the online documentation in the ABAP Editor by entering the table structure INDX. The key consists of client, work area, cluster ID, and next entry number. The cluster ID has a default length of 22 bytes, but it can have any length.

For large data clusters, the runtime system automatically appends new entries with the same length.

Page 375: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-7

© SAP AG

R

ABAP Cluster Databases

3 2 n 4 m 2MANDT RELID SRTF2 CLUSTR CLUSTDCLUSTD

Char Char Char INT4 INT2 LRAWLRAW

Generated, based on the length for thecluster table

Created structureStructure:

LengthNameType

Client Workarea

Cluster ID Nextentry

counter

Yourown

fields(optional)

Length Data field

INDX PERG RETL MLTS. . .

Examples:

Key fields

You can create your own ABAP cluster tables. To do so, proceed as follows: Create a table in the ABAP Dictionary as a transparent table. This is your cluster database. Use the above table structure. You may leave out the MANDT field (if you include it, it is filled automatically). The fields RELID, SRTF2, CLUSTR, CLUSTD, and the cluster ID are automatically filled during an EXPORT.

The optional user-defined fields must be filled before the EXPORT. You can then analyze them after an IMPORT.

The field names for the cluster ID and the user-defined fields can be chosen freely. The other fields must be named as above.

The length of the part of the table used for the data cluster is the total length of the structure minus the length of the first six fields.

Page 376: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-8

© SAP AG

R

Example: Catalog for INDX

REPORT sapbc411d_clustercatalogue.TABLES indx.SELECT-OPTIONS:

area FOR indx-relid,clstr_id FOR indx-srtfd.

START-OF-SELECTION.SELECT DISTINCT relid srtfd aedat usera pgmid

INTO (indx-relid, indx-srtfd, indx-aedat,indx-usera, indx-pgmid) FROM indx

WHERE relid IN areaAND srtfd IN clstr_id.

* AND srtf2 = 0.

WRITE: / indx-relid,indx-srtfd,indx-aedat DD/MM/YYYY,indx-usera,indx-pgmid.

ENDSELECT.

REPORT sapbc411d_clustercatalogue.TABLES indx.SELECT-OPTIONS:

area FOR indx-relid,clstr_id FOR indx-srtfd.

START-OF-SELECTION.SELECT DISTINCT relid srtfd aedat usera pgmid

INTO (indx-relid, indx-srtfd, indx-aedat,indx-usera, indx-pgmid) FROM indx

WHERE relid IN areaAND srtfd IN clstr_id.

* AND srtf2 = 0.

WRITE: / indx-relid,indx-srtfd,indx-aedat DD/MM/YYYY,indx-usera,indx-pgmid.

ENDSELECT.

As well as its key fields and the data cluster, the structure of the database table INDX has optional fields for administrative data (date of last change, validity date, name of user, and so on. For further information, refer to the structure INDX.) You can use the SELECT statement to access the key and administration fields (for example, to create a catalog). The system only fills the administration data fields if you fill them before the EXPORT using the MOVE statement (for example, MOVE SY-DATUM TO INDX-AEDAT).

Page 377: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-9

© SAP AG

R

ABAP Memory - Overview: Communication Between Internal Sessions

External session 1

Internal session 1

AB

AP

mem

ory

AB

AP

mem

ory

Internal session 2

External session 2

Internal session 1

Program 3Program 3

AB

AP

mem

ory

AB

AP

mem

ory

Internal session 2

ExportImport

ExportImport

R/3 terminal session

Roll area

Roll area

Roll area

Roll area

Program 4Program 4

Program 1Program 1

Program 2Program 2

A single terminal session in the R/3 System consists of one or more external sessions. Choosing System -> Create session or entering '/o….' in the command field creates a new external

session. The ABAP memory is active for the duration of an external session. A new internal session is created when you call a transaction (CALL TRANSACTION), a dialog

module (CALL DIALOG) or a report (SUBMIT… AND RETURN). For each internal session, the system creates a roll area containing the program data. You can make data available to several internal sessions by copying it into ABAP memory using EXPORT … TO MEMORY and using IMPORT … FROM MEMORY to read it.

Page 378: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-10

© SAP AG

R

ABAP/4

Transporting Data Between Programs(ABAP Memory)

ABAP memory

MYID

SPFLISPFLIIT_SPFLIIT_SPFLI

PROGRAM p1 ... ....DATA: p1_spfli LIKE spfli,

it_spfli LIKE spfliOCCURS 0.

...

SUBMIT p2.

IMPORTspfli TO p1_spfliit_spfliFROM MEMORY ID 'MYID'.

PROGRAM p2 ... ....DATA: p2_spfli LIKE spfli,

it_spfli LIKE spfliOCCURS 0.

...

IMPORTspfli TO p2_spfliit_spfliFROM MEMORY ID 'MYID'.

The EXPORT … TO MEMORY statement exports data as a cluster to the ABAP memory. The data is user-specific.

Since the ABAP memory is only available within a call chain (CALL TRANSACTION, CALL DIALOG, SUBMIT… AND RETURN), the data is lost as soon as the first program in the chain ends.

The IMPORT statement allows you to read data from ABAP memory into your program. Unlike the IMPORT… FROM DATABASE variant, the system does not check whether the source

and target fields have the same structure. You can delete the whole memory using the FREE MEMORY statement, or delete the memory for

a particular ID <id> using the FREE MEMORY ID <id> statement (analogous to FREE <itab>).

Page 379: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-11

© SAP AG

R

Application server 1

Program 1Program 1

Shar

ed b

uffe

rProgram 2Program 2

ExportImport

ExportImport

Shared Buffer - Overview

The cross-transaction application buffer is a memory area within an application server that is accessible to all of the work processes of an R/3 instance.

You can use it to store and retrieve data from application programs using the statements - EXPORT ... TO SHARED BUFFER <dbtab>(ar) ID <id> and - IMPORT ... FROM SHARED BUFFER <dbtab>(ar) ID <id> and delete data in the buffer using the statement - DELETE FROM SHARED BUFFER <dbtab>(ar) ID <id>

The data in the application buffer is visible to all transactions on the application server once it has been exported. Old data may be overwritten by new exports. This means that you should not assume that your application can reread the same data that it stored. The data can be deleted (for example, by another, parallel transaction), or be overwritten by new data. For this reason, you should export your data to a cluster database as well as to the shared buffer, and double check imported data against the cluster database. In this way, the shared buffer provides a kind of application buffer for the cluster database. When you use the shared buffer, you may encounter space problems if the cluster is too large. This results in a catchable runtime error (EXPORT_BUFFER_NO_MEMORY).

The storage structures used in the EXPORT, IMPORT, and DELETE statements, (database table), must have a standardized structure.

Page 380: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-12

© SAP AG

R

Cluster tableCluster table Transparent tableTransparent table

Only contains data within the cluster

Little access for large amounts of data

Heterogenous data (field, structured fields, internal tables)

Flexible technique

Not possible to link data

Access requires cluster ID and area

Access only returns one cluster

In relational database

Multiple access, since the data is stored in different tables

Data can be linked and evaluated

Select with any number of logical conditions

Cluster Tables and Transparent Tables

The cluster database contains the data in the required form. The internal administration of the cluster table means that you can read large quantities of data with relatively few database accesses.

In transparent tables, the standardization means that the data has to be selected from several tables, requiring more access. However, this can be made more efficient by using joins (from Release 3.1) in ABAP Open SQL (refer to the unit about ABAP Open SQL). The advantage of transparent tables is that you can read single obejcts from different tables and relate them to other objects. Compare this with cluster tables, where you can only read the data of a single cluster and cannot link this data to that in other clusters.

To access cluster data, you must know the cluster ID and the work area. Furthermore, the access can only return the data for a single cluster ID (where a SELECT loop could return more than one cluster). In transparent tables, you can retrieve data based on any logical expression.

Page 381: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 18-13

© SAP AG

R

Summary

In this unit, you have learned how to store data objects under an ID:

In a cluster table

In ABAP memory

In the shared bufffer

Page 382: BC411 - Advanced ABAP Programming

© SAP AG

R

Exercises

Note:

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

Page 383: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-2

Data used in the exercises: Data from database tables SGEOCITY, SPFLI, SFLIGHT, SBOOK All of the Repository objects used in this course can be found in development class SAPBC411. This development class is supplied to customers. You should find it in your IDES system. Names of model solutions Program name SAPBC411S_LIST SAPBC411S_TYPE SAPBC411S_ASSIGN SAPBC411S_KEYTAB_DEFINITION SAPBC411S_KEYTAB_FILL SAPBC411S_KEYTAB_READ SAPBC411S_TESTFRAME_ITABS SAPBC411S_OO_CREATE_CLASS SAPBC411S_OO_OBJECT_METHOD SAPBC411S_OO_INTERFACES SAPBC411S_OO_EVENTS SAPBC411S_OO_EVENT_PROTOCOLL SAPBC411S_CONTEXT_GEOGR_DISTAN SAPBC411S_FLIGHTS_OF_ONE_YEAR SAPBC411S_READ_10_FLIGHTS SAPBC411S_CUMULATE_LOCCURAM SAPBC411S_SEL_SFLIGHT_SBOOK SAPBC411S_SELECT_SUBQUERY SAPBC411S_SELECT_HAVING

Page 384: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-3

SAPBC411S_STRING_BIT_OPERATION

Page 385: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-4

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

1.1 Description of program: The program displays a selection screen containing a default date range of 01.01.1900 to 01.01.2000, and a parameter in which the user can specify a column of a structure, defined in the program. The program then displays a list of all flights within the specified period. The list is sorted by the column chosen by the user on the selection screen.

1.2 Copy the template program SAPBC411T_LIST and all of its includes to program ZBC411_##_LIST. Rename the includes with appropriate names.

1.3 Edit the three includes (<prefix>TOP, <prefix>E01, and <prefix>F01) and correct the syntax errors and warnings. Edit the main program to remove the syntax errors from the entire program.

1.4 Check the program using the extended program check and correct any errors and warnings.

1.5 Perform a runtime analysis for your program. Find out why the runtime is so high and correct the cause.

Page 386: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-5

Object Name / Description

Copy program SAPBC411T_List

Create program ZBC411_##_List

Activities

In the ABAP Editor settings, select the ‘Key words large’ option. This makes it easier to distinguish ABAP keywords from variables and macros.You do not need to change the program logic. You need the form routine OUTPUT to display the list.

Tips & tricks

Page 387: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-6

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

1.5 Copy the template program SAPBC411T_TYPE to ZBC411_##_TYPE. The program calculates the factorial of a number n.

1.6 Use the runtime analysis (Transaction SE30) to check the program for unnecessary type conversions. Eliminate these by using a single data type throughout the program.

Object Name / Description

Template program SAPBC411T_TYPE

Target program ZBC411_##_TYPE

Activities

It is possible to avoid all type P conversions in your program. The only type P conversions that should take place are those in system programs.

Tips & Tricks

Page 388: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-7

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

1.1 Copy the template program SAPBC411T_ASSIGN to ZBC411_##_ASSIGN. The program reads entries from table SFLIGHT for a given airline, and displays the column of the table specified in the ‘COMPONO’ parameter. There is an error in the program that prevents it from running properly.

1.2 Correct the error.

1.3 The required column is displayed with length 30. Change the program so that the minimum length is displayed, that is, the contents of the field without any trailing spaces.

1.4 Change the program so that the user can enter the component name instead of the component number.

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

Page 389: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-8

Object Name / Description

Template program SAPBC411T_ASSIGN

Activities

Target program ZBC411_##_ASSIGN

Page 390: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-9

Unit: Internal tables Exercise 1: Theme: Defining internal tables

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

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

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

Object Name / Description

Program ZBC411_##_itab

Activities

Tips & Tricks

Page 391: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-10

Unit: Internal tables Exercise 2: Theme: Filling internal tables

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

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

Object Name / Description

Program ZBC411_##_itab

Activities

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

Tips & Tricks

Page 392: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-11

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

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

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

3.3 Optional: Measure the runtime required to read the data for the

different table types by embedding your program in the test framework program.

3.4 Optional: Copy the program SAPBC411T_TESTFRAME to the

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

Object Name / Description

Program ZBC411_##_itab

Program template for runtime measurement

ZBC411T_testframe

Optional: Your program for measuring the runtime (copied from template)

ZBC411_##_testframe

Activities

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

Page 393: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-12

Tricks

Page 394: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-13

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

1.1 Write a program to create the classes C_SHIP and S_TRUCK

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

1.3 Define the attribute INST_ID in the classes as a class attribute. This will act as a counter for the various instances.

1.4 Define the attribute ID for the number of an instance and the attribute SHIP_SPEED or TRUCK_SPEED for the current speed.

1.5 Create the following objects for the program:

Object Name / Description

Program ZBC411_##_OO_create_class

Class C_SHIP: Ship class

Class C_TRUCK: Truck class

Attribute SHIP_SPEED, TRUCK_SPEED: speed Type: integer

Attribute MAX_SPEED: maximum speed Type: integer

Attribute ID: Identity

Type: integer

Activities

Class attribute INST_ID: Instance ID Type: integer

Page 395: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-14

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

2.1 Extend the program you wrote in exercise 1 by defining and implementing methods.

2.2 Both classes should have the methods CONSTRUCTOR, SPEED_UP, STOP, and WRITE. None of the methods has an interface.

2.3 Define the instances OSHIP and OTRUCK, and two internal tables that can store the instances of the classes you have defined.

2.4 Using a DO loop for each class, create two instances of each of the classes C_TRUCK and C_SHIP and add them to the appropriate internal table.

2.5 Use a LOOP statement to process the entries of each internal table. Within the loop, call the methods SPEED_UP and WRITE for the corresponding instances.

Page 396: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-15

2.6 Create the following objects for the program:

Object Name / Description

Program ZBC411_##_OO_object_method

Method CONSTRUCTOR: Increase the class attribute INST_ID by 1, assign the value to the ID attribute, and set the MAX_SPEED attribute to 30 for class C_SHIP and to 140 for class C_TRUCK.

Method SPEED_UP: Check that SPEED is less than MAX_SPEED, and then increase the speed by 10 for C_SHIP or by 20 for C_TRUCK.

Method STOP: Set SPEED to 0.

Method WRITE: Display the following: 'TRUCK- ID = <value> SPEED = <value>'

Activities

Instance OSHIP

OTRUCK

Internal table SHIP_TAB

TRUCK_TAB

with type REF TO class C_SHIP or C_TRUCK

Tips & Tricks

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

Page 397: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-16

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

3.1 Extend your program from exercise 2 by enclosing repetitively-used logic in an interface that presents a common point of contact for both classes. Define and implement the interface I_VEHICLE.

3.2 The methods SPEED_UP, STOP, and WRITE, and the attributes ID and MAX_SPEED should now be defined in the interface, and implemented in the classes C_SHIP and C_TRUCK. The methods have no interface.

3.3 Implement the CONSTRUCTOR method so that the interface attribute ID is supplied with the value of the class attribute INST_ID. You will also need to adjust the interface attribute MAX_SPEED accordingly.

3.4 Change the main program so that the two internal tables are replaced by a single table veh_tab that can contain references to the interface.

3.5 Define an interface reference variable IVEHICLE.

3.6 In a DO lop, fill the internal table VEH_TAB and call the interface methods SPEED_UP, WRITE, STOP, and WRITE.

Page 398: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-17

Create the following objects in your program:

Object Name / Description

Program ZBC411_##_OO_interfaces

Interface I_VEHICLE: Methods SPEED_UP, STOP, WRITE Attributes: ID and MAX_SPEED.

Method CONSTRUCTOR: Supply values to the interface attributes ID and MAX_SPEED.

Attribute Define INST_ID as a class attribute.

Interface method SPEED_UP: Change the name of the method and its attributes as required. Its function does not change.

Interface method STOP: Change the name of the method and its attributes as required. Its function does not change.

Method WRITE: Change the name of the method and attributes as required. Its function does not change.

Activities

Internal table VEH_TAB: Replaces the two previous internal tables. Line type: TYPE REF TO I_VEHICLE.

Interface reference variable IVEHICLE Type: TYPE REF TO I_VEHICLE.

DO loops APPEND to the internal table

LOOP Call the interface methods SPEED_UP, WRITE, STOP, WRITE

Page 399: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-18

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

4.1 Copy the template program SAPBC411T_OO_EVENTS to ZBC411_##_OO_EVENTS and include event handling in it. The program allows you to create instances of the classes C_SHIP and C_TRUCK using pushbuttons. You can also call the methods SPEED_UP, WRITE and STOP using pushbuttons if the cursor is on an existing object.

4.2 Familiarize yourself with the program SAPBC411S_OO_EVENTS.

4.3 Insert two events. 1.) The interface event SPEED_CHANGE with export parameter NEW_SPEED and 2.) the class event BUTTON_CLICKED with export parameter FCODE.

4.4 The event SPEED_CHANGE should be triggered by the interface methods SPEED_UP and STOP and be handled by the handler method LIST_CHANGE in the new class C_LIST. The event BUTTON_CLICKED should be triggered by the class method USER_ACTION of the new class STATUS and be handled by the handler method FCODE_HANDLER in class C_LIST.

4.5 Use SET HANDLER to register both handler methods.

4.6 Make the necessary changes at the appropriate points in the program code.

Page 400: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-19

4.7 Create the following objects for the program:

Object Name / Description

Program template SAPBC411T_OO_events

Target program ZBC411_##_OO_events

Interface event SPEED_CHANGE Exporting parameter NEW_SPEED type I, passed by value

Class event BUTTON_CLICKED Exporting parameter FCODE LIKE SY-UCOMM, passed by value

Handler method FCODE_HANDLER in the PUBLIC SECTION of class C_LIST. Define this method for the event BUTTON_CLICKED of class status, receiving the import parameter FCODE.

Handler method LIST_CHANGE in the PUBLIC SECTION of class C_LIST. Define this method for the event SPEED_CHANGE of interface I_VEHICLE, receiving the import parameter NEW_SPEED.

Trigger event The interface methods SPEED_UP and STOP should call the event SPEED_CHANGE in all classes using the RAISE EVENT statement and passing the export parameter. The parameter must be supplies with the value of the corresponding actual parameter.

Trigger event The class event BUTTON_CLICKED should be triggered by the method USER_ACTION in class STATUS. Its export parameter is FCODE, which is set when the user chooses a pushbutton (FCODE = SY-UCOMM).

Activities

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

Page 401: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-20

Page 402: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-21

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

5.1 Extend your program ZBC411_##_OO_EVENTS or copy the model solution SAPBC411S_OO_EVENTS to ZBC411_##_OO_EVENTS and include more event handling. Create a log of the functions that the user has chosen and display a list the first time the user chooses Cancel. The program should not end until the user presses Cancel a second time. Familiarize yourself with program SAPBC411S_OO_EVENT_PROTOKOLL.

5.2 You need to extend the existing program in three places. 1.) Define and implement a class C_PROTOKOLL with the public class methods FCODE_HANDLER and WRITE_PROTOCOLL, the public static attribute PROTOCOLL_WRITTEN, and the private static attribute FCODE_TAB, an internal table for storing the function codes triggered by the user.

5.3 The method FCODE_HANDLER is the handler method for the event BUTTON_CLICKED in class STATUS. It imports the function code from the variable FCODE.

5.4 2.) In the method FCODE_HANDLER of class C_LIST, you need to find out whether the static variable PROTOCOLL_WRITTEN = 1 when the user chooses CANCEL. If it is, leave the program. If not, call the static method WRITE_PROTOCOLL of the class C_PROTOCOLL, and stop the CASE statement with the STOP statement.

5.5 In the method WRITE_PROTOCOLL, loop through the internal table FCODE_TAB and display the contents. Afterwards, set the attribute PROTOCOLL_WRITTEN to 1.

5.6 Include another SET HANDLER statement to register the method FCODE_HANDLER for the class C_PROTOKOLL.

Page 403: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-22

5.7 Create the following objects for the program:

Object Name / Description

Program template SAPBC411S_OO_events or your program ZBC411_##_OO_events

Define and implement a class C_PROTOCOLL

Class definition

Public section: class methods

Static attribute

FCODE_HANDLER for the event BUTTON_CLICKED of class STATUS. Importing parameter FCODE

WRITE_PROTOCOLL, no interface

PROTOCOLL_WRITTEN TYPE i READ ONLY.

Private section: Internal table FCODE_TAB LIKE sy-ucomm OCCURS 0.

Class implementation FCODE_HANDLER should inserts FCODE into the internal table FCODE_TAB.

WRITE_PROTOCOLL: Loop through the internal table FCODE_TAB into a local variable within the method and display the contents. Then set the static variable PROTOCOLL_WRITTEN to 1.

Handle event The handler method FCODE_HANDLER in class C_LIST needs to be changed for the CANCEL function so that you leave the program if the static variable PROTOCOLL_WRITTEN has the value 1 (C_PROTOCOLL=> PROTOCOLL_WRITTEN = 1), otherwise, you call the static method WRITE_PROTOCOLL (CALL METHOD C_PROTOCOLL=> WRITE_PRTOCOLL) and then leave the CASE statement with the STOP statement.

Activities

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

Page 404: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-23

Page 405: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-24

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

1.7 Create a context to calculate the distance between two cities. It should consist of the following modules:

1.8 Context C_GEOGR_INFO and the function module CONTEXT_DEMO_COMPUTE_DISTANCE, which calculates the distance.

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

Object Name / Description

Context ZBC411_##_C_Geogr_Dist

Activities

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

Tips & Tricks

Page 406: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-25

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

2.1 Write a program that uses the context ZBC411_##_C_Geogr_Dist to calculate the distance between two cities.

2.2 To do this, define a context instance in your program and use the SUPPLY statement to pass values for the key fields to it. Calculate the distance between NEW YORK and FRANKFURT, retrieve it from the context using the DEMAND statement, and display it on a list. Leave error handling to the system.

1.

Object Name / Description

Program ZBC411_##_Geogr_Dist

Activities

Tips & Tricks

Page 407: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-26

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

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

Object Name / Description

Program ZBC411_##_Flights_Of_One_Year

Activities

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

Tips & Tricks

Page 408: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-27

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

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

Object Name / Description

Program ZBC411_##_Read_10_Flights

Activities

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

Tips & Tricks

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

Page 409: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-28

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

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

Object Name / Description

Program ZBC411_##_Cumulate_Loccuram

Activities

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

Tips & Tricks

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

Page 410: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-29

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

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

Object Name / Description

Program ZBC411_##_Sel_Sflight_Sbook

Activities

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

Tips & Tricks

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

Page 411: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-30

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

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

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

Object Name / Description

Program ZBC411_##_Sel_Max_Seatsocc

Activities

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

Tips & Tricks

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

Page 412: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-31

Theme: Minimizing the amount of data transferred

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

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

CARRID CONNID FLDATE avg. LUGGWEIGHT number of pass.

LH 0400 12.02.1998 31 12

Object Name / Description

Program ZBC411_##_Select_Having

Activities

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

Page 413: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-32

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

Tips & Tricks

Page 414: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-33

Unit: String Processing Exercise 1: Converting the value of a type I input field into a binary string Theme: String processing

1.9 Write a program to convert the value of a type I input field into a binary string. Display the binary string as a 32-character type C field.

Object Name / Description

Program ZBC411_##_String_Operation

Activities

Method: Use a WHILE loop with the MOD and DIV statements to retrieve the individual bits of the input value and place them in an output field using CONCATENATE. Use a loop counter to count the number of digits, and then use the SHIFT <output field> RIGHT BY <number> PLACES, to shift free places to the right. Use TRANSLATE <output field> USING <val> to change the spaces to zeros.

You can use the template program SAPBC411T_STRING_OPERATION for your solution

Tips & Tricks

Page 415: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 19-34

Unit: Bit processing Exercise 1: Converting the value of a type I input field into a binary string Theme: Bit processing

1.10 Repeat the string processing exercise, but this time use bit operations. Write a program to convert the value of a type I input field into a binary string. Display the binary value in a 32-character type C field.

Object Name / Description

Program ZBC411_##_ Bit_Operation

Activities

Tips & Tricks

One way of solving this problem is to place the input value into a hex field and use a WHILE loop and the GET BIT sy-index OF <hexfield> INTO <field> statement to find out which bits have the value 1. You then need to place these bits into the output field with the correct offset. Before you start, initialize the output field using CLEAR <output field> WITH '0'.

You may use the template program SAPBC411T_##_BIT_OPERATION for your solution.

Page 416: BC411 - Advanced ABAP Programming

© SAP AG

R

Solutions

Page 417: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-2

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

Model solution SAPBC410S_LIST

TOP include *&-------------------------------------------------------------*

*& Include BC411S_LISTTOP *

*& *

*&-------------------------------------------------------------*

PROGRAM sapbc411s_list MESSAGE-ID bc411 LINE-SIZE 130.

*TABLES statement not necessary

PARAMETERS:

s_from TYPE s_date DEFAULT '19000101',

s_to TYPE s_date DEFAULT '20000101',

s_sort(1) TYPE c DEFAULT '1'.

DATA:

slist TYPE tab_slist,

result TYPE c.

*CONSTANTS c_length is not used

*Macro definition increases runtime unnecessarily

Page 418: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-3

SAPBC411S_LISTEE01 Include (Event include)

*--------------------------------------------------------------*

* INCLUDE BC411S_LISTE01 *

*--------------------------------------------------------------*

*wrong parameters passed

CALL FUNCTION 'SAPBC411_GET_DATA' EXPORTING p_from = s_from

p_to = s_to

IMPORTING p_list = slist

EXCEPTIONS no_data = 1.

*Returncode check and possible EXIT statement were missing

IF sy-subrc <> 0.

WRITE 'No flights found'(001).

EXIT.

ENDIF.

*Spelling error and wrong parameter passed

PERFORM sort TABLES slist USING s_sort CHANGING result.

IF result = space.

MESSAGE s000.

ENDIF.

*Spelling error and wrong parameter passed

PERFORM output USING slist.

Page 419: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-4

SAPBC411S_LISTEF01 (Form include) *---------------------------------------------------------------*

* INCLUDE BC411S_LISTF01 *

*---------------------------------------------------------------*

*pass parameter p_sortindex as reference

FORM sort TABLES p_list TYPE tab_slist

USING p_sortindex TYPE c

CHANGING p_result TYPE c.

*l_field1(clength) not required

*defining l_component as type i reduces unnecessary type p *conversion

*see runtime analyses

DATA:

l_component TYPE i.

FIELD-SYMBOLS

<l_fs>.

p_result = 'X'.

*spelling error

l_component = p_sortindex.

*Spelling error in field symbol

ASSIGN COMPONENT l_component OF STRUCTURE p_list TO <l_fs>.

* Clear before EXIT

IF sy-subrc <> 0.

CLEAR p_result.

EXIT.

ENDIF.

SORT p_list BY <l_fs>.

*Macro definition increases runtime. Macro unnecessary

ENDFORM.

*---------------------------------------------------------------*

* FORM OUTPUT *

*---------------------------------------------------------------*

Page 420: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-5

*

*Pass Parameter p_list with VALUE

FORM output USING p_list TYPE tab_slist.

DATA:

*Spelling error: LIKE LINE OF p_list instead of LIKE LINE OF * *l_list

l_list_wa LIKE LINE OF p_list.

*Status LISTE instead of LIST. And SET PF-STATUS only once *outside of the LOOP.

SET PF-STATUS 'LISTE'.

LOOP AT p_list INTO l_list_wa.

*l_list_wa-price without currency clause

WRITE: /

l_list_wa-fldate,

l_list_wa-countryfr,

l_list_wa-cityfrom,

l_list_wa-countryto,

l_list_wa-cityto,

l_list_wa-price CURRENCY l_list_wa-currency,

l_list_wa-currency.

ULINE.

ENDLOOP.

WRITE 'End of list'(002).

ENDFORM.

*empty FORM work. Not necessary

*PERFORM after FORM can not be reached.

Page 421: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-6

Unit: Types Exercise 1: Adjusting Data Types Theme: Runtime of Data Type Conversions

Solution SAPBC411S_TYPE *&-----------------------------------------------------------------*

*& Report SAPBC411T_TYPE *

*&-----------------------------------------------------------------*

*& *

REPORT sapbc411t_type .

PARAMETERS:

*n type i avoids type P conversions. Also true for variable result

n TYPE i.

DATA:

result TYPE i.

*n of Type i. Don't pass as string. Avoids internal conversions.

IF n > 12.

WRITE 'N is too large'(001).

EXIT.

ENDIF.

PERFORM fakultaet USING n CHANGING result.

WRITE: / n, result.

*------------------------------------------------------------------*

* FORM FAKULTAET *

Page 422: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-7

*------------------------------------------------------------------*

* --> VALUE(P_N) *

* --> P_RESULT *

*------------------------------------------------------------------*

*p_n pass as reference is faster. Complete type definition reduces

*errors.

FORM fakultaet USING p_n TYPE i

CHANGING p_result TYPE i.

DATA:

*l_temp only with length 1 required. Defined as type i avoids *conversions in calculations

l_temp TYPE i.

*Value 0 not as string. Avoids internal conversions. Also true with

*p_result

IF p_n = 0.

p_result = 1.

EXIT.

ENDIF.

*Don't pass value 1 as string

l_temp = p_n - 1.

PERFORM fakultaet USING l_temp CHANGING p_result.

p_result = p_n * p_result.

ENDFORM.

Page 423: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-8

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

Model solution SAPBC410S_BIT_OPERATION

*&------------------------------------------------------------------

*& Report SAPBC411S_ASSIGN *&

*&------------------------------------------------------------------

REPORT sapbc411t_assign.

PARAMETERS:

carrid TYPE sflight-carrid DEFAULT 'LH',

compno TYPE i DEFAULT '1',

compname(8) TYPE c DEFAULT 'CONNID'.

PERFORM write_selected_field USING compno.

ULINE.

PERFORM write_selected_field_2 USING compname.

ULINE.

PERFORM write_selected_field_3 USING compname.

*------------------------------------------------------------------*

* FORM WRITE_SELECTED_FIELD *

*------------------------------------------------------------------*

* ........ *

*------------------------------------------------------------------*

* --> P_COMPNO *

Page 424: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-9

*------------------------------------------------------------------*

FORM write_selected_field USING p_compno TYPE any.

DATA:

l_wa_sflight TYPE sflight,

l_field(30) TYPE c,

l_length TYPE i.

FIELD-SYMBOLS:

<l_fs>.

SELECT * FROM sflight INTO l_wa_sflight WHERE carrid = carrid.

PERFORM assign_component USING l_wa_sflight

p_compno

CHANGING l_field.

l_length = STRLEN( l_field ).

ASSIGN l_field(l_length) TO <l_fs>.

IF sy-subrc = 0.

WRITE / <l_fs> COLOR COL_NEGATIVE.

ENDIF.

ENDSELECT.

ENDFORM.

*------------------------------------------------------------------*

* FORM ASSIGN_COMPONENT *

*------------------------------------------------------------------*

* ........ *

*------------------------------------------------------------------*

* --> P_STRUCTURE *

* --> P_COMPONENT *

* --> P_RESULT *

*------------------------------------------------------------------*

FORM assign_component USING p_structure TYPE any

p_component TYPE any

CHANGING p_result TYPE any.

FIELD-SYMBOLS:

<l_fs>.

Page 425: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-10

ASSIGN COMPONENT p_component OF STRUCTURE p_structure TO <l_fs>.

MOVE <l_fs> TO p_result.

ENDFORM.

*------------------------------------------------------------------*

* FORM WRITE_SELECTED_FIELD_2 *

*------------------------------------------------------------------*

* ........ *

*------------------------------------------------------------------*

* --> P_COMPNO *

*------------------------------------------------------------------*

FORM write_selected_field_2 USING p_compname TYPE c.

DATA:

l_wa_sflight TYPE sflight,

l_field(30) TYPE c,

l_length TYPE i.

FIELD-SYMBOLS:

<l_fs>.

SELECT * FROM sflight INTO l_wa_sflight WHERE carrid = carrid.

PERFORM assign_component USING l_wa_sflight

p_compname

CHANGING l_field.

l_length = STRLEN( l_field ).

ASSIGN l_field(l_length) TO <l_fs>.

WRITE / <l_fs> COLOR COL_NEGATIVE.

ENDSELECT.

ENDFORM.

Page 426: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-11

*------------------------------------------------------------------*

* FORM WRITE_SELECTED_FIELD_3 *

*------------------------------------------------------------------*

* ........ *

*------------------------------------------------------------------*

* --> P_COMPNO *

*---------------------------------------------------------------------*

FORM write_selected_field_3 USING p_compname TYPE c.

DATA:

l_wa_sflight TYPE sflight, "#EC *

l_field_name(30) TYPE c,

l_length TYPE i.

FIELD-SYMBOLS:

<l_fs>.

SELECT * FROM sflight INTO l_wa_sflight WHERE carrid = carrid.

CONCATENATE 'L_WA_SFLIGHT-' p_compname INTO l_field_name.

ASSIGN (l_field_name) TO <l_fs>.

l_length = STRLEN( <l_fs> ).

ASSIGN <l_fs>(l_length) TO <l_fs>.

WRITE / <l_fs> COLOR COL_NEGATIVE.

ENDSELECT.

ENDFORM.

Page 427: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-12

Unit: Internal Tables Exercise 1 Theme: Defining Internal Tables

Soultion SAPBC411S_KEYTAB_DEFINITION *&-----------------------------------------------------------------*

*& Report SAPBC411S_KEYTAB_DEFINITION *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411s_keytab_definition .

TYPES: BEGIN OF struc,

a TYPE i,

b(1000) TYPE c,

d TYPE p,

END OF struc.

DATA: std_tab TYPE STANDARD TABLE OF struc

WITH NON-UNIQUE KEY a,

sort_tab TYPE SORTED TABLE OF struc

WITH NON-UNIQUE KEY a,

hash_tab TYPE HASHED TABLE OF struc

WITH UNIQUE KEY a.

Page 428: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-13

Unit: Internal Tables Exercise 2: Theme: Filling internal tables

Solution SAPBC411S_KEYTAB_FILL *&-----------------------------------------------------------------*

*& Report SAPBC411S_KEYTAB_FILL *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411s_keytab_fill.

* Type definition for internal tables

TYPES: BEGIN OF struc,

a TYPE i,

b(1000) TYPE c,

d TYPE p,

END OF struc.

* internal table definition

DATA: std_tab TYPE STANDARD TABLE OF struc

WITH NON-UNIQUE KEY a,

sort_tab TYPE SORTED TABLE OF struc

WITH NON-UNIQUE KEY a,

hash_tab TYPE HASHED TABLE OF struc

WITH UNIQUE KEY a.

PARAMETERS: value TYPE i.

DATA: wa TYPE struc.

Page 429: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-14

* fill internal tables

DO value TIMES.

wa-a = sy-index.

wa-b = 'interne Tabellen machen Spaß'(001).

wa-d = '100.01'.

INSERT wa INTO TABLE std_tab.

INSERT wa INTO TABLE sort_tab.

INSERT wa INTO TABLE hash_tab.

ENDDO.

Page 430: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-15

Unit: Internal Tables Exercise 3: Accessing a single entry Theme: Runtime for accessing single entries

Solution SAPBC411S_KEYTAB_READ *&-----------------------------------------------------------------*

*& Report SAPBC411S_KEYTAB_DEFINITION *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411s_keytab_definition .

* Type definition for internal tables

TYPES: BEGIN OF struc,

a TYPE i,

b(1000) TYPE c,

d TYPE p,

END OF struc.

* internal table definition

DATA: std_tab TYPE STANDARD TABLE OF struc

WITH NON-UNIQUE KEY a,

sort_tab TYPE SORTED TABLE OF struc

WITH NON-UNIQUE KEY a,

hash_tab TYPE HASHED TABLE OF struc

WITH UNIQUE KEY a.

PARAMETERS: value TYPE i, read_val TYPE i.

DATA: wa TYPE struc.

* fill internal tables

DO value TIMES.

Page 431: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-16

wa-a = sy-index.

wa-b = 'interne Tabellen machen Spaß'(001).

wa-d = '100.01'.

INSERT wa INTO TABLE std_tab.

INSERT wa INTO TABLE sort_tab.

INSERT wa INTO TABLE hash_tab.

ENDDO.

*read a line from the internal tables.

READ TABLE std_tab INTO wa WITH TABLE KEY a = read_val.

WRITE: / wa-a, wa-b, wa-d.

READ TABLE sort_tab INTO wa WITH TABLE KEY a = read_val.

WRITE: / wa-a, wa-b, wa-d.

READ TABLE hash_tab INTO wa WITH TABLE KEY a = read_val.

WRITE: / wa-a, wa-b, wa-d.

Page 432: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-17

Unit: ABAP Objects Exercise 1: Defining and Implementing Classes Theme: Classes

Solution SAPBC411S_OO_CREATE_CLASS REPORT oo_interfaces_1 NO STANDARD PAGE HEADING.

********************************************************************

* Simple example for classes definition and implementation.

********************************************************************

CLASS c_ship DEFINITION.

PUBLIC SECTION.

* methods/interfaces will be defined later

PRIVATE SECTION.

DATA: ship_speed TYPE i.

DATA: max_speed TYPE i VALUE 30.

DATA: id TYPE i.

CLASS-DATA: inst_id TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.

PUBLIC SECTION.

* methods/interfaces will be defined later

PRIVATE SECTION.

DATA: truck_speed TYPE i.

DATA: max_speed TYPE i VALUE 10.

CLASS-DATA: inst_id TYPE i.

ENDCLASS.

Page 433: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-18

********************************************************************

* Implementations

********************************************************************

CLASS c_ship IMPLEMENTATION.

* here all METHOD will be implemented

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.

* here all METHOD will be implemented

ENDCLASS.

********************************************************************

* Program

********************************************************************

START-OF-SELECTION.

Page 434: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-19

Unit: ABAP Objects Exercise 2: Creating Instances, Defining, Implementing, and Calling Methods Theme: Instances and Methods

Solution SAPBC411S_OO_OBJECTS_METHODS REPORT sapbc411s_oo_object_method NO STANDARD PAGE HEADING.

********************************************************************

* Simple example for classes definition/implementation with methods

********************************************************************

CLASS c_ship DEFINITION.

PUBLIC SECTION.

New parts are marked bold and italic

METHODS constructor. "Is called automatically in Rel. 4.5A in "CREATE OBJECT

METHODS speed_up.

METHODS stop.

METHODS write.

PRIVATE SECTION.

DATA: ship_speed TYPE i.

DATA: max_speed TYPE i VALUE 30.

DATA: id TYPE i.

CLASS-DATA: inst_id TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.

PUBLIC SECTION.

Page 435: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-20

METHODS constructor. "Is called automatically in Rel. 4.5A "in CREATE OBJECT

METHODS speed_up.

METHODS stop.

METHODS write.

PRIVATE SECTION.

DATA: truck_speed TYPE i.

DATA: max_speed TYPE i VALUE 10.

DATA: id TYPE i.

CLASS-DATA: inst_id TYPE i.

ENDCLASS.

********************************************************************

* Implementations

********************************************************************

CLASS c_ship IMPLEMENTATION.

METHOD constructor.

inst_id = inst_id + 1.

id = inst_id.

max_speed = 30.

ENDMETHOD.

METHOD speed_up.

CHECK ship_speed < max_speed.

ship_speed = ship_speed + 10.

ENDMETHOD.

METHOD stop.

ship_speed = 0.

ENDMETHOD.

METHOD write.

WRITE: / 'Ship: ID = ', id, ' Speed = ', ship_speed.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.

METHOD constructor.

Page 436: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-21

inst_id = inst_id + 1.

id = inst_id.

max_speed = 130.

ENDMETHOD.

METHOD speed_up.

CHECK truck_speed < max_speed.

truck_speed = truck_speed + 50.

ENDMETHOD.

METHOD stop.

truck_speed = 0.

ENDMETHOD.

METHOD write.

WRITE: / 'Truck: ID = ', id, ' Speed = ', truck_speed.

ENDMETHOD.

ENDCLASS.

********************************************************************

* Program

********************************************************************

START-OF-SELECTION.

DATA oship TYPE REF TO c_ship.

DATA otruck TYPE REF TO c_truck.

DATA ship_tab TYPE REF TO c_ship OCCURS 0.

DATA truck_tab TYPE REF TO c_truck OCCURS 0.

*-------------------------------------------------------------------

*--- create some instances (ID is set automatically).

DO 2 TIMES.

CREATE OBJECT oship.

CALL METHOD oship->constructor.

APPEND oship TO ship_tab.

ENDDO.

DO 2 TIMES.

CREATE OBJECT otruck.

CALL METHOD otruck->constructor.

APPEND otruck TO truck_tab.

ENDDO.

Page 437: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-22

*---- speed up and write

LOOP AT ship_tab INTO oship.

CALL METHOD oship->speed_up.

CALL METHOD oship->write.

ENDLOOP.

LOOP AT truck_tab INTO otruck.

CALL METHOD otruck->speed_up.

CALL METHOD otruck->write.

ENDLOOP.

Page 438: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-23

Unit: ABAP Objects Exercise 3: Defining, Implementing, and Using Interfaces Theme: Interfaces

Solution SAPBC411S_OO_INTERFACES REPORT sapbc411s_oo_interfaces NO STANDARD PAGE HEADING.

********************************************************************

* Simple example of interfaces

********************************************************************

new parts are marked bold, italic

INTERFACE i_vehicle.

DATA: id TYPE i READ-ONLY.

METHODS: speed_up,

write,

stop.

ENDINTERFACE.

*-------------------------------------------------------------------

CLASS c_ship DEFINITION.

PUBLIC SECTION.

METHODS constructor. "Is called automatically in Rel. 4.5A "in CREATE OBJECT

INTERFACES i_vehicle.

PRIVATE SECTION.

DATA ship_speed TYPE i.

DATA: max_speed type i.

CLASS-DATA: inst_id TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.

PUBLIC SECTION.

Page 439: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-24

METHODS constructor. "Is called automatically in Rel. 4.5A "in CREATE OBJECT

INTERFACES i_vehicle.

PRIVATE SECTION.

DATA truck_speed TYPE i.

DATA: max_speed type i.

CLASS-DATA: inst_id TYPE i.

ENDCLASS.

********************************************************************

* Implementations

********************************************************************

CLASS c_ship IMPLEMENTATION.

METHOD constructor.

inst_id = inst_id + 1.

i_vehicle~id = inst_id.

max_speed = 30.

ENDMETHOD.

METHOD i_vehicle~speed_up.

CHECK ship_speed < max_speed.

ship_speed = ship_speed + 10.

ENDMETHOD.

METHOD i_vehicle~stop.

ship_speed = 0.

ENDMETHOD.

METHOD i_vehicle~write.

WRITE: / 'Ship: ID = ', i_vehicle~id, ' Speed = ', ship_speed.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.

METHOD constructor.

inst_id = inst_id + 1.

id = inst_id.

max_speed = 130.

Page 440: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-25

ENDMETHOD.

METHOD i_vehicle~speed_up.

CHECK truck_speed < speed.

truck_speed = truck_speed + 50.

ENDMETHOD.

METHOD i_vehicle~stop.

truck_speed = 0.

ENDMETHOD.

METHOD i_vehicle~write.

WRITE: / 'Truck: ID = ', i_vehicle~id, ' Speed = ', truck_speed.

ENDMETHOD.

ENDCLASS.

********************************************************************

* Program

********************************************************************

START-OF-SELECTION.

DATA oship TYPE REF TO c_ship.

DATA otruck TYPE REF TO c_truck.

DATA ivehicle TYPE REF TO i_vehicle.

DATA veh_tab TYPE REF TO i_vehicle OCCURS 0.

*----------------------------------------

*--- create some instances (ID is set automatically).

DO 2 TIMES.

CREATE OBJECT oship.

CALL METHOD oship->constructor.

APPEND oship TO veh_tab.

ENDDO.

DO 2 TIMES.

CREATE OBJECT otruck.

CALL METHOD otruck->constructor.

APPEND otruck TO veh_tab.

ENDDO.

*---- speed up and write

LOOP AT veh_tab INTO ivehicle.

Page 441: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-26

CALL METHOD ivehicle->speed_up.

CALL METHOD ivehicle->speed_up.

CALL METHOD ivehicle->write.

CALL METHOD ivehicle->stop.

CALL METHOD ivehicle->write.

SKIP.

ENDLOOP.

Page 442: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-27

Unit: ABAP Objects Exercise 4: Defining, Implementing, Handling, and Registering Events Theme: Events

Solution SAPBC411S_OO_EVENTS Refer to the program for the definition of the screen REPORT sapbc411s_oo_events NO STANDARD PAGE HEADING.

INCLUDE <list>.

********************************************************************

* Declarations

********************************************************************

new parts are marked bold

INTERFACE i_vehicle.

DATA max_speed TYPE i.

EVENTS: speed_change EXPORTING value(new_speed) TYPE i.

METHODS: speed_up,

stop.

ENDINTERFACE.

*-------------------------------------------------------------------

CLASS c_ship DEFINITION.

PUBLIC SECTION.

METHODS constructor. "Is called automatically in Rel. 4.5A "in CREATE OBJECT

INTERFACES i_vehicle.

PRIVATE SECTION.

* ALIASES max FOR i_vehicle~max_speed. "Rel. 4.5A

DATA ship_speed TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

Page 443: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-28

CLASS c_truck DEFINITION.

PUBLIC SECTION.

METHODS constructor. "Is called automatically in Rel. 4.5A "in CREATE OBJECT

INTERFACES i_vehicle.

PRIVATE SECTION.

* ALIASES max FOR i_vehicle~max_speed. "Rel. 4.5A

DATA truck_speed TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS status DEFINITION.

PUBLIC SECTION.

CLASS-EVENTS button_clicked EXPORTING value(fcode) LIKE sy-ucomm.

CLASS-METHODS: class_constructor, "Is called automatically in "Rel. 4.5A in CREATE OBJECT

user_action.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list DEFINITION.

PUBLIC SECTION.

METHODS: fcode_handler FOR EVENT button_clicked OF status

IMPORTING fcode,

list_change FOR EVENT speed_change OF i_vehicle

IMPORTING new_speed,

list_output.

PRIVATE SECTION.

DATA: id TYPE i,

ref_ship TYPE REF TO c_ship,

ref_truck TYPE REF TO c_truck,

BEGIN OF line,

id TYPE i,

flag,

iref TYPE REF TO i_vehicle,

Page 444: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-29

speed TYPE i,

END OF line,

list LIKE SORTED TABLE OF line WITH UNIQUE KEY id.

ENDCLASS.

********************************************************************

* Implementations

********************************************************************

CLASS c_ship IMPLEMENTATION.

METHOD constructor.

i_vehicle~max_speed = 30.

ENDMETHOD.

METHOD i_vehicle~speed_up.

CHECK ship_speed < i_vehicle~max_speed.

ship_speed = ship_speed + 10.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = ship_speed.

ENDMETHOD.

METHOD i_vehicle~stop.

CHECK ship_speed > 0.

ship_speed = 0.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = ship_speed.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.

METHOD constructor.

max = 150.

ENDMETHOD.

METHOD i_vehicle~speed_up.

CHECK truck_speed < ivehicle~max_speed.

truck_speed = truck_speed + 50.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = truck_speed.

ENDMETHOD.

METHOD i_vehicle~stop.

Page 445: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-30

CHECK truck_speed > 0.

truck_speed = 0.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = truck_speed.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS status IMPLEMENTATION.

METHOD class_constructor.

SET PF-STATUS 'VEHICLE'.

WRITE 'Click a button!'.

ENDMETHOD.

METHOD user_action.

RAISE EVENT button_clicked EXPORTING fcode = sy-ucomm.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list IMPLEMENTATION.

METHOD fcode_handler.

CLEAR line.

CASE fcode.

WHEN 'CREA_SHIP'.

id = id + 1.

CREATE OBJECT ref_ship. CALL METHOD ref_ship->constructor.

line-id = id.

line-flag = 'S'.

line-iref = ref_ship.

APPEND line TO list.

WHEN 'CREA_TRUCK'.

id = id + 1.

CREATE OBJECT ref_truck. CALL METHOD ref_truck->constructor.

line-id = id.

line-flag = 'T'.

line-iref = ref_truck.

Page 446: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-31

APPEND line TO list.

WHEN 'SPEED_UP'.

CHECK sy-lilli > 0. "absolute line number in list

READ TABLE list INDEX sy-lilli INTO line.

CALL METHOD line-iref->speed_up.

WHEN 'STOP'.

LOOP AT list INTO line.

CALL METHOD line-iref->stop.

ENDLOOP.

WHEN 'CANCEL'.

LEAVE PROGRAM.

ENDCASE.

CALL METHOD list_output.

ENDMETHOD.

METHOD list_change.

line-speed = new_speed.

MODIFY TABLE list FROM line.

ENDMETHOD.

METHOD list_output.

sy-lsind = 0. "List level

SET TITLEBAR 'TIT'.

LOOP AT list INTO line.

IF line-flag = 'S'.

WRITE / icon_ws_ship AS ICON.

ELSEIF line-flag = 'T'.

WRITE / icon_ws_truck AS ICON .

ENDIF.

WRITE: 'Speed = ', line-speed.

ENDLOOP.

ENDMETHOD.

ENDCLASS.

********************************************************************

* Global data of program

********************************************************************

DATA list TYPE REF TO c_list.

********************************************************************

* Program events

Page 447: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-32

********************************************************************

START-OF-SELECTION.

CREATE OBJECT list.

SET HANDLER: list->fcode_handler,

list->list_change FOR ALL INSTANCES.

*-------------------------------------------------------------------

AT USER-COMMAND.

CALL METHOD status=>user_action.

*************************************************************

Page 448: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-33

Unit: ABAP Objects Exercise 5: Defining, Implementing, Handling, and Registering Events Theme: Logging with Events

Solution SAPBC411S_OO_EVENT_PROTOCOLL Refer to the program for the screen definition REPORT sapbc411s_oo_event_protokoll NO STANDARD PAGE HEADING.

INCLUDE <list>.

********************************************************************

* Declarations

********************************************************************

INTERFACE i_vehicle.

DATA max_speed TYPE i.

EVENTS: speed_change EXPORTING value(new_speed) TYPE i.

METHODS: speed_up,

stop.

ENDINTERFACE.

*-------------------------------------------------------------------

CLASS c_ship DEFINITION.

PUBLIC SECTION.

METHODS constructor.

INTERFACES i_vehicle.

PRIVATE SECTION.

* ALIASES max FOR i_vehicle~max_speed. "Rel 4.5A

DATA ship_speed TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck DEFINITION.

Page 449: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-34

PUBLIC SECTION.

METHODS constructor.

INTERFACES i_vehicle.

PRIVATE SECTION.

* ALIASES max FOR i_vehicle~max_speed. "Rel 4.5A

DATA truck_speed TYPE i.

ENDCLASS.

*-------------------------------------------------------------------

CLASS status DEFINITION.

PUBLIC SECTION.

CLASS-EVENTS button_clicked EXPORTING value(fcode) LIKE sy-ucomm.

CLASS-METHODS: class_constructor,

user_action.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list DEFINITION.

PUBLIC SECTION.

METHODS: fcode_handler FOR EVENT button_clicked OF status

IMPORTING fcode,

list_change FOR EVENT speed_change OF i_vehicle

IMPORTING new_speed,

list_output.

PRIVATE SECTION.

DATA: id TYPE i,

ref_ship TYPE REF TO c_ship,

ref_truck TYPE REF TO c_truck,

BEGIN OF line,

id TYPE i,

flag,

iref TYPE REF TO i_vehicle,

speed TYPE i,

END OF line,

list LIKE SORTED TABLE OF line WITH UNIQUE KEY id.

ENDCLASS.

********************************************************************

Page 450: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-35

* Protocoll by event handling

****** PROTOCOLL MODIFICATION ******

CLASS c_protocoll DEFINITION.

PUBLIC SECTION.

CLASS-METHODS: fcode_handler FOR EVENT button_clicked OF status

IMPORTING fcode.

CLASS-METHODS: write_protocoll.

CLASS-DATA: protocoll_written TYPE i READ-ONLY.

PRIVATE SECTION.

CLASS-DATA fcode_tab LIKE sy-ucomm OCCURS 0.

ENDCLASS.

CLASS c_protocoll IMPLEMENTATION.

METHOD fcode_handler. "-- Arg: fcode

APPEND fcode TO fcode_tab.

ENDMETHOD.

METHOD write_protocoll.

DATA comm LIKE sy-ucomm.

LOOP AT fcode_tab INTO comm.

WRITE: / comm.

ENDLOOP.

protocoll_written = 1.

ENDMETHOD.

ENDCLASS.

****** PROTOCOLL MODIFICATION END ******

********************************************************************

* Implementations

********************************************************************

CLASS c_ship IMPLEMENTATION.

METHOD constructor.

i_vehicle~max_speed = 30.

ENDMETHOD.

METHOD i_vehicle~speed_up.

CHECK ship_speed < i_vehicle~max_speed.

ship_speed = ship_speed + 10.

RAISE EVENT i_vehicle~speed_change

Page 451: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-36

EXPORTING new_speed = ship_speed.

ENDMETHOD.

METHOD i_vehicle~stop.

CHECK ship_speed > 0.

ship_speed = 0.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = ship_speed.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_truck IMPLEMENTATION.

METHOD constructor.

i_vehicle~max_speed = 150.

ENDMETHOD.

METHOD i_vehicle~speed_up.

CHECK truck_speed < i_vehicle~max_speed.

truck_speed = truck_speed + 50.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = truck_speed.

ENDMETHOD.

METHOD i_vehicle~stop.

CHECK truck_speed > 0.

truck_speed = 0.

RAISE EVENT i_vehicle~speed_change

EXPORTING new_speed = truck_speed.

ENDMETHOD.

ENDCLASS.

*-------------------------------------------------------------------

CLASS status IMPLEMENTATION.

METHOD class_constructor.

SET PF-STATUS 'VEHICLE'.

WRITE 'Click a button!'.

ENDMETHOD.

METHOD user_action.

RAISE EVENT button_clicked EXPORTING fcode = sy-ucomm.

ENDMETHOD.

Page 452: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-37

ENDCLASS.

*-------------------------------------------------------------------

CLASS c_list IMPLEMENTATION.

METHOD fcode_handler.

CLEAR line.

CASE fcode.

WHEN 'CREA_SHIP'.

id = id + 1.

CREATE OBJECT ref_ship. CALL METHOD ref_ship->constructor.

line-id = id.

line-flag = 'C'.

line-iref = ref_ship.

APPEND line TO list.

WHEN 'CREA_TRUCK'.

id = id + 1.

CREATE OBJECT ref_truck. CALL METHOD ref_truck->constructor.

line-id = id.

line-flag = 'T'.

line-iref = ref_truck.

APPEND line TO list.

WHEN 'SPEED_UP'.

CHECK sy-lilli > 0. "absolut line number in list

READ TABLE list INDEX sy-lilli INTO line.

CALL METHOD line-iref->speed_up.

WHEN 'STOP'.

LOOP AT list INTO line.

CALL METHOD line-iref->stop.

ENDLOOP.

WHEN 'CANCEL'.

********* PROTOLL MODIFCATION ****

IF c_protocoll=>protocoll_written = 1.

LEAVE PROGRAM.

ENDIF.

CALL METHOD c_protocoll=>write_protocoll.

STOP.

ENDCASE.

****** PROTOCOLL MODIFICATION END ******

Page 453: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-38

CALL METHOD list_output.

ENDMETHOD.

METHOD list_change.

line-speed = new_speed.

MODIFY TABLE list FROM line.

ENDMETHOD.

METHOD list_output.

sy-lsind = 0. "List level

SET TITLEBAR 'TIT'.

LOOP AT list INTO line.

IF line-flag = 'C'.

WRITE / icon_ws_ship AS ICON.

ELSEIF line-flag = 'T'.

WRITE / icon_ws_truck AS ICON .

ENDIF.

WRITE: 'Speed = ', line-speed.

ENDLOOP.

ENDMETHOD.

ENDCLASS.

********************************************************************

* Global data of program

********************************************************************

DATA list TYPE REF TO c_list.

********************************************************************

* Program events

********************************************************************

START-OF-SELECTION.

CREATE OBJECT list.

SET HANDLER: list->fcode_handler,

list->list_change FOR ALL INSTANCES.

****** PROTOCOLL MODIFICATION ******

Page 454: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-39

*--- extension for protocoll of commands

SET HANDLER: c_protocoll=>fcode_handler.

****** PROTOCOLL MODIFICATION END ******

*-------------------------------------------------------------------

AT USER-COMMAND.

CALL METHOD status=>user_action.

********************************************************************

Page 455: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-40

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

Model solution context C_GEOGR_DISTANC: See definition in the Context Builder (Transaction SE33) Modules used: Name Type Name . DISTANCE Function module

Context_demo_compute_distance

C_GEOGR_INFORMATION Context C_GEOGR_INFORMATION

Module Distance Parameters I/O Fieldname . Longitude1 I Longitude

Lattitude1 I Lattitude

Longitude2 I Longitude_1

Lattitude2 I Latitude_1

Distance O Distance

*Anmerkung: Note the parameters are the import parameters of the function module Context_demo_compute_distance. The field names are those used in the context, and are also those that you will use in the SUPPLY and DEMAND statements in exercise 2.

Page 456: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-41

ModuleC_Geogr_Information Parameters I/O Field names Cityfrom I City

Countryfrom I Country

Cityto I City_1

Countryto I Country_1

Latitudefrom O Latitude

Longitudefrom O Longitude

Latitudeto O Latitude_1

Longitudeto O Longitude_1

*Note: These paraemters are the input/output parameters of the modules of context C_Geogr_Information. The field names are those used in the current context, and are those that you will use in the SUPPLY and DEMAND statements in the second exercise.

Page 457: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-42

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

Model solution SAPBC411S_CONTEXT_GEOGR_DISTANC *&-----------------------------------------------------------------*

*& Report SAPBC411S_CONTEXT_GEOGR_DISTAN *

*& *

*&-----------------------------------------------------------------*

*& This Report demands the geographical latitude and longitude * of two cities from a context

*& Error messages from the context are dealt with in the * program.

*&-----------------------------------------------------------------*

*&-----------------------------------------------------------------*

*& Include BC411_DCONTEXT_GEOGR_DISTANCE *

*& *

*&-----------------------------------------------------------------*

* Begin of TOP Include

program zbc411s_context_geogr_distatop.

include <list>. "includes include <symbol> und include

"<icon>

contexts: c_geogr_distanc.

types context_typ type context_t_c_geogr_distanc.

data: latitudefrom type context_typ-latitude,

longitudefrom type context_typ-longitude,

Page 458: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-43

latitudeto type context_typ-latitude,

longitudeto type context_typ-longitude,

distance like latitudefrom.

*

parameters: p_cityfr type context_typ-city default 'FRANKFURT',

p_counfr type context_typ-country default 'DE',

p_cityto type context_typ-city default 'NEW YORK',

p_counto type context_typ-country default 'US'.

*

data: geogr_distance_inst1 type context_c_geogr_distanc.

data itab like symsg occurs 0 with header line.

* End of TOP Include

* Begin of main program

include zbc411s_context_geogr_distatop.

start-of-selection.

perform get_data.

if sy-subrc <> 0.

perform write_mess.

else.

perform write_data.

endif.

form get_data.

supply city = p_cityfr

country = p_counfr

city_1 = p_cityto

country_1 = p_counto

to context geogr_distance_inst1.

demand longitude = longitudefrom

latitude = latitudefrom

longitude_1 = longitudeto

latitude_1 = latitudeto

Page 459: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-44

distance = distance

from context geogr_distance_inst1 messages into itab.

endform.

form write_mess.

sy-tvar0 = 'With error handling'(007).

write: 'Display error message from internal table'(006).

loop at itab.

write: / itab-msgty, itab-msgid, itab-msgno,

itab-msgv1, itab-msgv2.

endloop.

endform.

*output

form write_data.

write: /(20) 'City'(001) color 1, '|',

(22) 'Longitude'(002) color 1, '|',

(22) 'Latitude'(003) color 1, '|'.

uline.

write: / p_cityfr color 4, '|',

longitudefrom color 2, '|',

latitudefrom color 2,'|'.

write: / p_cityto color 4, '|',

longitudeto color 2, '|',

latitudeto color 2,'|'.

uline.

format color 3.

write /72 ' '.

write: 1(20) 'Distance'(004), '|', (21) distance, (32) 'km'.

endform.

Page 460: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-45

Unit: ABAP Open SQL Exercise 1: Reading all flights for one year Theme: Runtime of a single access

Solution SAPBC411S_FLIGHTS_OF_ONE_YEAR *&------------------------------------------------------------------

*& Report SAPBC411S_FLIGHT_OF_ONE_YEAR * *

*&-----------------------------------------------------------------

REPORT sapbc411s_fligts_of_one_year .

PARAMETERS: param1(4) DEFAULT '1998'.

DATA: wa_sflight LIKE sflight.

DATA: BEGIN OF search_string,

param(4),

rest VALUE '%',

END OF search_string.

DATA: t1 TYPE i, t2 TYPE i.

GET RUN TIME FIELD t1.

SELECT * FROM sflight INTO wa_sflight.

CHECK wa_sflight-fldate(4) = param1.

* WRITE: / wa_sflight-carrid, wa_sflight-connid.

ENDSELECT.

GET RUN TIME FIELD t1.

WRITE: / 'SELECT ... CHECK:'(001), t1, Number:'(002), sy-dbcnt.

Page 461: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-46

search_string-param = param1.

GET RUN TIME FIELD t1.

SELECT * FROM sflight INTO wa_sflight

WHERE fldate LIKE search_string.

* WRITE: / wa_sflight-carrid, wa_sflight-connid.

ENDSELECT.

GET RUN TIME FIELD t2.

t2 = t2 - t1.

WRITE: / 'SELECT ... WHERE:'(003), t2, Number:'(002), sy-dbcnt.

Page 462: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-47

Unit: ABAP Open SQL Exercise 2: Reading the first 10 flights Theme: Using data selectively

Solution SAPBC411S_READ_10_FLIGHTS *&-----------------------------------------------------------------*

*& Report SAPBC411S_READ_10_FLIGHTS *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411s_read_10_flights .

DATA: t1 TYPE i, t2 TYPE i.

DATA: BEGIN OF wa,

carrid LIKE sbook-carrid,

connid LIKE sbook-connid,

END OF wa.

GET RUN TIME FIELD t1.

SELECT carrid connid INTO wa FROM sbook

WHERE carrid ='LH' .

IF sy-dbcnt > 10.

EXIT.

ENDIF.

* WRITE: / wa-carrid, wa-connid.

ENDSELECT.

GET RUN TIME FIELD t1.

WRITE: / 'SELECT ... IF sy-dbcnt > 10'(001), Time:'(002), t1.

GET RUN TIME FIELD t1.

SELECT carrid connid FROM sbook INTO wa

UP TO 10 ROWS WHERE carrid = 'LH'.

* WRITE: / wa-carrid, wa-connid.

Page 463: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-48

ENDSELECT.

GET RUN TIME FIELD t2.

t2 = t2 - t1.

WRITE: / 'SELECT ... UP TO 10 ROWS:'(003),Time:'(002), t2.

Page 464: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-49

Unit: ABAP Open SQL Exercise 3: Calculating sums Theme: Using aggregate functions

Solution SAPBC411S_CUMULATE_LOCCURAM *&-----------------------------------------------------------------*

*& Report SAPBC411D_CUMULATE_LOCCURAM *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411d_cumulate_loccuram .

DATA: wa_loccuram LIKE sbook-loccuram.

DATA: wa_loccurkey LIKE sbook-loccurkey.

DATA: sum TYPE sbook-loccuram.

DATA: t1 TYPE i, t2 TYPE i.

*-slow version-----------------------------------------------------

GET RUN TIME FIELD t1.

sum = 0.

SELECT loccuram wunit FROM sbook INTO (wa_loccuram, wa_loccurkey)

WHERE fldate LIKE '1998%'.

sum = sum + wa_loccuram.

ENDSELECT.

GET RUN TIME FIELD t1.

WRITE: / 'Total revenue'(002), sum CURRENCY wa_loccurkey.

WRITE: / 'Entries read'(001), sy-dbcnt, 'Time:'(003), t1.

SKIP 3.

Page 465: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-50

*-fast version -----------------------------------------------------

sum = 0.

GET RUN TIME FIELD t1.

SELECT SUM( loccuram ) INTO (sum)

FROM sbook WHERE fldate LIKE '1998%'.

GET RUN TIME FIELD t2.

t2 = t2 - t1.

WRITE: / 'Total revenue'(002), sum CURRENCY wa_loccurkey.

WRITE: / 'Entries read'(001), sy-dbcnt, 'Time:'(003), t2.

Page 466: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-51

Unit: ABAP Open SQL Exercise 4: Reading from more than one table Theme: Join

Solution SAPBC411S_SEL_SFLIGHT_SBOOK &------------------------------------------------------------------*

& Report SAPBC411D_SEL_SFLIGHT_SBOOK *

& *

&------------------------------------------------------------------*

REPORT sapbc411s_sel_sflight_sbook .

TYPES: BEGIN OF t_flight_book,

carrid TYPE sbook-carrid,

connid TYPE sbook-connid,

fldate TYPE sbook-fldate,

price TYPE sflight-price,

currency TYPE sflight-currency,

paymentsum TYPE sflight-paymentsum,

bookid TYPE sbook-bookid,

customid TYPE sbook-customid,

END OF t_flight_book.

DATA: it_fb TYPE t_flight_book OCCURS 0 WITH HEADER LINE.

DATA: t1 TYPE i, t2 TYPE i.

GET RUN TIME FIELD t1.

SELECT carrid connid fldate price currency paymentsum

FROM sflight

INTO (it_fb-carrid, it_fb-connid, it_fb-fldate,

it_fb-price, it_fb-currency, it_fb-paymentsum).

SELECT bookid customid

FROM sbook

INTO (it_fb-bookid, it_fb-customid)

WHERE carrid = it_fb-carrid

Page 467: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-52

AND connid = it_fb-connid

AND fldate = it_fb-fldate.

APPEND it_fb.

ENDSELECT.

ENDSELECT.

GET RUN TIME FIELD t1.

WRITE: / 'Time (manually):'(001), 'Time:'(002), t1.

*loop at it_fb.

* WRITE: / it_fb-carrid, it_fb-connid, it_fb-fldate, it_fb-price

* CURRENCY it_fb-currency,

* it_fb-bookid, it_fb-customid.

*endloop.

GET RUN TIME FIELD t1.

SELECT f~carrid f~connid f~fldate f~price f~currency f~paymentsum

b~bookid b~customid

FROM sflight as f INNER JOIN sbook as b

ON f~carrid = b~carrid AND

f~connid = b~connid AND

f~fldate = b~fldate

INTO TABLE it_fb.

GET RUN TIME FIELD t2. t2 = t2 - t1.

WRITE: / 'Time using JOIN:'(003), 'Time:'(002), t2.

*LOOP AT it_fb.

* WRITE: / it_fb-carrid, it_fb-connid, it_fb-fldate, it_fb-price,

* currency it_fb-currency

* it_fb-bookid, it_fb-customid.

*ENDLOOP.

WRITE: 'sy-dbcnt', sy-dbcnt.

Page 468: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-53

Unit: ABAP Open SQL Exercise 5: Reading extreme values Theme: Subquery

Solution SAPBC411S_SELECT_SUBQUERY *&-----------------------------------------------------------------*

*& Report SAPBC411D_SELECT_SUBQUERY *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411d_select_subquery.

DATA: f TYPE sflight, f1 TYPE sflight.

DATA: t1 TYPE i, t2 TYPE i.

GET RUN TIME FIELD t1.

SELECT carrid connid MAX( seatsocc ) FROM sflight

INTO (f-carrid, f-connid, f-seatsocc)

GROUP BY carrid connid

ORDER BY carrid connid.

SELECT carrid connid fldate FROM sflight

INTO (f1-carrid, f1-connid, f1-fldate)

WHERE carrid = f-carrid

AND connid = f-connid

AND seatsocc = f-seatsocc.

* WRITE: / f1-carrid, f1-connid, f1-fldate, f-seatsocc.

ENDSELECT.

ENDSELECT.

GET RUN TIME FIELD t1.

WRITE: / 'Time with nesting:'(001), t1.

GET RUN TIME FIELD t1.

Page 469: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-54

SELECT carrid connid fldate seatsocc FROM sflight as f

INTO (f-carrid, f-connid, f-fldate, f-seatsocc)

WHERE seatsocc =

( select MAX( seatsocc ) FROM sflight

WHERE carrid = f~carrid

AND connid = f~connid )

ORDER BY carrid connid fldate.

* WRITE: / f-carrid, f-connid, f-fldate, f-seatsocc.

ENDSELECT.

GET RUN TIME FIELD t2. t2 = t2 - t1.

WRITE: / 'Time with subquery:'(002), t2.

WRITE: / 'sy-dbcnt', sy-dbcnt.

Page 470: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-55

Unit: ABAP Open SQL Exercise 6: Reading grouped data with conditions Theme: HAVING clause

Solution SAPBC411S_SELECT_HAVING *&-----------------------------------------------------------------*

*& Report SAPBC411S_SELECT_HAVING *

*& *

*&-----------------------------------------------------------------*

REPORT sapbc411s_select_having.

DATA: t1 TYPE i, t2 TYPE i.

DATA: count TYPE i, max TYPE i.

DATA: connid TYPE sbook-connid.

DATA: fldate TYPE sbook-fldate.

DATA: avg TYPE f.

* SELECT and CHECK--------------------------------------------------

GET RUN TIME FIELD t1.

SELECT connid fldate COUNT(*) AVG( luggweight )

INTO (connid, fldate, count, avg)

FROM sbook

WHERE carrid = 'LH'

AND fldate > '19981201'

GROUP BY connid fldate.

CHECK avg > 2.

WRITE: / 'LH', connid, fldate, avg, count.

ENDSELECT.

WRITE: / 'sy-dbcnt:', sy-dbcnt.

GET RUN TIME FIELD t2.

t2 = t2 - t1.

WRITE: / 'Time with CHECK:'(001), 'Time:'(002), t2.

* HAVING CLAUSE-----------------------------------------------------

Page 471: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-56

GET RUN TIME FIELD t1.

SELECT connid fldate COUNT( * ) AVG( luggweight )

INTO (connid, fldate, count, avg)

FROM sbook

WHERE

carrid = 'LH' AND

fldate > '19981201'

GROUP BY connid fldate

HAVING AVG( luggweight ) > 2.

WRITE: / 'LH', connid, fldate, avg, count.

ENDSELECT.

GET RUN TIME FIELD t2.

t2 = t2 - t1.

WRITE: / 'Time with HAVING:'(003), t2.

Page 472: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-57

Unit: String processing Exercise 1: Converting the value of a type I input field into a binary string Theme: String processing

Model solution SAPBC411S_STRING_OPERATION *&------------------------------------------------------------------

*& Report SAPBC411S_STRING_OPERATION *&

*&------------------------------------------------------------------

REPORT sapbc411s_string_operation.

PARAMETERS: n TYPE i.

DATA: binstr(32) TYPE c,

digits TYPE i,

rest TYPE c,

i TYPE i.

* Decimal to binary conversion using string operations

i = n.

WHILE i <> 0.

rest = i MOD 2.

CONCATENATE rest binstr INTO binstr.

i = i DIV 2.

ADD 1 TO digits.

ENDWHILE.

IF digits < 32.

digits = 32 - digits.

SHIFT binstr RIGHT BY digits PLACES.

TRANSLATE binstr USING ' 0'.

ENDIF.

Page 473: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-58

WRITE: / 'Decimal to binary conversion using string operations:'(005),

/ 'Decimal:'(002), n LEFT-JUSTIFIED,

/ 'binary:(003) '(004), binstr.

Page 474: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 20-59

Unit: Bit processing Exercise 1: Converting the value of a type I input field into a binary string Theme: Bit processing

Model solution SAPBC410S_BIT_OPERATION

*&------------------------------------------------------------------

*& Report SAPBC411S_BIT_OPERATION *&

*&------------------------------------------------------------------

REPORT sapbc411s_bit_operation.

PARAMETERS: n TYPE i.

* Decimal to binary conversion using bit operations

DATA: binstr(32) TYPE c

DATA: hex(4) TYPE x,

offs TYPE i,

b TYPE i.

CLEAR binstr WITH '0'.

hex = n.

DO 32 TIMES.

GET BIT sy-index OF hex INTO b.

IF b = 1.

offs = sy-index - 1.

binstr+offs(1) = '1'.

ENDIF.

ENDDO.

SKIP.

WRITE: / 'Decimal to binary conversion using bit operations:'(001),

/ 'Decimal:'(002), n LEFT-JUSTIFIED,

/ 'Binary:'(003), binstr.

Page 475: BC411 - Advanced ABAP Programming

© SAP AG

R

Glossary

Page 476: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 22-2

ABAP Glossary Each entry in the glossary contains a reference to the application component to which it belongs. You can use this path in the R/3 Library to find further information. For example, for more information about ABAP Dictionary, look under ABAP Workbench (application component BC-DWB).

A 0ABAP Dictionary ABAP Workbench (BC-DWB) Central and redundancy-free storage facility for all data used in the R/3 System. The ABAP Dictionary describes the logical structure of application development objects and their representation in the structures of the underlying relational database. All runtime environment components such as application programs or the database interface, get information about these objects from the ABAP Dictionary. The ABAP Dictionary is an active data dictionary and is fully integrated into the ABAP Workbench.

1ABAP Native SQL ABAP Workbench (BC-DWB) ABAP Native SQL allows you to include database-specific SQL statements in an ABAP program. Most ABAP programs containing database-specific SQL statements do not run with different databases. If different databases are involved, use Open SQL. To execute ABAP Native SQL in an ABAP program, use the statement EXEC.

2ABAP Open SQL ABAP Workbench (BC-DWB) Subset of standard SQL statements. To avoid conflicts between database tables and to keep ABAP programs independent from the database system used, SAP has generated its own set of SQL statements known as Open SQL. Using Open SQL allows you to access all database tables available in the R/3 System, regardless of the manufacturer.

3ABAP Program ABAP Workbench (BC-DWB) Program written in the ABAP programming language. An ABAP program consists of a collection of processing locks, which are processed sequentially as soon as they are called by the runtime system. There are two main kinds of ABAP program: • Report programs (ABAP reports) • Dialog programs

4ABAP Query Basis Services/Communication Interfaces (BC-SRV) ABAP Workbench tool that allows users without knowledge of the ABAP programming language, or table or field names, to define and execute their own reports. To determine the structure of reports in ABAP Query, users only have to enter texts, and select fields and options. Fields are selected from functional areas and can be assigned a sequence by numbering. There are three types of report available: • Basic lists • Statistics • Ranked lists

5ABAP Report ABAP Workbench (BC-DWB) ABAP program that reads and analyzes the data in database tables without modifying the database. ABAP report programs are defined as type '1' programs and are linked to a particular logical database. Both of these values are specified in the program attributes. When you execute an ABAP report program, you can display the resulting output list - also known as a report - on the screen or send it to a printer.

Page 477: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 22-3

6ABAP Workbench ABAP Workbench (BC-DWB) SAP's integrated graphical programming environment. The ABAP Workbench supports the development and modification of R/3 client/server applications written in ABAP. You can use the tools of the ABAP Workbench to • write ABAP code • design screens • create user interfaces • use predefined functions • get access to database information • control access to development objects • test applications for efficiency • debug applications

7Activation ABAP Workbench (BC-DWB) Process that makes an object available at runtime. When you activate an object, the system generates a load version that application programs and screens can access and use.

8Amodal Dialog Box Graphical User Interface (BC-FES-GUI) Dialog box, allowing the user to work on one screen without the previous screen first being closed.

9Application Hierarchy Business Navigator (BC-BE-NAV) Organizational tool for displaying all of the business applications in the R/3 System. The application hierarchy has a user interface similar to that of a file manager, with a hierarchical structure. You can display either the standard applications delivered with the system, or a company-specific hierarchy.

10Application Link Enabling Integration Technology ALE (CA-BFA-ALE) Application Link Enabling (ALE) refers to the creation and operation of distributed applications. The basic idea is to guarantee a distributed, but integrated, R/3 installation. This involves business-controlled message exchange with consistent data across loosely linked SAP applications. Application integration is achieved not via a central database, but via synchronous and asynchronous communication. ALE comprises the following three layers: • application services • distribution services communication services

11Application Toolbar Graphical User Interface (BC-FES-GUI) Element of the graphical user interface, The application toolbar is situated below the standard toolbar on the screen. It contains pushbuttons, which allow users quick access to application-specific functions, and occupies the whole of the primary window. Before you can assign a function to a pushbutton, you must assign it to a function key.

12Authorization Computing Center Management System (BC-CCM) Authority to perform a particular action in the R/3 System. Each authorization refers to one authorization object and defines one or more permissible values for each authorization field listed in the authorization object. Authorizations are combined in profiles which are entered in a user's master record.

13Authorization Field Computing Center Management System (BC-CCM)

Page 478: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 24-4

Element of an authorization object. In authorization objects, authorization fields represent values for individual system elements which are supposed to undergo authorization checking to verify a user's authorization.

14Authorization Object Computing Center Management System (BC-CCM) Element of the authorization concept. Authorization objects allow you to define complex authorizations. An authorization object groups together up to 10 authorization fields in an AND relationship in order to check whether a user is allowed to perform a certain action. To pass an authorization test for an object, the user must satisfy the authorization check for each field in the object.

15Authorization Profile Computing Center Management System (BC-CCM) Element of the authorization concept. An authorization profile gives a user access to the system. It contains authorizations, identified by the name of an authorization object. Users have all of the authorizations contained in each profile entered in their user master record.

B 16Batch Input Basis Services/Communications Interfaces (BC-SRV) Interface allowing you to import large amounts of data into an R/3 System. You use batch input to import legacy data into your new R/3 System, and for periodic imports of external data.

17Batch Input Session Basis Services/Communications Interfaces (BC-SRV) Set of transactions supplied with data by a program. The transactions are stored as a stack. You can then run the session later in dialog mode. The database changes are not made until you have run the session. This method allows you to import large quantities of data into an R/3 System in a short time.

C 18Change Request ABAP Workbench (BC-DWB) Information folder in the Workbench Organizer and Customizing Organizer for entering and administrating all changes to Repository objects and Customizing settings made during a development project.

19Change Request, Transportable ABAP Workbench (BC-DWB) A change request that can be transported into other systems once it has been released.

20Client Business Engineer (BC-BE) In commercial, organizational and technical terms, a self-contained unit in an R/3 System with separate master records and its own set of tables. See also the glossary entry for "logical system".

21Clipboard Graphical User Interface (BC-FES-GUI) Memory resource that stores a copy of the last information to be copied with the 'Copy' function, or cut with the 'Cut' function. You can use the 'Paste' function to copy data stored in the clipboard to the current program. The clipboard is managed by the operating system.

22Command Field Graphical User Interface (BC-FES-GUI)

Page 479: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 25-5

Input field in the standard toolbar to the right of the ENTER pushbutton. You can enter fastpaths or transaction codes in this field, to choose menu entries or call transactions respectively.

23Control Group Change ABAP Workbench (BC-DWB) Point at which the system changes from one control group to another in a report. The control group change represents a change in the value of whichever field is currently most significant. In an ABAP program, you trigger it with the AT NEW statement.

D 24Data Definition Language ABAP Workbench (BC-DWB) Language used to define all the attributes and properties of a database management system The query language SQL (Structured Query Language) consists of two kinds of statements: • DDL (data definition language) • DML (data manipulation language)

25Data Extract ABAP Workbench (BC-DWB) Sequential dataset in the memory area of a report.

26Data Manipulation Language ABAP Workbench (BC-DWB) Language for processing data in a database management system. The query language SQL (Structured Query Language) consists of two kinds of statements: • DDL (data definition language) DML (data manipulation language)

27Data Model Data Model (BC-RMC-DMO) Structured description of data objects, their attributes, and the relationships between them. There are different types of data model, depending on the types of data structure you want to define (for example, relational data model).

28Data Object ABAP Workbench (BC-DWB) Physical unit used by a program. Each data object has a certain data type, which defines how ABAP processes it. All data object occupy memory space.

29Data Type ABAP Workbench (BC-DWB) Attribute of a Data Object Data types describe the technical attributes of data objects. They are purely descriptions, and occupy no memory space.

30Database Commit ABAP Workbench (BC-DWB) In a database commit, all of the database update requests from the current logical unit of work (LUW) are written to the database. In the R/3 System, database commits are either triggered automatically or manually, using the ABAP statement COMMIT WORK (or, in Native SQL, the database-specific equivalent).

31Database Rollback ABAP Workbench (BC-DWB) If you discover an error within an LUW, you can undo all of the update requests in the LUW (that is, since the last commit) using a database rollback. In the R/3 System, database rollbacks are either triggered automatically or manually, using the ABAP statement ROLLBACK WORK (or, in Native SQL, the database-specific equivalent).

Page 480: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 27-6

32Database View ABAP Workbench (BC-DWB) A type of view in the ABAP Dictionary. Database views are implemented using an equivalent view in the underlying database system.

33Development Class ABAP Workbench (BC-DWB) Group of logically related development objects. A development class contains all the objects which must be corrected and transported as a whole. The objects which make up a transaction usually belong to one development class. Customer development classes begin with 'Y' or 'Z'.

E 34EDI IDoc Interface / Electronic Data Interchange (CA-EDI) Electronic Data Interchange. Business-to-business electronic data interchange (for example, sales documents). The business partners may be in different countries, and might be using different hardware, software, and communication services. The data is formatted according to fixed standards. In addition, SAP ALE enables companies to exchange data internally.

35Event Keyword ABAP Workbench (BC-DWB) Type of ABAP keyword. An event keyword defines a processing block in an ABAP program. The processing block is processed when the particular event occurs. Examples. GET, START-OF-SELECTION, AT SELECTION-SCREEN.

F 36Function Group ABAP Workbench (BC-DWB) Group of functions that logically belong together and use a shared program context at runtime. The function group is a container program for the function modules that it contains. Functions that work with the same data are usually all included in the same function group. Function groups are an administrative unit within the Function Builder.

37Function Module ABAP Workbench (BC-DWB) Reusable function. Function modules are external subroutines that you maintain centrally in the Function Builder, and which can be called from any ABAP program. This allows you to avoid redundancy in your coding and makes programming more efficient. Unlike normal subroutines, function modules have a defined interface.

38Functional Area Basis Services/Communications Interfaces (BC-SRV) You can use ABAP Query to define reports without any previous programming knowledge. When you create a query, you must assign it to a functional area, which determines the tables and fields that the query can use. Functional areas in ABAP Query are usually subsets of logical databases.

39Functional Group Basis Services/Communications Interfaces (BC-SRV) Element of ABAP Query A functional group is a collection of fields that forms a logical unit. You use them to provide users with a selection of fields so that he or she does not need to sort through all of the fields in a logical database in order to create a query. You must assign a field to a functional group in order for it to be used later in a query.

Page 481: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 30-7

G 40GUI Status Graphical User Interface (BC-FES-GUI) Main element of the graphical user interface. A GUI status consists of: • A menu bar with menus • A standard toolbar • An application toolbar • Functions, and function key settings

H 41Hide Area ABAP Workbench (BC-DWB) Main memory area for storing key fields of a line in a report list. If you want to select further data based on a line selection, the system can find the key fields that it requires in the hide area. You must place the key fields into the hide area yourself using the HIDE statement.

I 42Icon Graphical User Interface (BC-FES-GUI) Graphical representation of an object or functions. Icons are small colored bitmaps that are used for pushbuttons, checkboxes, and radio buttons, either with or without text. Unlike symbols, icons always have the same size, which is one of two, selected automatically by the system according to the font size.

Page 482: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 32-8

43IDES IMG (BC-BE-IMG) The R/3 International Demonstration and Education System. IDES contains several fictional companies that model the different business processes in the R/3 System. Simple user guides and sample master and transaction data allow you to simulate a wide range of scenarios. This makes IDES a useful tool for training your project team.

44Inheritance ABAP Workbench (BC-DWB) Data Modeler (BC-RMC-DMO) Passing of attributes from one data object to another. Attributes can either be passed generally (all attributes), or by copying individual characteristics. Workflow (BC-BMT-WFM) “is a” relationship between object types in which shared attributes and methods of supertypes are passed automatically to subtypes. Subtypes usually have the same key fields as the supertype, but a more wide-ranging function.

45Internal Table ABAP Workbench (BC-DWB) Temporary data structure that exists during the runtime of a program. Internal tables are one of two structured data types in ABAP. They consist of any number of table lines, each of which has the same structure. They may or may not have a header line. The header line is a structure, and serves as a work area for the internal table. The data type of the line can be either elementary or structured.

L 46List Graphical User Interface (BC-FES-GUI) Standard function in the R/3 System used to display lists.

47List Header ABAP Workbench (BC-DWB) First line of the screen in a list. The list header is often the same as the title of the program. However, you can maintain it independently of the program title.

48Logical Database ABAP Workbench (BC-DWB) Special ABAP program that combines the contents of certain database tables. You can attach a logical database to an ABAP report program as one of the program attributes. It supplies the report with a set of hierarchically-structured table lines, which can come from different database tables. This saves the programmer from having to retrieve the data him- or herself. The term “logical database” applies not only to the program, but also to the data itself.

49Logical Unit of Work ABAP Workbench (BC-DWB) Inseparable sequence of database operations, working on the all-or-nothing principle, where the operations are either all carried out, or all canceled. From the point of view of the database system, logical units of work (LUWs) are crucial to the integrity of the data in the database.

M 50Menu Graphical User Interface (BC-FES-GUI) Graphical element for choosing functions.

Page 483: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 33-9

Menus are graphical elements that present the user with a series of options, each of which triggers a function in the system. This can include opening a submenu. There are two types of menu: • Menu bars • Action menus To choose a menu entry, single-click it with the mouse, or position the cursor on it using the arrow keys and press ENTER.

51Menu Bar Graphical User Interface (BC-FES-GUI) Element of the graphical user interface. The menu bar appears directly below the title bar in the primary window. When you choose an entry in the menu bar, the system opens the corresponding action menu below the entry. You can put up to 6 menus in the menu bar, to which the system automatically adds the ‘System’ and ‘Help’ menus.

52Menu Exit ABAP Workbench (BC-DWB) Placeholder in the standard system for customers’ own menu entries. Menu exits allow you to link your own functions to menu entries reserved in the standard system as part of the enhancement concept (Transaction CMOD). You use an associated function module exit to implement the function.

53Menu Painter ABAP Workbench (BC-DWB) Development tool in the ABAP Workbench for designing the graphical user interface of an ABAP program. Each GUI consists of a title and a GUI status. The GUI status contains the following elements: • Menu bar with menus • Standard toolbar • Application toolbar Functions, assigned to function keys.

54Message Class ABAP Workbench (BC-DWB) Collection of messages that are used by a particular application. Each ABAP program is linked to a message class. The name of the class can be up to 20 characters.

55Metadata ABAP Workbench (BC-DWB) Data that describes other data. Metadata are data definitions, usually stored in a data dictionary.

56Modal Dialog Box Graphical User Interface (BC-FES-GUI) Dialog box that must be processed or canceled before the screen behind it can be processed further.

57Modification ABAP Workbench (BC-DWB) Customer-specific change to an R/3 Repository object. When you upgrade the system, you need to check, and possibly update, your modified objects.

P 58Processing Block ABAP Workbench (BC-DWB) Group of program statements that are processed together as a unit at a particular point. ABAP is an event-oriented language (the flow of a program is controlled by events). Program sections are therefore grouped into processing blocks, which are assigned to particular events. Events are triggered in the program using event keywords.

Page 484: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 33-10

A processing block consists of all of the statements between two event keywords or between an event keyword and a FORM statement.

59Program ABAP Workbench (BC-DWB) A set of statements that provides a solution to a task. A program consists of a set of statements that are interpreted and executed by a computer.

Page 485: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 36-11

Q 60Query Basis Services/ Communication Interfaces (BC-SRV) Report that users without programming expertise can generate using ABAP Query. There are three different types of query: • Basic list • Statistic Ranked list

R 61R/3 Repository ABAP Workbench (BC-DWB) Central store for development objects in the ABAP Workbench. Development objects include ABAP programs, screens, documentation, and so on.

62R/3 Repository Information System ABAP Workbench (BC-DWB) Information system that enables you to find information about al of the development objects in the R/3 System and the relationships between them. The user interface of the R/3 Repository Information System displays objects in a hierarchical structure similar to a file manager. The R/3 Repository Information allows you to: • Create lists of programs, tables, fields, data elements, and domains. • Find out where tables and fields are used in ABAP programs and screens. Display foreign key relationships.

63RFC ABAP Workbench (BC-DWB) Remote Function Call. RFC is an SAP interface protocol based on CPI-C. This simplifies the process of programming communication between systems. RFC allows you to call and execute predefined functions in a remote system. They have built-in communication control, parameter passing, and error handling.

S 64SAP Memory ABAP Workbench (BC-DWB) Global, user-specific memory. You address the SAP memory using SPA/GPA parameters.

65Screen ABAP Workbench (BC-DWB) A screen (in the sense of a 'dynpro' or DYNamic PROgram) consists of a screen and its underlying flow logic. The main components of a screen are: • attributes (e.g. screen number, next screen) • layout (the arrangement of texts, fields, and other elements) • field attributes (definition of the properties of individual fields) • flow logic (calls the relevant ABAP modules)

66Selection Screen Graphical User Interface (BC-FES-GUI) Screen in an ABAP report program.

Page 486: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 37-12

You use the selection screen to enter the selection criteria by which the system should retrieve data from the database.

67Selection Table ABAP Workbench (BC-DWB) Internal table containing selection criteria. The system creates a selection table for each SELECT-OPTIONS statement that you use in an ABAP report program. They allow you to save complex selections in a standard format.

T 68Table ABAP Workbench (BC-DWB) Tabular collection of data. The definition is stored in the ABAP Dictionary, the contents are stored in the database. A table consists of columns (sets of data values with the same type) and lines (data records). Each line of a table can be identified uniquely using a field or a combination of fields.

69Table Work Area ABAP Workbench (BC-DWB) Data object created in an ABAP program using the TABLES statement. A table work area is a structure with the same construction as the corresponding table in the ABAP Dictionary.

70Task ABAP Workbench (BC-DWB) Information carrier in the Workbench Organizer for entering and managing all changes to Repository objects and Customizing settings performed by employees within a development project. A task is assigned to a change request

71Text Symbol ABAP Workbench (BC-DWB) Text constant that you create and maintain outside programs. You use text symbols instead of text literals to make texts easier to maintain and translate. Each text symbol is identified by a three-character code.

72Title Bar Graphical User Interface (BC-FES-GUI) Element in the graphical user interface. The title bar is the top line of every primary window and dialog box in the R/3 System. It contains the title of the window, and icons that allow you to control the window size.

73Transaction ABAP Workbench (BC-DWB) A logical process in the R/3 System. From the user’s point of view, a transaction is a logical unit (for example, to generate a list of customers, change a customer’s address, create a reservation for a flight, or run a program). From the programmer’s point of view, it is a complex object, consisting of a module pool and a set of screens. You start transactions using a transaction code. After logging onto the R/3 System, there are three levels - the SAP level, work area level, and application level. A transaction is a process at application level. To start the transaction, you can either use the menus or enter a four-character transaction code. Using the transaction code saves you having to remember the menu path. Example: To start a program from the ABAP Workbench, you can either choose Tools → ABAP Workbench → ABAP Editor, or enter SE38 in the command field.

74Transaction Code ABAP Workbench (BC-DWB) Sequence of up to twenty characters that identifies an SAP transaction. When you enter a transaction code in the command field, the corresponding transaction is started in the R/3 System. For example, the transaction code SM31 identifies the transaction “Display Table”.

Page 487: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 37-13

75Transparent Table ABAP Workbench (BC-DWB) Table type in the ABAP Dictionary. You define transparent tables in the ABAP Dictionary. They are created in the database.

76Transport Request Computing Center Management System (BC-CCM) Document for copying corrections between different kinds of system. Released corrections are collected in a transport request. When you release the request, it is transported. For example, you can transport corrections from an integration system into a consolidation system.

Page 488: BC411 - Advanced ABAP Programming

(C) SAP AG BC411 39-14

77Typing ABAP Workbench (BC-DWB) Function in the ABAP Editor that enables you to avoid unnecessary type conversions in ABAP programs. When the function is called, the system analyzes the parameters in the PERFORM statements and searches in the FORM statements for formal parameters with similar technical attributes ( type and length). Whenever it finds two parameters that correspond, it suggests a type for the formal parameter in the FORM statement. You can then change your coding accordingly. 78User Group Basis Services/Communication Interfaces (BC-SRV) Object in ABAP Query. The assignment to a user group determines which queries a user is allowed to execute and/or maintain.

79User Interface ABAP Workbench (BC-DWB) Technical features and functions available to the user to exchange information with the computer system. In the R/3 System, you design the user interface in the ABAP Workbench with the Screen Painter and the Menu Painter.

V 80View ABAP Workbench (BC-DWB) Application-specific view of different tables in the ABAP Dictionary. When you create a table, you assign a key according to technical criteria. However, the key fields may be insufficient for solving certain problems, or some of them may be irrelevant. In this case, you can use a view to access part of a table or a series of tables.

W 81Web Reporting Web Basis (CA-B-WEB) WebRFC applicat allowing Internet users to access information in the R/3 System. Users can access SAP reports, display lists, and navigate through reporting trees using URLs.