Uploaded by tendo06

BC402 EN Col15 Advanced ABAP

advertisement
BC402
Advanced ABAP
.
.
PARTICIPANT HANDBOOK
INSTRUCTOR-LED TRAINING
.
Course Version: 15
Course Duration: 5 Day(s)
e-book Duration: 45 Hours 30 Minutes
Material Number: 50123878
SAP Copyrights and Trademarks
© 2016 SAP SE or an SAP affiliate company. All rights reserved.
No part of this publication may be reproduced or transmitted in any form or for any purpose
without the express permission of SAP SE or an SAP affiliate company.
SAP and other SAP products and services mentioned herein as well as their respective
logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in
Germany and other countries. Please see http://global12.sap.com/corporate-en/legal/
copyright/index.epx for additional trademark information and notices.
Some software products marketed by SAP SE and its distributors contain proprietary
software components of other software vendors.
National product specifications may vary.
These materials are provided by SAP SE or an SAP affiliate company for informational
purposes only, without representation or warranty of any kind, and SAP SE or its affiliated
companies shall not be liable for errors or omissions with respect to the materials. The only
warranties for SAP SE or SAP affiliate company products and services are those that are
set forth in the express warranty statements accompanying such products and services, if
any. Nothing herein should be construed as constituting an additional warranty.
In particular, SAP SE or its affiliated companies have no obligation to pursue any course of
business outlined in this document or any related presentation, or to develop or release any
functionality mentioned therein. This document, or any related presentation, and SAP SE’s
or its affiliated companies’ strategy and possible future developments, products, and/or
platform directions and functionality are all subject to change and may be changed by SAP
SE or its affiliated companies at any time for any reason without notice. The information in
this document is not a commitment, promise, or legal obligation to deliver any material,
code, or functionality. All forward-looking statements are subject to various risks and
uncertainties that could cause actual results to differ materially from expectations. Readers
are cautioned not to place undue reliance on these forward-looking statements, which
speak only as of their dates, and they should not be relied upon in making purchasing
decisions.
Typographic Conventions
American English is the standard used in this handbook.
The following typographic conventions are also used.
This information is displayed in the instructor’s presentation
Demonstration
Procedure
Warning or Caution
Hint
Related or Additional Information
Facilitated Discussion
User interface control
Example text
Window title
Example text
© Copyright. All rights reserved.
iii
iv
© Copyright. All rights reserved.
Contents
ix
Course Overview
1
Unit 1:
2
13
17
28
35
43
Lesson: Describing Packages and Program Types
Exercise 1: Create a Package
Lesson: Describing ABAP Data Types and Data Objects
Lesson: Selecting Data from a Single Database Table with Open SQL
Exercise 2: Develop a Simple Report
Unit 2:
44
53
60
83
Program Calls and Memory Management
Lesson: Calling Programs Synchronously
Exercise 3: Implement Program and Transaction Calls
Lesson: Describing the ABAP Runtime and Memory Management
Exercise 4: Use ABAP Memory and SAP Memory to Share Data
Between Programs
Lesson: Using Shared Objects
Exercise 5: Use Shared Objects
100
121
139
ABAP Basics
Unit 3:
140
Statements, Functions, and Expressions for Simple Data
Lesson: Explaining the Differences Between Statements, Functions,
and Expressions
Lesson: Using Numeric Data Types in Arithmetic Expressions
Exercise 6: Use Numeric Data Types and Arithmetic
Expressions
Lesson: Processing Character Strings and Byte Strings Using
Classical Options
Exercise 7: Process Character Strings
Exercise 8: Split a Character String into an Internal Table
Lesson: Processing Character Strings and Byte Strings Using
144
153
163
167
179
188
Functions and Expressions
207
208
223
231
237
250
257
265
271
Unit 4:
Internal Tables
Lesson: Using Standard, Sorted, and Hashed Tables
Exercise 9: Use a Sorted Table with Unique Key
Lesson: Using Special Techniques with Internal Tables
Exercise 10: Use Special Techniques with Internal Tables
Lesson: Using Data References and Field Symbols
Exercise 11: Use Field Symbols and Data References to Access
Internal Tables
Lesson: Using Inline Declarations and Table Expressions
Exercise 12: Use Inline Declarations and Table Expressions
© Copyright. All rights reserved.
v
285
Unit 5:
287
Lesson: Explaining the Dynamic Programming Techniques of ABAP
289
299
307
315
Lesson: Using Dynamic Statements and Dynamic Calls
Exercise 13: Implement a Dynamic Method Call
Lesson: Using Generic Data Types
Exercise 14: Use Dynamically Typed Field Symbols in Dynamic
SQL Statements
Exercise 15: Access Structure Components Dynamically
Lesson: Describing Data Types, Data Objects, and Objects at
Runtime
Exercise 16: Provide Column Headers Using RTTI
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Exercise 17: Create Data Objects at Runtime
Exercise 18: Create Data Types at Runtime with RTTC
325
335
347
359
365
375
395
Unit 6:
397
421
425
439
445
451
458
465
475
482
490
497
515
516
523
530
536
ABAP Open SQL
Lesson: Describing the Technical Background of Database Accesses
with Open SQL
Lesson: Implementing Complex WHERE Conditions and Special
INTO Clauses
Lesson: Processing and Aggregating Datasets on the Database
Exercise 19: Request Ordered and Condensed Datasets from
the Database
Exercise 20: Perform Calculations on the Database
Lesson: Selecting Data from Multiple Database Tables
Exercise 21: Implement a Join of Multiple Database Tables
Lesson: Explaining Additional Techniques for Reading from Multiple
Database Tables
Exercise 22: Implement Full Buffering and Buffering on Demand
Exercise 23: Read Additional Data with the FOR ALL ENTRIES
Addition
Lesson: Accessing Large Objects (LOBs) on the Database
Lesson: Using New Open SQL
Exercise 24: Use New Open SQL Syntax and Features
412
vi
Dynamic Programming
Unit 7:
Analysis and Testing
Lesson: Defining and Activating Checkpoints
Exercise 25: Define and Activate Checkpoints
Lesson: Using the ABAP Trace
Lesson: Using the SQL Trace
© Copyright. All rights reserved.
543
Unit 8:
Best Practices for ABAP
544
Lesson: Avoiding Common Errors in ABAP Programming
548
552
560
Lesson: Creating Readable and Easy-to-Maintain ABAP Programs
Lesson: Optimizing the Runtime of ABAP Applications
Lesson: Avoiding Slow Database Accesses
© Copyright. All rights reserved.
vii
viii
© Copyright. All rights reserved.
Course Overview
TARGET AUDIENCE
This course is intended for the following audiences:
●
Development Consultant
●
Developer
© Copyright. All rights reserved.
ix
x
© Copyright. All rights reserved.
UNIT 1
ABAP Basics
Lesson 1
Describing Packages and Program Types
Exercise 1: Create a Package
2
13
Lesson 2
Describing ABAP Data Types and Data Objects
17
Lesson 3
Selecting Data from a Single Database Table with Open SQL
Exercise 2: Develop a Simple Report
28
35
UNIT OBJECTIVES
●
Explain packages and package interfaces
●
Explain the variety of program types
●
Explain the differences between program types
●
Explain include programs
●
Type data objects
●
Use global and local data objects
●
Select data from a single database table with Open SQL
© Copyright. All rights reserved.
1
Unit 1
Lesson 1
Describing Packages and Program Types
LESSON OVERVIEW
This lesson explains the use of packages and provides information about what the program
types are and how they can be structured.
Business Example
You are a developer and your manager has asked you and your team to create a new tool in a
structured way. For this reason, you require the following knowledge:
●
An understanding of how to structure objects into packages
●
An understanding of the different types of programs
●
An understanding of the internal structure of a program
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain packages and package interfaces
●
Explain the variety of program types
●
Explain the differences between program types
●
Explain include programs
Packages and Package Interfaces
You should already have an understanding that the Repository is made up of application
components, which themselves are made up of packages.
For example, the application component Materials Management (MM), consists of several
packages containing relevant objects for a more detailed logical subdivision.
Whenever repository objects are created, they must be assigned to a package.
Basic properties of a package that you should already be familiar with include the following:
Application Component
The application component determines the location of the package within the application
hierarchy by specifying the corresponding application component.
Software Component
For customer developments, enter HOME for the software component.
Transport Layer
The transport layer determines if the objects of this package are to be transported to a
subsequent system and, if so, to which system. For customer developments, specify the
transport layer that your system administrator set up for this purpose.
2
© Copyright. All rights reserved.
Lesson: Describing Packages and Program Types
Package Type
Choose between the three package types: development package (which can contain
repository objects and other packages), main package (which can only contain other
packages), and structure package (which can only contain main packages).
Figure 1: Purpose of Packages
Additional Properties of Packages
Additional properties of packages include the following:
●
Nesting is the ability of packages to have other packages embedded in them. The top level
in the package hierarchy is formed by structure packages, generally consisting of several
main packages. The associated development packages are then created as subpackages
within each main package. This process allows the specification of the number and
granularity of subpackages, along with the depth to which they are nested.
●
Visibility is an attribute of package elements, that is, of development objects. An element
can only be used outside its own package if it is externally visible. To make an element
visible from outside the package, it needs to be included in at least one package interface.
Each element is always visible within its own package.
●
Use access is the unilateral right of a package to access the elements from the interface of
the provider package.
© Copyright. All rights reserved.
3
Unit 1: ABAP Basics
Figure 2: Additional Properties of Packages
Uses of Packages
Packages can be either server (provider) or client (user) packages. Server packages offer
services to other packages by exposing elements (function modules, Business Application
Programming Interfaces (BAPIs), classes, ABAP programs, types, and so on) into one or
more package interfaces. A server can also take on the role of client, availing itself of the
services of other packages.
Use package interfaces to specify which repository objects you want to be visible to other
packages. When you add elements to interfaces, you can group them according to semantic
or use criteria. You can also nest packages at different levels, and specify at each level
whether you want to release the elements of the interface. Finally, you can apply constraints
to the use of an interface, by naming exclusive users.
By default, all the elements in a package interface are visible to - and thus can be used by - all
the packages at the same hierarchy level. In some cases, however, the provider package may
want to restrict the use of an interface to one or more user packages. For example, an
interface might provide critical functions that could cause data inconsistencies and that can
only be used correctly by a particular package in a specific context. In such a case, it would be
undesirable for other packages to be given use access to this special interface. Provider
packages can make their interfaces available only to certain users, preventing other packages
from using them.
The nested package concept allows you to release different elements of an interface at
different levels. At each separate level of nesting from the inside outwards, you can decide
whether or not a visible element in an embedded package should remain visible to the next
level outwards. In this way, you can specify, for example, that development objects can only
be used within a main package and not between two main packages. Conversely, if you want a
visible element within a main package to be available for other main packages, you must
extend visibility over several levels until the other main packages can see it.
User packages cannot use all of the visible elements of an interface of a provider package,
unless there is use access available for it (only visibility together with use access permits use).
The package immediately surrounding the embedded package is the only package that does
not require use access for the interface, because here, use access is implicit.
4
© Copyright. All rights reserved.
Lesson: Describing Packages and Program Types
The option of ensuring that the different relationships of the repository objects are defined
correctly in accordance with the package concept rules is available with the package check.
The package check covers the static relationships between repository objects, in much the
same way as the syntax of an ABAP program or the activation of a repository object is
checked.
Note:
Package checks are always performed at the design time of the development
object, not at compile time or runtime. This means that dynamic uses of the object
(such as calling a function module) are not checked.
Package Checks
Package checks can be performed as follows:
●
Performing a package check for all objects in a package
This method includes all repository objects of a selected package in the package check.
The package check is initiated either from the Object Navigator or from the Package
Builder (SE21).
●
Performing a package check for individual objects in a package
In the Repository Browser, choose the object to be checked, open the context menu for
the node and choose Check → Package Check.
●
Call from the extended program check (transaction code SLIN).
The following system settings affect package checks:
Global Package Check Switch
This system-wide switch is activated as part of customizing. If this switch is deactivated,
there is no package check. In general, one of the following values can be selected:
●
OFF
No package check.
●
RESTRICTED
Structure packages are not considered in the package check. The package check only
takes place if the appropriate setting Package encapsulated is activated for the
package.
●
R3ENTERPRISE
The check considers structure packages on the client and server package side. This is
similar to a RESTRICTED package check but takes structure packages into account.
That is, if the client and the provider are stored in the same structure package, the
check is limited to the RESTRICTED package check. Otherwise, the system needs to
check whether or not a use relationship between the two structure packages is
allowed. If it is, the system performs the restricted package check. Otherwise, an error
message appears.
Package-Specific Settings
Package-specific settings are generally made when the package is created. You can
change them later in the Package Builder (on the Properties tab).
© Copyright. All rights reserved.
5
Unit 1: ABAP Basics
Package encapsulated: When this package property is activated, the package is referred
to as encapsulated. This setting is especially relevant for a package in the role of a server
package because it protects the package contents from unwanted use. Using this
encapsulation property, you determine the sanctions imposed during package checks if
the contents of the respective package are accessed. Development objects (contents of
the package) must first be made available through server package interfaces before they
can be accessed by a user through a use access.
Structure of ABAP programs
Figure 3: Structure of ABAP Source Code
The source code of an ABAP program consists of several parts. The ABAP program type
determines which source code parts are contained in the respective program.
The different sections which might be found in an ABAP program include the following:
●
Introductory statements
Nearly every program type has its own special introductory statement. Each program can
only have one introductory statement, which must be the first statement in the program
(after expanding any includes).
●
Global declarations
Global declarations include the declarative statements for global program data objects
(constants and variables), as well as local program data types, classes, and interfaces.
●
Implementations
This includes the implementation parts of any local classes, containing the method
implementations of these classes.
●
6
Processing blocks
© Copyright. All rights reserved.
Lesson: Describing Packages and Program Types
A processing block is an indivisible program unit that must be programmed contiguously.
The types of processing blocks are as follows:
-
ABAP event blocks
These are introduced by an event keyword and ended implicitly by keywords that
introduce the next processing block. Event blocks are called by the ABAP runtime
environment at specific times during program execution. They cannot be called in the
source code.
-
Dialog modules
These are introduced and concluded using the relevant keywords (MODULE ...
ENDMODULE). Dialog modules can only be addressed in the flow logic of a screen. They
are then called by the runtime environment when the screen is processed.
-
Procedures
These are introduced and concluded using the relevant keywords (FORM ... ENDFORM.
and FUNCTION ... ENDFUNCTION). They are reusable units that are used to modularize
the program. They are executed when they are explicitly called in a different processing
block.
Structure of ABAP Source Code
Figure 4: Structure of ABAP Source Code
The figure Structure of ABAP Source Code, displays an example of the structure of source
code in an executable program.
Introductory Statements for Programs
The introductory statement for a program depends on the corresponding program type.
© Copyright. All rights reserved.
7
Unit 1: ABAP Basics
Table 1: Introductory Statements
The following table provides the introductory statement of various program types:
PROGRAM TYPE
INTRODUCTORY STATEMENT
Executable program
REPORT name ... [MESSAGE-ID id].
Function group
FUNCTION-POOL name ...[MESSAGE-ID
id].
Module pool
PROGRAM name [MESSAGE-ID id].
Subroutine pool
No separate statement
Class pool (global class)
CLASS-POOL [MESSAGE-ID id].
Interface pool (global interface)
INTERFACE-POOL.
Type pool (Type group)
TYPE-POOL name.
When developers create new repository objects, they define a program type, which then
appears in the program attributes. When the program is created, the appropriate introductory
statement is automatically generated. For some program types, the developer can later add
the optional addition MESSAGE-ID, to specify the default message class to be used in the
program. Additions for controlling list output are also available for the REPORT and
FUNCTION-POOL statements.
Caution:
The introductory statement does not necessarily have to match the program
type in the program attributes. To avoid unexpected system behavior, when
editing, make sure that you only change the additions, not the statement itself.
Global Declarations
The global declarations you can use depend on the program type.
Table 2: Declarations Allowed for Each Program Type
The following table lists the declarations allowed for each program type:
8
PROGRAM
TYPE
LOCAL DATA CONTYPES
STANTS
GLOBAL DA- LOCAL CLASSES, LOCAL INTERTA OBJECTS FACES
Executable
program
√
√
√
√
Function
group
√
√
√
√
Module pool √
√
√
√
Subroutine
pool
√
√
√
√
Class pool
(global
class)
√
As attributes As attributes √
© Copyright. All rights reserved.
Lesson: Describing Packages and Program Types
PROGRAM
TYPE
LOCAL DATA CONTYPES
STANTS
GLOBAL DA- LOCAL CLASSES, LOCAL INTERTA OBJECTS FACES
Interface
pool (global
interface)
In interface
signature
As attributes x
x
Type pool
(type
group)
√
√
x
x
You can define local program data in all program types. For global classes, this definition is
possible in both the class signature (Types tab of the Class Builder), and the local definition
part of the class (Local Types push button). Only the first option is available for global
interfaces.
You cannot create constants in the local definition part of a class. You must define them as a
part of the signature (Attributes tab). Global interfaces and type groups are collections of
data types and constants. Therefore, they cannot contain any other data objects, local
classes, or interfaces.
Processing Blocks
Table 3: Processing Blocks Allowed in Program Types
The following table shows the different processing blocks that each program type can
contain:
PROGRAM
TYPE
ABAP EVENTS SCREENS AND SUBROUDIALOG MOD- TINES
ULES
IMPLEMENTATION OF
METHODS
Executable
program
All
√
√
√
Function group All (except reporting event
blocks)
√
√ (Only in
function
groups with
function modules)
√
Module pool
All (except reporting event
blocks)
√
√
√
Subroutine
pool
x
x
√
√
Class pool
(global class)
x
x
x
√
Interface pool
(global interface)
x
x
x
x
Type pool
(type group)
x
x
x
x
© Copyright. All rights reserved.
9
Unit 1: ABAP Basics
The strictly declarative program types, Interface-Pool, and Type-Pool, cannot contain any
processing blocks.
Subroutines are not allowed in object-oriented program types or strictly declarative type
groups.
Screens, dialog modules, and ABAP event blocks are only allowed in the conventional main
program types like executable programs (sometimes known as reports), function groups, and
module pools.
The ABAP event blocks used in the different program types have the following limitations:
●
Executable programs may contain the events LOAD-OF-PROGRAM, INITIALIZATION,
START-OF-SELECTION, GET, and END-OF-SELECTION.
●
Function groups and module pools may only contain the LOAD-OF-PROGRAM event.
Executable programs, function groups, and module pools may contain user dialogs of type
DYNPRO, selection screen, or list.
If you use any of these user dialogs, the following additional events may be used:
●
Dynpros: PROCESS BEFORE OUTPUT (PBO), PROCESS AFTER INPUT (PAI), PROCESS
ON HELP REQUEST (POH), PROCESS ON VALUE REQUEST (POV).
●
Selection screens: AT SELECTION-SCREEN OUTPUT, AT SELECTION-SCREEN.
●
Lists: TOP-OF-PAGE, END-OF-PAGE, AT LINE-SELECTION, AT USER-COMMAND, TOPOF-PAGE DURING LINE-SELECTION.
Function modules, as specific procedures, are only allowed in function groups.
Include Programs
Figure 5: Naming Convention for Includes
In the simplest cases, you can enter all required source code in a single program. You can use
include programs to organize the code in more complex programs, to make them easier to
understand and to make it possible to maintain and transport source code components
separately.
10
© Copyright. All rights reserved.
Lesson: Describing Packages and Program Types
Include programs help you to break ABAP source code into individual repository objects. An
ABAP program can be created with the program type Include Program in the program
attributes. Include programs cannot have their own introductory statements, and cannot be
generated independently in the ABAP Compiler. Instead, use INCLUDE statements to
integrate include programs into programs that can be generated.
Consider the following when creating Include Programs:
●
An include program must contain full statements.
●
An include program can integrate other include programs, but not itself.
●
The creation of new include programs is supported by the development environment for
some program types (executable programs, module pools, subroutine pools), supported
partially for others (function groups), or completely forced (class pools, interface pools).
It is recommended that you follow the naming convention for include programs, which is
shown in the figure Naming Convention for Includes.
Note:
The INCLUDE statement is the only statement that can appear at the top of a
program instead of an introductory statement. The only prerequisite is that once
the include program is expanded, an introductory statement must appear at the
top of the included program.
Hint:
You can use service report RSINCL00 to generate reference lists for include
programs.
© Copyright. All rights reserved.
11
Unit 1: ABAP Basics
12
© Copyright. All rights reserved.
Unit 1
Exercise 1
Create a Package
Business Example
You have a major development project that is logically self-contained. To structure your work,
create a package to hold all your developments.
You need to create a package and assign the repository object to a Workbench request.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
1. Create a package in the ABAP Workbenchwith name ZBC402_## and assign it to
application component CA.
2. What is the difference between an application component and a software component?
3. What is the importance of the transport layer?
© Copyright. All rights reserved.
13
Unit 1
Solution 1
Create a Package
Business Example
You have a major development project that is logically self-contained. To structure your work,
create a package to hold all your developments.
You need to create a package and assign the repository object to a Workbench request.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
1. Create a package in the ABAP Workbenchwith name ZBC402_## and assign it to
application component CA.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown list on the left of the screen, choose Package and specify
the name of the package ZBC402_##.
c) Choose Display.
A Create Pack. dialog box appears.
d) To create the package, choose Yes.
A Create Package dialog box appears.
e) In the Create Package dialog box, enter a short description for the package and the
application component and choose Continue.
f) Save the package in the transport request that your instructor specifies.
2. What is the difference between an application component and a software component?
The application component is an additional classification criterion for your applications,
and usually consists of several packages. The application component is used, for example,
as a search criterion to find development objects in the Repository Information System. In
turn, a software component contains several application components, and is the highest
classification criterion in the SAP system. The Basis system, for example, consists of the
SAP_BASIS and SAP_ABA software components. All your (customer) developments must
be assigned to software component HOME.
14
© Copyright. All rights reserved.
Lesson: Describing Packages and Program Types
3. What is the importance of the transport layer?
The transport layer determines where your development objects are transported after the
Workbench request is released. The system landscape must be configured accordingly in
the Transport Management System.
© Copyright. All rights reserved.
15
Unit 1: ABAP Basics
LESSON SUMMARY
You should now be able to:
16
●
Explain packages and package interfaces
●
Explain the variety of program types
●
Explain the differences between program types
●
Explain include programs
© Copyright. All rights reserved.
Unit 1
Lesson 2
Describing ABAP Data Types and Data Objects
LESSON OVERVIEW
This lesson discusses the type system in ABAP. It also discusses the different data types, and
where and how they are defined and used.
Business Example
You want to develop reliable, sophisticated ABAP applications. To do so, you need to
understand the data types and data objects in the ABAP programming language. For this
reason, you require the following knowledge:
●
An understanding of the type system in ABAP
●
An understanding of the advantages of global and local types
●
An understanding of the differences between flat and deep data objects
●
An understanding of the visibility and validity of data objects
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Type data objects
●
Use global and local data objects
© Copyright. All rights reserved.
17
Unit 1: ABAP Basics
Data Types and Data Objects
Figure 6: Defining Data Objects
We differentiate between data objects and data types in ABAP. Data types are mere
descriptions that are not linked with an address in the memory. Data objects are instances of
data types and occupy memory to store the specific data that a program uses at runtime.
You can define data objects in a program using the DATA statement. As shown in the figure
Defining Data Objects, the name of the data object is followed by a TYPE addition. The type is
linked to the data object statically and cannot be changed at runtime.
Other syntax variants are available (for legacy reasons). Some of these legacy variants are no
longer supported within classes.
You can declare data objects using the following:
●
Predefined ABAP types
The ABAP runtime environment provides predefined data types. Incomplete types (C, N, P,
and X) and complete types (I, F, D, T, STRING, XSTRING, DECFLOAT16, and
DECFLOAT34) are differentiated depending on whether the system requires an additional
length specification when you declare the corresponding data objects.
●
Global data types
Global data types refer to predefined Dictionary types, which largely correspond to the
predefined ABAP types.
●
Local data types
The TYPES statement defines local data types within the ABAP program. The local data
types refer to predefined ABAP types or global data types from the Dictionary.
Predefined ABAP Types
18
© Copyright. All rights reserved.
Lesson: Describing ABAP Data Types and Data Objects
Table 4: Numeric ABAP Data Types
The following table lists the numeric ABAP data types:
Data Type
Description
Length in Bytes/ Value Range
Initial Length
Decimals
I
Integer
4
0
-2,147,483,648 +2,147,483,647
P
Packed Number
1 ... 16
8
Digits:
2*Length-1
Up to 14
Decimals: up to
14
F
Binary Floating
Point Number
8
Max: +/- 1.79E
+308
16
Min: +/2.22E-308
and 0
DECFLOAT16
Decimal Floating 8
Point Number
Max: +/- 1E+385 16
Min: +/- 1E-383
and 0
DECFLOAT34
Decimal Floating 16
Point Number
Max: +/- 1E
+6145
34
Min: +/- 1E-6143
and 0
Note that data types DECFLOAT16 and DECFLOAT34 exist as of SAP NetWeaver 7.0 EhP2 as
a replacement for data type F.
The numeric ABAP data types differ in the following ways:
●
Rules for storage
●
Value range
●
Arithmetic used in calculations
Predefined ABAP Types - Character Types
Table 5: Character ABAP Types
The following table lists the character ABAP data types:
Data Type
Description
N
Sequence of dig- 0 … 0
its
© Copyright. All rights reserved.
Initial Value
Length in Bytes/ Additional InforInitial Length
mation
1 … 65535
1
LENGTH addition can be used
to specify length
if default length
of 1 not required
19
Unit 1: ABAP Basics
Data Type
Description
Initial Value
C
Sequence of
characters
Space
Date field
00000000
(YYYYMMDD)
8
000000
(HHMMSS)
6
D
T
Time field
STRING
Length in Bytes/ Additional InforInitial Length
mation
1 … 65535
LENGTH addition can be used
to specify length
if default length
of 1 not required
1
Sequence of
characters
-Length fixed
-Date calculations possible
-Length fixed
-Time calculations possible
0…
-Length variable
0
Note:
You can use character operations for data objects of all character types.
Predefined ABAP Types - Byte Types
Table 6: ABAP Byte Types
The following table lists the ABAP byte types:
Data Type
Description
X
Sequence of
00 …
bytes in hexadecimal notation
XSTRING
Sequence of
bytes in hexadecimal notation
Initial Value
Length in Bytes/ Additions
Initial Length
1 … 65535
LENGTH addition used to
specify length if
default length of
1 byte not required
1
0…
-Length variable
0
Note:
You can use byte operations for data objects of both byte types.
Predefined Data Types
The tables above list all the elementary predefined data types provided by the ABAP runtime
environment. You can use the complete types (I, F, DECFLOAT16, DECFLOAT34, D, T,
20
© Copyright. All rights reserved.
Lesson: Describing ABAP Data Types and Data Objects
STRING, and XSTRING) to type a data object directly. Supplement the incomplete types (P, N,
C, and X) with a length specification to create a complete type. You can specify the length in
the DATA or TYPES statement, usually by using the LENGTH addition. For example:
TYPE <type_name> TYPE <ABAP-Type> LENGTH <length>.
DATA <obj_name> TYPE <ABAP-Type> LENGTH <length>.
Hint:
It is also possible to specify the length in parentheses after the name of the data
object or local data type, but for reasons of legibility, it is recommended to use
the LENGTH addition instead.
TYPE <type_name>(<length>) TYPE <ABAP-Type>.
DATA <obj_name>(<length>) TYPE <ABAP-Type>.
Use the DECIMALS addition to define the number of decimal places for type P (packed
number).
The numeric data types (I, F, P, DECFLOAT16, and DECFLOAT34) differ primarily in their
value ranges, and in the arithmetic used for calculations.
The major differences among the character data types (N, C, D, and T) are as follows:
●
The characters that can be used to form the strings of these types
●
The way they are formatted when output to the screen
●
Data objects with types D and T are handled in a special way in arithmetic operations
A primary attribute of the string data type is that data objects with this type have variable
lengths. The runtime system adjusts this length to the respective contents dynamically at
runtime.
Each predefined data type has its own initial value. This type-specific initial value plays an
important role in instantiating the data objects and executing the CLEAR statement. All
numeric data types have 0 as their initial value. The character data types N, D, and T have a
sequence of character 0 as their initial value, while type C has a sequence of spaces. The
variable-length data types have length 0 in their initial state.
Generic ABAP Types
Table 7: Predefined Generic ABAP Types
The following table lists the predefined generic ABAP types:
Generic Data Type
Meaning
Compatible ABAP Types
any
Any type
All
data
Any data type
All
Elementary data type or
flat,
All
Fully generic
Elementary, flat
Simple
character-type structure
© Copyright. All rights reserved.
21
Unit 1: ABAP Basics
Generic Data Type
Meaning
Compatible ABAP Types
numeric
Numeric data type
I, F, P, DECFLOAT16, DECFLOAT34
decfloat
Numeric data type
DECFLOAT16, and DECFLOAT34
clike
Character data type
C, N, D, T, STRING
csequence
Text data type
C, and STRING
Hexadecimal
Byte data type
X, and XSTRING
Numeric
Character-type
xsequence
In addition to the predefined ABAP types, the runtime environment also provides predefined
generic types. Generic types do not completely define the attributes of a data object, and
therefore they cannot be used in the declaration of data objects.
Instead, generic types are used exclusively to type formal parameters (of subroutines,
function modules, or methods) and field symbols.
Note:
Information about the use of generic types is discussed in the context of dynamic
programming.
Data Object Categories
Table 8: Data Object Categorization
Data objects can be categorized as follows:
Type
Reference
Internal Table
Structure
Elementary Field
Deep
All
All
At least one
STRING and
deep component XSTRING
Flat
No
No
No deep compo- I, F, P, DECnents
FLOAT16, DECFLOAT34, C, N,
D, T, and X
In terms of internal structure, you can distinguish the following data object categories:
22
●
Elementary fields
●
Structures
●
Internal tables
●
References
© Copyright. All rights reserved.
Lesson: Describing ABAP Data Types and Data Objects
You can nest structures and internal tables to any number of levels. A structure that contains
other structures as its components, or even an entire internal table, is called a nested
structure.
In terms of memory requirements and memory management, you can also differentiate
between flat and deep data objects, as follows:
●
Flat data objects
Flat data objects have a static length and do not refer to other objects. All elementary data
objects apart from strings and all structures with exclusively flat components (regardless
of potential nesting) are flat.
●
Deep data objects
Deep data objects include references, strings, and internal tables. Structures are also
called deep if they contain at least one deep component, taking all includes and
substructures into account.
Literals
Figure 7: Literals
Literals are data objects that you define in the source code of a program by specifying a string
representing a value.
The ABAP runtime environment differentiates among the following types of literals:
●
Numeric literals
You can define a numeric literal as a sequence of digits in the program text, with or without
+ or - signs. A numeric literal has type I if its value lies within the value range of this type
(-2^31+1 to 2^31-1), otherwise it has type P.
●
Text field literals
© Copyright. All rights reserved.
23
Unit 1: ABAP Basics
You can define a text field literal as a character string that is enclosed in single quotation
marks (') in the program text. A text field literal can be from one to 255 characters long,
and any spaces at the end are ignored. Text field literals have type C.
●
String literals
You can define a string field literal as a character string that you enclose in back quotation
marks (`) in the program text. String literals have the type string, and their length is limited
to 255 characters. They can also have zero length. In contrast to text field literals, spaces
are not suppressed at the end of a string literal.
Hint:
To display a single quotation mark within a text field literal, you have to enter it
twice. The same applies if you enter a back quotation in a string literal. No
restrictions apply to single quotations in a string literal, or back quotations in a
text field literal.
Visibility of Data Objects in Procedural ABAP
Figure 8: Visibility of Data Objects
The extent to which data objects are visible depends on the context.
The following rules apply for data objects that are defined using the DATA statement:
●
24
If the DATA statement appears between FORM and ENDFORM, it defines a local data
object of a subroutine.
© Copyright. All rights reserved.
Lesson: Describing ABAP Data Types and Data Objects
●
If the DATA statement appears between FUNCTION and ENDFUNCTION, it defines a local
data object of a function module.
●
In all other positions, the DATA statement defines a global data object, which is visible in
the entire program.
●
If a global data object and a local data object have the same name, only the local data
object is visible within the modularization unit. In technical terms, it ignores the identically
named global data object.
Caution:
Data objects in modules and event blocks are always global. If the DATA
statement appears between MODULE and ENDMODULE, the object you define is
still a global data object that is visible in the entire program. Likewise, data
objects that you declare in an ABAP event block are visible globally.
To avoid misunderstandings, SAP recommends that you declare such data at the
start of the program, and avoid declaring DATA statements completely in
modules and event blocks.
The TABLES statement always creates data objects that are visible throughout
the program. Data objects that you create using the TABLES statement are
always visible in the entire program, even if the statement appears within a
subroutine or function module.
Visibility of Data Objects in Object-Oriented ABAP
Figure 9: Visibility Sections in Object-Oriented ABAP
If you use objects (instances of ABAP classes) in your application, the visibility of data is
determined in a different way.
© Copyright. All rights reserved.
25
Unit 1: ABAP Basics
Data objects that are defined in the declaration part of a class are called attributes.
For attributes, the visibility sections are as follows:
●
Private attributes
Private attributes are visible only within the object or class. All the methods of the object
can read and change the data. External access to these attributes is possible only when
you use a suitably defined method.
●
Public attributes
Public attributes are also visible and accessible outside of the object or class.
●
Protected attributes
Protected attributes are visible within the object or class, and also to instances of any
subclasses.
If the DATA statement appears within METHOD..ENDMETHOD, it defines a local data object in
the method.
Lifetime of Data Objects
Figure 10: Lifetime of Data Objects
The lifetime of a data object is usually linked with its visibility.
Global data objects remain valid as long as the corresponding program is in the memory.
The lifetime of object attributes begins when the object is instantiated at runtime and ends
when the last reference to the object has been deleted.
The lifetime of a local data object is usually identical to the lifetime of the surrounding
modularization unit, which means the contents of the data object are lost between two calls of
the same modularization unit.
26
© Copyright. All rights reserved.
Lesson: Describing ABAP Data Types and Data Objects
Hint:
If you use the STATICS statement instead of DATA when you declare local data
objects, the system extends their lifetime to the overall program lifetime.
Therefore, these such data objects have the same lifetime as global data objects,
but their visibility is still limited to the respective modularization unit. You can
use the STATICS statement in function modules, subroutines, and static
methods.
LESSON SUMMARY
You should now be able to:
●
Type data objects
●
Use global and local data objects
© Copyright. All rights reserved.
27
Unit 1
Lesson 3
Selecting Data from a Single Database Table
with Open SQL
LESSON OVERVIEW
This lesson provides a summary of Open SQL and how simple database read accesses can be
structured in Open SQL.
Business Example
You want to program complex, high-performance database accesses. To do so, you need to
refresh your knowledge of Open SQL. For this reason, you require the following knowledge:
●
An understanding of Open SQL
●
An understanding of how to program simple database read accesses with Open SQL
●
An understanding of the difference between single record access, sequential access, and
array fetch
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
28
Select data from a single database table with Open SQL
© Copyright. All rights reserved.
Lesson: Selecting Data from a Single Database Table with Open SQL
Open SQL Architecture
Figure 11: Open SQL and Native SQL
Open SQL statements are a subset of Standard SQL that is fully integrated in the ABAP
language. Open SQL statements allow uniform data access to the ABAP programmer
regardless of the database system installed. The database interface dynamically converts
Open SQL statements to database-specific SQL statements.
The SELECT Statement
Figure 12: Structure of the SELECT Statement
Use the Open SQL statement SELECT to program database read access.
© Copyright. All rights reserved.
29
Unit 1: ABAP Basics
The SELECT statement contains a series of clauses, each of which performs a different task.
The clauses of the SELECT statement are as follows:
●
SELECT clause
The SELECT clause describes, among other things, whether the result of the selection
comprises several lines or a single data record. This clause also describes which fields of
the table are to be read.
●
FROM clause
The FROM clause names the source (database table or view) from which you want to read
the data.
●
INTO clause
The INTO clause determines the internal data objects into which you want to place the
read data.
●
WHERE clause
The WHERE clause defines the conditions that the selection results must fulfill. The clause,
therefore specifies the rows you want to read from the table or view.
You can differentiate between three basic variants of the SELECT statement with regard to
the data volume to be read, and the structure of the data object you fill.
The variants of the SELECT statement are as follows:
●
Single record access (SELECT SINGLE)
●
Sequential processing (SELECT ... ENDSELECT)
●
ARRAY FETCH (SELECT ... INTO TABLE)
Hint:
The syntax components SINGLE, ENDSELECT, and INTO TABLE are mutually
exclusive.
30
© Copyright. All rights reserved.
Lesson: Selecting Data from a Single Database Table with Open SQL
Single Record Access (SELECT SINGLE)
Figure 13: Single Record Access (SELECT SINGLE)
The SELECT SINGLE * statement allows you to read a single record from a database table. To
ensure unique access, fill all key fields in the WHERE clause.
The * informs the database interface that the system should read all columns in that line of
the database table. If you only need a specific selection of columns, list the required fields
instead.
In the INTO clause, specify the data objects into which the selected data is to be placed. The
target area must have a structure identical to the columns of the database table being read.
Use the CORRESPONDING FIELDS OF addition to the INTO clause, to fill the target area
component by component. The system only fills those components having identical names to
columns in the database table. If you do not use this addition, the system fills the target area
left-justified, irrespective of its structure.
If the system finds a table entry matching your conditions, SY-SUBRC has the value 0.
© Copyright. All rights reserved.
31
Unit 1: ABAP Basics
Mass Access with Sequential Processing (SELECT ... ENDSELECT)
Figure 14: Mass Access with Sequential Processing (SELECT ... ENDSELECT)
If you do not use the addition SINGLE with the SELECT statement, the system reads multiple
records from the database. The field list determines the columns that will be read from the
database.
You can restrict the number of requested lines to be read using the WHERE clause. The name
of the database table that you can access is entered in the FROM clause. You can also add
multiple logical conditions to the WHERE clause using AND or OR statements.
The database delivers data to the database interface in packages. The ABAP runtime system
copies the data records to the target area line by line in a loop, therefore allowing sequential
processing of all statements between SELECT and ENDSELECT for each record.
After the ENDSELECT statement, you can check the return code for the SELECT loop. SYSUBRC has the value 0 if the result set consists of at least one record. After the ENDSELECT
statement, SY-DBCNT contains the total number of lines read.
32
© Copyright. All rights reserved.
Lesson: Selecting Data from a Single Database Table with Open SQL
Mass Access with ARRAY FETCH (SELECT ... INTO TABLE)
Figure 15: Mass Access with ARRAY FETCH (SELECT ... INTO TABLE)
The addition INTO TABLE ... causes the ABAP runtime system to copy the contents of the
database interface directly to an internal table. This process is known as an array fetch. Since
the system doesn’t execute the array fetch as a loop, you must not program an ENDSELECT
statement. SY-SUBRC is set to 0 if the system reads at least one record. In this case, SYDBCNT contains the number of lines read.
© Copyright. All rights reserved.
33
Unit 1: ABAP Basics
34
© Copyright. All rights reserved.
Unit 1
Exercise 2
Develop a Simple Report
Business Example
You are responsible for developing reports in a development project, and want to create a list
of flights.
Template
None
Solution
BC402_INS_FLIGHT_LIST
Create an executable program that outputs all the flights for a specific airline. You want the
user to enter an airline code on the selection screen, and also enter a constraint for the flight
numbers. You want the corresponding flights to appear in a list.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
1. Go to the Object Navigator and create a program with type Executable Programand name
ZBC402_##_FLIGHT_LIST.
2. Assign message class BC402 to the program as the default message class.
3. Define a selection screen. Define an elementary input field for the airline code. Enable the
user to enter one or more flight numbers.
4. Read the data from database table SFLIGHT using an array fetch, making sure to select
only the flights chosen by the user on the selection screen. Define a suitable data object to
hold the data. Output a suitable error message if no data can be found for the selection
criteria in the database.
5. Output the following fields in a simple list:
CARRID, CONNID, FLDATE, PRICE, CURRENCY, PLANETYPE, SEATSMAX, SEATSOCC
6. Check, activate and test the program.
© Copyright. All rights reserved.
35
Unit 1
Solution 2
Develop a Simple Report
Business Example
You are responsible for developing reports in a development project, and want to create a list
of flights.
Template
None
Solution
BC402_INS_FLIGHT_LIST
Create an executable program that outputs all the flights for a specific airline. You want the
user to enter an airline code on the selection screen, and also enter a constraint for the flight
numbers. You want the corresponding flights to appear in a list.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
1. Go to the Object Navigator and create a program with type Executable Programand name
ZBC402_##_FLIGHT_LIST.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown list on the left of the screen, choose Program and specify
the name of the program ZBC402_##_FLIGHT_LIST.
c) Choose Display.
A Create Program dialog box appears.
d) To create the program, choose Yes.
A Create Program dialog box appears.
e) In the Create Program dialog box, choose Continue.
f) In the ABAP: Program Attributes ZBC402_##_FLIGHT_LIST Changedialog box, choose
Save.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
h) In the Prompt for transportable Workbench requestdialog box, choose Continue.
2. Assign message class BC402 to the program as the default message class.
a) In the Object Name panel, double-click ZBC402_##_FLIGHTLIST.
36
© Copyright. All rights reserved.
Lesson: Selecting Data from a Single Database Table with Open SQL
b) Choose the Display <-> Change button.
c) See the source code excerpt from the model solution.
3. Define a selection screen. Define an elementary input field for the airline code. Enable the
user to enter one or more flight numbers.
a) See the source code excerpt from the model solution.
4. Read the data from database table SFLIGHT using an array fetch, making sure to select
only the flights chosen by the user on the selection screen. Define a suitable data object to
hold the data. Output a suitable error message if no data can be found for the selection
criteria in the database.
a) See the source code excerpt from the model solution.
5. Output the following fields in a simple list:
CARRID, CONNID, FLDATE, PRICE, CURRENCY, PLANETYPE, SEATSMAX, SEATSOCC
a) See the source code excerpt from the model solution.
6. Check, activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
REPORT
bc402_ins_flight_list MESSAGE-ID bc402.
DATA: gt_flight TYPE TABLE OF sflight,
gs_flight TYPE
sflight.
PARAMETERS pa_car TYPE sflight-carrid.
SELECT-OPTIONS so_con FOR gs_flight-connid.
START-OF-SELECTION.
SELECT * FROM sflight INTO TABLE gt_flight
WHERE carrid = pa_car
AND connid IN so_con.
IF sy-subrc <> 0.
MESSAGE e038.
ENDIF.
LOOP AT gt_flight INTO gs_flight.
WRITE: /
gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate,
gs_flight-price
CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
ENDLOOP.
© Copyright. All rights reserved.
37
Unit 1: ABAP Basics
LESSON SUMMARY
You should now be able to:
●
38
Select data from a single database table with Open SQL
© Copyright. All rights reserved.
Unit 1
Learning Assessment
1. When you create a repository object, you can optionally assign it to a package.
Determine whether this statement is true or false.
X
True
X
False
2. Each program can only have __________ introductory statements.
Choose the correct answer.
X
A Two
X
B One
X
C Three
3. Different event blocks can be used in ABAP programs, but only the _____ event can be
used in function groups and module pools.
Choose the correct answer.
X
A LOAD-OF-PROGRAM
X
B INITIALIZATION
X
C START-OF-SELECTION
X
D GET
X
E END-OF-SELECTION
4. An include program can integrate other include programs, as well as itself.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
39
Unit 1: Learning Assessment
5. What are the three types of literals?
Choose the correct answers.
X
A Numeric literals
X
B Variable literals
X
C Fixed literals
X
D Text field literals
X
E String literals
6. A DATA statement defines a local data object in the method if it appears between which
statements?
Choose the correct answer.
X
A FORM..ENDFORM
X
B METHOD..ENDMETHOD
X
C FUNCTION..ENDFUNCTION
X
D MODULE..ENDMODULE
7. Open SQL statements allow the ABAP programmer uniform access to data, regardless of
the database system installed.
Determine whether this statement is true or false.
40
X
True
X
False
© Copyright. All rights reserved.
Unit 1
Learning Assessment - Answers
1. When you create a repository object, you can optionally assign it to a package.
Determine whether this statement is true or false.
X
True
X
False
2. Each program can only have __________ introductory statements.
Choose the correct answer.
X
A Two
X
B One
X
C Three
3. Different event blocks can be used in ABAP programs, but only the _____ event can be
used in function groups and module pools.
Choose the correct answer.
X
A LOAD-OF-PROGRAM
X
B INITIALIZATION
X
C START-OF-SELECTION
X
D GET
X
E END-OF-SELECTION
4. An include program can integrate other include programs, as well as itself.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
41
Unit 1: Learning Assessment - Answers
5. What are the three types of literals?
Choose the correct answers.
X
A Numeric literals
X
B Variable literals
X
C Fixed literals
X
D Text field literals
X
E String literals
6. A DATA statement defines a local data object in the method if it appears between which
statements?
Choose the correct answer.
X
A FORM..ENDFORM
X
B METHOD..ENDMETHOD
X
C FUNCTION..ENDFUNCTION
X
D MODULE..ENDMODULE
7. Open SQL statements allow the ABAP programmer uniform access to data, regardless of
the database system installed.
Determine whether this statement is true or false.
42
X
True
X
False
© Copyright. All rights reserved.
UNIT 2
Program Calls and Memory
Management
Lesson 1
Calling Programs Synchronously
Exercise 3: Implement Program and Transaction Calls
44
53
Lesson 2
Describing the ABAP Runtime and Memory Management
Exercise 4: Use ABAP Memory and SAP Memory to Share Data Between Programs
60
83
Lesson 3
Using Shared Objects
Exercise 5: Use Shared Objects
100
121
UNIT OBJECTIVES
●
Call programs synchronously
●
Generate and activate programs
●
Explain the memory management of user sessions
●
Transfer data between programs
●
Analyze the memory management of deep data objects
●
Use boxed components
●
Explain shared objects
●
Use shared objects
© Copyright. All rights reserved.
43
Unit 2
Lesson 1
Calling Programs Synchronously
LESSON OVERVIEW
This lesson discusses various techniques for calling programs synchronously. It also
discusses how to insert and restart programs, and how to pass data on to the called program.
Business Example
You want to call existing programs from within a new application. To do so, you must
familiarize yourself with the techniques for calling programs. For this reason, you require the
following knowledge:
●
How programs are called from other programs
●
An understanding of the various options for passing data to the called program during
program calls
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Call programs synchronously
Synchronous Program Calls
Figure 16: Synchronous Program Calls
You have the following two options when calling another program synchronously:
44
© Copyright. All rights reserved.
Lesson: Calling Programs Synchronously
●
The process flow of the calling program pauses while the called program executes, and
resumes when the called program is complete (refer to the left side of figure Synchronous
Program Calls).
●
The calling program terminates and the called program starts (refer to the right side of
figure Synchronous Program Calls).
Complete programs can only run in a sequence within a single user session. This is referred to
as sequential calls. To run activities in parallel (known as asynchronous processing), you must
use function modules.
Note:
More information on asynchronous execution is available in other training courses
and in the ABAP keyword documentation for the CALL FUNCTION ... STARTING
NEW TASK ... statement.
Synchronous Calls of Executable Programs
Figure 17: Calling an Executable Program
To call an executable (type 1) program, use the SUBMIT statement. If you use the VIA
SELECTION-SCREEN addition, the system displays the standard selection screen.
If you use the AND RETURN addition, the system resumes processing with the first statement
of the calling program after the SUBMIT statement, once the execution of the called program
finishes.
Note:
For more information, see the ABAP keyword documentation for the SUBMIT
statement.
© Copyright. All rights reserved.
45
Unit 2: Program Calls and Memory Management
Passing Data Using the Program Interface
Figure 18: Passing Data Using the Program Interface
When you call ABAP programs that have a standard selection screen, you can pass data for
the input fields in the call.
Data for input fields can be passed in the following ways:
46
●
By specifying a variant for the selection screen when you call the program
●
By specifying specific values for the input fields when you call the program
© Copyright. All rights reserved.
Lesson: Calling Programs Synchronously
Pre-assignment of Input Fields
Figure 19: Pre-assignment of Input Fields
The WITH addition in the SUBMIT statement allows you to assign values to the fields on a
standard selection screen. The relational operators such as EQ, NE, and so on, and the
inclusion operators I and E have the same meaning as when they are used with SELECTOPTIONS.
If you want to provide several values for a select option, use the RANGE type instead of
individual WITH additions. Using the RANGE type creates a selection table that you can fill, as
though it were a select option. Then pass the table to the executable program.
To display the standard selection screen when you call the program, use the VIA SELECTIONSCREEN addition. Use the Pattern button in the ABAP Editor to insert a program call via
SUBMIT.
The pattern automatically supplies the names of the parameters and select options that are
available on the standard selection screen.
© Copyright. All rights reserved.
47
Unit 2: Program Calls and Memory Management
Synchronous Transaction Calls
Figure 20: Calling a Transaction
If you use the LEAVE TO TRANSACTION 'T_CODE' statement, the system terminates the
current program and starts the transaction with transaction code T_CODE. This statement is
the equivalent of entering /NT_CODE in the command field.
With the CALL TRANSACTION ‘T_CODE’ statement, execution of the calling program is
paused until the called program finishes its execution.
Use the LEAVE PROGRAM statement to force the termination of a program. For cases in
which this statement is executed in a program called by CALL TRANSACTION ‘T_CODE’ or
SUBMIT prog_name AND RETURN, the calling program will continue with the next statement
after the original call. In all other cases, the system returns to the application menu from
which the user started the program.
If you use the ... AND SKIP FIRST SCREEN addition, the system does not display the contents
of the first screen in the transaction.
Caution:
However, the flow logic of this first screen is processed.
When you start a transaction using CALL TRANSACTION 'T_CODE' and that transaction uses
update techniques, you can use the UPDATE ... addition to specify the update technique that
the program should use: asynchronous (default), synchronous, or local.
48
© Copyright. All rights reserved.
Lesson: Calling Programs Synchronously
Passing Data when Calling a Transaction
Figure 21: Passing Data when Calling a Transaction
When you call a transaction using the CALL TRANSACTION 'T_CODE' USING gt_bdcdata
statement, you can run transaction T_CODE using the values from internal table gt_bdcdata
in the screen fields.
This internal table must have the global structure type BDCDATA, and you should fill it
accordingly.
The MODE addition allows you to specify whether the screen displays all its contents (A –
default setting) only when an error occurs (E), or not at all (N).
You can use the MESSAGES INTO addition to specify an internal table into which any system
messages can be written. The corresponding internal table must have the type of global
structure BDCMSGCOLL.
Use the return code (SY-SUBRC), to verify that the system executes the transaction
successfully.
This technique of passing data using an internal table is useful in the following cases:
●
Processing in dialog, but not filling the input fields using GET parameters
●
Processing the transaction in the background, in which case you must pass the function
codes in the table as well
Fields in the Global Type BDCDATA
Table 9: Fields in the Global Type BDCDATA
The fields in the global type BDCDATA are as follows:
© Copyright. All rights reserved.
49
Unit 2: Program Calls and Memory Management
Field Name
Length
Description
Note When Filling
program
40
Program name
Only in first record for
screen
dynpro
4
Screen number
Only in first record for
screen
dynbegin
1
First record
‘X’ for first record for
screen, otherwise ‘ ‘
fnam
132
Field name
N/A
fval
132
Field value
Case sensitive
The information you require to fill the internal table in batch input format is as follows:
●
Identify each screen that you want to fill and process automatically in the transaction by a
line in which only the PROGRAM, DYNPRO, and DYNBEGIN fields are filled.
●
After the record identifies the screen, use a new BDCDATA record for each field you want
to fill. These records use the FNAM and FVAL fields. You can provide values for the
following types of fields: input or output fields (with data), the command field
BDC_OKCODE (with a function code), or the field for cursor positioning BDC_CURSOR
(with a field name).
The technique of passing data using an internal table is also one of the possible ways of
transferring data from non-SAP systems. When doing so, the internal table has to contain the
complete input that is needed for an execution of the transaction in background.
Data Transfer Using an Internal Table, Application Example
Figure 22: Data Transfer Using an Internal Table, Application Example
50
© Copyright. All rights reserved.
Lesson: Calling Programs Synchronously
The figure Data Transfer Using an Internal Table, Application Example shows an example of
how the internal table would be filled when calling transaction BC402_CALD_CRE_CUST. When
the transaction is called, the system passes the data of the internal table and it is processed in
the background.
© Copyright. All rights reserved.
51
Unit 2: Program Calls and Memory Management
52
© Copyright. All rights reserved.
Unit 2
Exercise 3
Implement Program and Transaction Calls
Business Example
An existing program displays a list of data. You want to enhance the program by enabling
users to access an existing report or dialog transaction by double-clicking on a line.
You need to implement a call of an executable program and a transaction, passing data from
the calling program when you do so.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy a Program and All its Components
1. In the Object Navigator, copy the template program BC402_PCT_CONN_LISTand all its
components to the name ZBC402_##_CONN_LIST. Familiarize yourself with the program
and how it works.
2. Activate and test the program.
3. Analyze the source code. How is the display of the flight connections implemented?
4. The program is already set to handle double-click events. Which processing block do you
have to enhance to do so?
Call an Executable Program
Implement the handler method that runs when a user double-clicks a flight connection. Make
sure a list of flights is returned for the chosen connection if the user double-clicks in the
CARRID column. To do so, use executable program BC402_INS_FLIGHT_LISTor your own
program, ZBC402_##_FLIGHTLIST.
1. Implement the on_double_click method of the local class lcl_handler. The COLUMN import
parameter contains the information about which column the user clicked. Use the SUBMIT
statement to call the executable program.
2. Make sure users can return to the display of flight connections after displaying the dates.
© Copyright. All rights reserved.
53
Unit 2: Program Calls and Memory Management
3. Supply the interface of the called program with the key values of the chosen flight
connection. To do so, determine the names of the input fields on the selection screen.
Call a Dialog Transaction
Implement the handler method that runs when a user double-clicks a flight connection. Make
sure details for the airline are output for the chosen connection if the user double-clicks in the
CARRID column. To do so, call dialog transaction BC402MCAR.
1. Call the transaction to insert it synchronously.
2. Pass the airline ID of the chosen connection on to the transaction. To do so, use the
USING addition. Determine the program name, screen number, and field label of the input
field on the initial screen of transaction BC402MCAR.
3. Pass the function code that is linked with the button on the initial screen on to the
transaction.
4. Make sure the transaction is processed without screen display. To do so, use the MODE
addition with a suitable value.
5. Check, activate and test the program.
54
© Copyright. All rights reserved.
Unit 2
Solution 3
Implement Program and Transaction Calls
Business Example
An existing program displays a list of data. You want to enhance the program by enabling
users to access an existing report or dialog transaction by double-clicking on a line.
You need to implement a call of an executable program and a transaction, passing data from
the calling program when you do so.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy a Program and All its Components
1. In the Object Navigator, copy the template program BC402_PCT_CONN_LISTand all its
components to the name ZBC402_##_CONN_LIST. Familiarize yourself with the program
and how it works.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown list on the left of the screen, choose Program and specify
the name of the program BC402_PCT_CONN_LIST.
c) Choose Display.
d) Right-click BC402_PCT_CONN_LISTand choose Copy....
e) In the Copy Program BC402_PCT_CONN_LISTdialog box, in the Target program field,
enter ZBC402_##_CONN_LIST and choose Copy.
f) In the Copy Program BC402_PCT_CONN_LIST to ZBC402_##_CONN_LISTdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test the program.
a) Double-click ZBC402_##_CONN_LIST.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
d) Choose Back.
© Copyright. All rights reserved.
55
Unit 2: Program Calls and Memory Management
3. Analyze the source code. How is the display of the flight connections implemented?
The static factory method is called to generate an instance of the class, and the internal
table containing the data is passed to it.
4. The program is already set to handle double-click events. Which processing block do you
have to enhance to do so?
The on_double_click method of the local class lcl_handler.
Call an Executable Program
Implement the handler method that runs when a user double-clicks a flight connection. Make
sure a list of flights is returned for the chosen connection if the user double-clicks in the
CARRID column. To do so, use executable program BC402_INS_FLIGHT_LISTor your own
program, ZBC402_##_FLIGHTLIST.
1. Implement the on_double_click method of the local class lcl_handler. The COLUMN import
parameter contains the information about which column the user clicked. Use the SUBMIT
statement to call the executable program.
a) Choose the Display <-> Change button.
b) See the source code excerpt from the model solution.
2. Make sure users can return to the display of flight connections after displaying the dates.
a) AND RETURN addition; see source code excerpt from the model solution.
3. Supply the interface of the called program with the key values of the chosen flight
connection. To do so, determine the names of the input fields on the selection screen.
a) See the source code excerpt from the model solution.
Call a Dialog Transaction
Implement the handler method that runs when a user double-clicks a flight connection. Make
sure details for the airline are output for the chosen connection if the user double-clicks in the
CARRID column. To do so, call dialog transaction BC402MCAR.
1. Call the transaction to insert it synchronously.
a) CALL TRANSACTION. See source code excerpt from the model solution.
2. Pass the airline ID of the chosen connection on to the transaction. To do so, use the
USING addition. Determine the program name, screen number, and field label of the input
field on the initial screen of transaction BC402MCAR.
a) See the source code excerpt from the model solution.
3. Pass the function code that is linked with the button on the initial screen on to the
transaction.
a) See the source code excerpt from the model solution.
4. Make sure the transaction is processed without screen display. To do so, use the MODE
addition with a suitable value.
a) See the source code excerpt from the model solution.
5. Check, activate and test the program.
a) Choose the Check button.
56
© Copyright. All rights reserved.
Lesson: Calling Programs Synchronously
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
REPORT
bc402_pcs_conn_list MESSAGE-ID bc402.
TYPES: BEGIN OF gty_s_conn,
carrid
TYPE spfli-carrid,
connid
TYPE spfli-connid,
cityfrom TYPE spfli-cityfrom,
cityto
TYPE spfli-cityto,
deptime TYPE spfli-deptime,
arrtime TYPE spfli-arrtime,
period
TYPE spfli-period,
END OF gty_s_conn.
TYPES gty_t_conn TYPE STANDARD TABLE OF gty_s_conn
WITH NON-UNIQUE DEFAULT KEY.
DATA gt_conn TYPE gty_t_conn.
DATA gv_msg TYPE string.
DATA: go_alv
go_evt
go_fct
gx_msg
TYPE
TYPE
TYPE
TYPE
REF
REF
REF
REF
TO
TO
TO
TO
cl_salv_table,
cl_salv_events_table,
cl_salv_functions_list,
cx_salv_msg.
*------------------------------------------------*
*
CLASS lcl_handler DEFINITION
*------------------------------------------------*
*
*-----------------------------------------------*
CLASS lcl_handler DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
on_double_click FOR EVENT double_click
OF if_salv_events_actions_table
IMPORTING row column.
ENDCLASS.
"lcl_handler DEFINITION
*----------------------------------------------------*
*
CLASS lcl_handler IMPLEMENTATION
*---------------------------------------------------*
*
*---------------------------------------------------*
CLASS lcl_handler IMPLEMENTATION.
METHOD on_double_click.
DATA: lt_bdc TYPE TABLE OF bdcdata,
ls_bdc TYPE
bdcdata.
DATA ls_conn LIKE LINE OF gt_conn.
READ TABLE gt_conn INTO ls_conn INDEX row.
CASE column.
© Copyright. All rights reserved.
57
Unit 2: Program Calls and Memory Management
WHEN 'CARRID'.
ls_bdc-program = 'SAPMBC402_IND_CARRIER'.
ls_bdc-dynpro
= '0100'.
ls_bdc-dynbegin = 'X'.
APPEND ls_bdc TO lt_bdc.
CLEAR ls_bdc.
ls_bdc-fnam = 'BC402_S_CARRIER-CARRID'.
ls_bdc-fval = ls_conn-carrid.
APPEND ls_bdc TO lt_bdc.
CLEAR ls_bdc.
ls_bdc-fnam = 'BDC_OKCODE'.
ls_bdc-fval = 'GO'.
APPEND ls_bdc TO lt_bdc.
CALL TRANSACTION 'BC402MCAR'
USING lt_bdc
MODE 'E'.
WHEN OTHERS.
SUBMIT bc402_ins_flight_list
AND RETURN
WITH pa_car EQ ls_conn-carrid
WITH so_con EQ ls_conn-connid.
ENDCASE.
ENDMETHOD.
ENDCLASS.
"on_double_click
"lcl_handler IMPLEMENTATION
*-------------------------------------------------*
START-OF-SELECTION.
SELECT carrid connid cityfrom cityto
deptime arrtime period
FROM spfli
INTO TABLE gt_conn.
TRY.
CALL METHOD cl_salv_table=>factory
IMPORTING
r_salv_table = go_alv
CHANGING
t_table
= gt_conn.
CATCH cx_salv_msg INTO gx_msg.
gv_msg = gx_msg->get_text( ).
MESSAGE gv_msg TYPE 'E'.
ENDTRY.
go_evt = go_alv->get_event( ).
SET HANDLER lcl_handler=>on_double_click
FOR go_evt.
go_alv->display( ).
58
© Copyright. All rights reserved.
Lesson: Calling Programs Synchronously
LESSON SUMMARY
You should now be able to:
●
Call programs synchronously
© Copyright. All rights reserved.
59
Unit 2
Lesson 2
Describing the ABAP Runtime and Memory
Management
LESSON OVERVIEW
This lesson explains in detail how the ABAP runtime environment executes a program. The
lesson also explains ABAP memory and SAP memory and their usage techniques for transient
data exchange across program boundaries.
Additionally, this lesson explains how data objects with variable length, known as dynamic
data objects, are managed in memory.
Business Example
You want to develop complex applications that include program calls, modularization, and
dynamic data objects. To ensure your applications have a robust, high-performance design,
you want to find out how the runtime environment and memory management work in detail.
You also want to learn about the options of the ABAP memory and SAP memory to exchange
data across program boundaries during program calls. For this reason, you require the
following knowledge:
●
An understanding of how the ABAP runtime environment executes programs
●
An understanding of the importance of the runtime object
●
An understanding of the roll area and program execution area (PXA)
●
An understanding of memory management in the ABAP runtime environment
●
An understanding of how dynamic data objects are managed
●
An understanding of how Boxed Components are managed and when they should be used
LESSON OBJECTIVES
After completing this lesson, you will be able to:
60
●
Generate and activate programs
●
Explain the memory management of user sessions
●
Transfer data between programs
●
Analyze the memory management of deep data objects
●
Use boxed components
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
ABAP Compiler and Runtime Objects
Figure 23: Developed Version of a Program
Development objects are stored in the Repository in the form in which they are developed.
These are the only versions of the development objects that can be displayed in the
Workbench.
To run a program in the ABAP runtime environment, the program must first be generated,
using the ABAP Compiler.
© Copyright. All rights reserved.
61
Unit 2: Program Calls and Memory Management
Generated Version
Figure 24: Generated Version of a Program
When you generate a development object, the system creates a runtime object, or LOAD. The
LOAD consists largely of byte code statements that are linked to C functions. To avoid
generating programs every time they run, program LOADS are saved in the database and
buffered on the application server.
The system generates the LOAD automatically in the following situations:
●
When the program is called and no LOAD exists yet.
●
When the LOAD in the database or program buffer is obsolete
You can also generate programs explicitly, in the ABAP Editor using menu path
Program → Generate.
A saved or buffered LOAD is considered obsolete under either of the following conditions:
62
●
The developed version of the program is changed.
●
An object that the program uses is changed in the ABAP Dictionary.
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Hint:
Transports between SAP systems always involve developed versions. After being
imported into a target system, the system discards all affected runtime objects.
The system does not generate new LOADs automatically. They are generated at
the first instance, when a user calls the corresponding program (directly or
indirectly). After an import, users may temporarily experience wait times and low
performance until all the required LOADS are generated again. To avoid this,
start the SAP load generator (transaction code SGEN) after the import.
Inactive Sources
Figure 25: Active and Inactive Versions
When you change an active development object and save it, the system creates an inactive
version, in addition to the existing active version.
Hint:
Saving an inactive version has no effect on the program LOAD. Accordingly, the
syntax of the inactive version does not necessarily have to be correct. You can
also save an interim, non-executable version of the development object
inactively. However, the active version remains available as an executable
version.
You can toggle the view between the active and inactive versions, but you can only edit the
inactive version. When a syntax check is performed, it is done on the version in development
(the inactive version), but not on the generated version. When running source code for
© Copyright. All rights reserved.
63
Unit 2: Program Calls and Memory Management
executable programs from the ABAP Editor, the system refers back to the inactive version. In
this case, the system creates a temporary generated version that is not buffered or stored in
the database. In all other cases, the system always accesses the active version when you
execute the program.
Program Activation
Figure 26: Activating a Program
All inactive objects that the system assigns to your user ID are listed in your work list.
The following steps occur when you activate an object:
1. The object is saved, that is, a new inactive version is created. This is subject to a syntax
check.
2. The system overwrites the current active version. The previously inactive version is now
the active version, which means there is no longer an inactive version.
3. The system creates a new runtime version and updates the LOAD.
64
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Program Execution Area (PXA) and Roll Area
Figure 27: Loading a Runtime Object to Working Memory
When the runtime system generates a new runtime object (the LOAD) of a program or loads it
from the database, it places the program in the working memory of the application server. In
the process, the runtime system treats the modifiable parts of the program differently than
the non-modifiable parts.
Parts of a Program
●
●
Non-modifiable parts of a program
-
Byte code for statements
-
Values of constants and literals
-
Program texts
-
Screen definitions
Modifiable parts of a program
-
Data objects (variables)
The system stores the non-modifiable parts of the program in the PXA and buffers them there
as long as possible. This memory area is shared by all users on the application server and
exists only once on each server. After a program is executed, the byte code of the program
remains buffered in the PXA for as long as possible. Buffering prevents the system from
loading the code from the database again during the next execution.
The modifiable parts of the program are created in memory during every execution, in a
memory space called the roll area. When the program is executed several times concurrently
© Copyright. All rights reserved.
65
Unit 2: Program Calls and Memory Management
(by the same user or different users), each execution has its own roll area. This ensures that
the system executes the programs independently of one another.
Memory Management from the Program Perspective
Figure 28: Logical Memory Model
The figure Logical Memory Model shows the way in which main memory is organized from a
program’s perspective.
To understand the logical memory model, it is important to distinguish between internal and
external sessions, as follows:
●
External session (main session)
An external session corresponds to a SAPGUI window. You can create a new session by
choosing System → New Session or by calling /o<t_code>. Up to 16 external sessions are
possible in SAP NetWeaver 7.0 and later. The maximum number of sessions available in a
given system is defined by system parameter rdisp/max_alt_modes, which has a default
value of 6.
●
Internal session
External sessions are subdivided into internal sessions (placed in a stack). Each call of an
ABAP program (SUBMIT, CALL TRANSACTION, and so on) generates a new internal
session. A maximum of nine internal sessions can exist in each external session, and they
must all belong to the same call stack.
Hint:
The system reserves one roll area for each internal session.
66
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Program Groups
Figure 29: Program Groups
When a program calls external modularization units, the system loads the corresponding
programs into the same internal session. The programs within an internal session form
program groups. When the system opens an internal session with a program call, the system
always creates the main program group. There can be one or more additional program
groups. Each program group contains one main program, and possibly other programs as
well.
The program data objects are only visible within its program group, which means programs in
different program groups do not share any data objects. All programs and objects of an
internal session can use instances of classes. An object continues to exist as long as there are
references to it.
© Copyright. All rights reserved.
67
Unit 2: Program Calls and Memory Management
Memory Management for Program Calls
Figure 30: Before Inserting a Program
The figure Before Inserting a Program illustrates the situation before a program call is made.
The starting point for the first example is the execution of a SUBMIT ... AND RETURN or CALL
TRANSACTION statement within a program (that is, the insertion of a program).
Inserted Program
Figure 31: The Inserted Program Runs
68
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
When you insert a program, the system creates a new internal session which contains the new
program context. The system places the new session in the stack. The program context of the
calling program remains in the stack.
After the Inserted Program Ends
Figure 32: After the Inserted Program Ends
When the called program is completed, the system deletes the called program’s internal
session (the top one in the stack). The system then begins processing the next-highest
internal session in the stack.
© Copyright. All rights reserved.
69
Unit 2: Program Calls and Memory Management
Before Starting a New Executable Program
Figure 33: Before Starting a New Executable Program
When a program is ended and a new one started, there is a difference between calling an
executable program using the SUBMIT statement, and calling a transaction using the LEAVE
TO TRANSACTION statement, with regard to memory areas.
The starting point for the next case is the execution of a SUBMIT statement within a program.
70
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
The New Executable Program Runs
Figure 34: The New Executable Program Runs
When you start an executable program with the SUBMIT statement, the following actions
occur:
●
The system ends the calling program.
●
The system destroys the internal session of the program that you are terminating (the top
program in the stack).
●
The system creates a new internal session, which contains the program context of the
called program. The system then places the new session in the stack and retains any
previously created program contexts. The topmost internal session in the stack is thereby
replaced.
© Copyright. All rights reserved.
71
Unit 2: Program Calls and Memory Management
Before Starting a New Transaction
Figure 35: Before Starting a New Transaction
The starting point for the third case is the execution of a LEAVE TO TRANSACTION statement
within a program.
The New Transaction Runs
Figure 36: The New Transaction Runs
72
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
When you start a transaction using the LEAVE TO TRANSACTION statement, the system
destroys all internal sessions in the stack. The system then creates a new internal session,
which contains the program context of the called program.
The system initializes the complete stack of internal sessions, which also means it initializes
ABAP memory after the call.
Memory Management for Calls of Function Modules and Methods
Figure 37: Main or Additional Program Groups
The figure Main or Additional Program Groups explains the impact of external procedure calls
on Function Pools (type F) and Class Pools (type K).
Cross-program modularization, where function modules are called or global classes are
accessed, is not implemented using internal sessions. Instead, program groups play a central
role.
When an internal session is opened, the system always creates the main program group.
Any number of additional program groups can be created in the same internal session. Each
program group has only one main program.
An additional program group is created in the following cases:
●
When the program calls a function module from a function group that has not yet been
loaded.
●
When the program calls a method of a global class that has not yet been loaded.
The system loads each function group and each global class only once into a given internal
session.
© Copyright. All rights reserved.
73
Unit 2: Program Calls and Memory Management
Same Function Group in Different Internal Sessions
Figure 38: Same Function Group in Different Internal Sessions
When two programs running in different internal sessions call up function modules from the
same function group, the system loads the function group into each of the internal sessions
separately. The system creates the global data of the function group separately in each
internal session. Therefore, there is no possibility or risk of the two main programs
exchanging data through the function group.
74
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Same Class in Different Internal Sessions
Figure 39: Same Class in Different Internal Sessions
When programs that run in different internal sessions use the same global class, the global
class is created separately in each internal session. The static attributes of the class can have
different values in different internal sessions.
© Copyright. All rights reserved.
75
Unit 2: Program Calls and Memory Management
Same Function Group or Class Within an Internal Session
Figure 40: Same Function Group or Class Within an Internal Session
When two programs run in the same internal session, for example, an executable program
and the AB function group it addresses, and both programs address the same XY function
group, then the system loads the function group XY in the internal session once only.
Therefore, the main program and function group AB can exchange data using function group
XY. The same applies for global classes.
Caution:
In practice, this situation can result in errors because the main program and
function group AB (or class CL_A) affect each other inadvertently. The main
program may buffer data in function group XY, for example, but function group
AB or class CL_A can unintentionally overwrite the data or initialize it. This can
result in program termination and even data inconsistency.
The causes of such errors are difficult to find, particularly when the program does not use the
function group AB or class CL_A directly but through other function groups or classes
instead.
76
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Hint:
When the shared program is a global class (class CL_B in the figure), there is only
a risk of unintended interaction with regard to static attributes. The two
programs used see only the same instances (and therefore the instance attribute
values) of a class when they specifically exchange references to these instances.
An elegant way of avoiding unintended interaction for global classes is to use
instance attributes instead of static attributes. Also, make sure that every user of
the class generates a separate instance.
External Subroutine Calls
Figure 41: External Subroutine Calls
The figure External Subroutine Calls explains the impact of external subroutine calls on
Executable programs (type 1), Module pools (type M) and subroutine pools (type S).
When a program calls a subroutine externally, the system does not generate a new program
group in the internal session. Instead, it loads the main program of this subroutine into the
existing program group of the calling program.
Hint:
Subroutines of a function group are an exception. When a subroutine of a
function group is called externally, the system loads the corresponding function
group into an additional program group.
When two programs are in the same program group, the developer must observe the
following constraints:
●
Within a program group, all programs share the interface work areas that are declared with
TABLES, NODES, and COMMON PART.
●
Within a program group, CALL SCREEN can only be used to call screens of the main
program.
© Copyright. All rights reserved.
77
Unit 2: Program Calls and Memory Management
Caution:
When you use external subroutine calls, you always run the risk that data objects
from one program can be shared with other programs. While you may do this
purposely in some exceptional cases, you should avoid it wherever possible
considering the aspects of encapsulation and ease of maintenance. Therefore,
avoid using external subroutine calls altogether.
Data Transfer Options
Figure 42: Data Transfer Between Programs – Overview
When programs run in different program groups, internal sessions, or external sessions, they
do not share any data objects. However, various options are available for exchanging data
between these programs.
Some techniques for passing data are as follows:
78
●
Using the interface of the called program (screen or selection screen)
●
ABAP memory
●
SAP memory
●
Database tables
●
Local files on the presentation server
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Note:
For more information about passing data using database tables or the shared
buffer, see the ABAP keyword documentation for the EXPORT and IMPORT
statements.
For more information about transferring data between an ABAP program and your
presentation server, see the documentation of function modules GUI_UPLOAD
and GUI_DOWNLOAD. You can also use the methods of class
CL_GUI_FRONTEND_SERVICES for this purpose.
ABAP Memory and SAP Memory
Figure 43: Range of ABAP Memory and SAP Memory
When you need to transfer data between two different programs but cannot specify the data
as an addition in the program call, you can use SAP memory and ABAP memory to transfer
data.
SAP memory is a user-specific memory area for storing field values. It is, therefore, not useful
for passing data between internal sessions.
The system retains values in SAP memory for the duration of the terminal session for the
user. You can also use SAP memory between sessions in the same terminal session. All
external sessions of a user session can access SAP memory. You can use the contents of SAP
memory as default values for screen fields.
ABAP memory is also user specific. There is a local ABAP memory for each external session.
You can use it to exchange any ABAP data objects (such as fields, structures, internal tables,
and complex objects) between internal sessions in any one external session.
When the user exits an external session (by entering /I in the command field), the system
automatically initializes or releases the corresponding ABAP memory.
© Copyright. All rights reserved.
79
Unit 2: Program Calls and Memory Management
Access to ABAP Memory
Figure 44: Passing Data Using ABAP Memory
The EXPORT ... TO MEMORY statement copies any number of ABAP data objects with their
current values (data cluster) to ABAP memory. The ID addition, which can be a maximum of
60 characters long, enables you to identify different clusters.
When you use a new EXPORT TO MEMORY statement for an existing data cluster, the new
statement overwrites the old one. The IMPORT ... FROM MEMORY ... statement allows you to
copy data from ABAP memory to the corresponding fields of your ABAP program.
You can also restrict the selection to a part of the data cluster in the IMPORT statement. The
variables into which you want to read data from the cluster in ABAP memory must have the
same types, in both the exporting and the importing programs.
You use the FREE MEMORY ID ... statement to release a data cluster explicitly.
Caution:
When you call transactions, you can only use ABAP memory to pass data to the
transaction in the insert case (CALL TRANSACTION).
80
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Access to SAP Memory
Figure 45: Passing Parameters Using SAP Memory
You can define memory areas (called parameters) in SAP memory in the following ways:
●
You can create screen input/output fields with reference to the ABAP Dictionary.
These fields take the parameter names of the data elements to which they refer.
Alternatively, you can enter a name in the attributes of the input/output fields. Then, you
can also choose whether you want to transfer the entries from the field to the parameter
(SET) or fill out the input field with the value from the parameter (GET). To find out about
the names of the parameters assigned to input fields, display the field help using the F1 key
and choose the Technical info button.
●
You can also fill the memory areas directly using the SET PARAMETER ID 'PAR_ID' FIELD
var. statement and read from them using the GET PARAMETER ID 'PAR_ID' FIELD var.
statement.
© Copyright. All rights reserved.
81
Unit 2: Program Calls and Memory Management
82
© Copyright. All rights reserved.
Unit 2
Exercise 4
Use ABAP Memory and SAP Memory to Share
Data Between Programs
Business Example
An existing program selects data based on user entries and outputs it in a list. You call this
program from within another program. Instead of displaying the data directly with the called
report, you want to load the data you select into ABAP memory, and process it further in the
calling program. You also want to use parameters in SAP memory to pre assign values to
fields when calling a transaction.
Use ABAP memory to exchange data between programs and SAP memory to preassign fields
in a transaction call.
Template
BC402_INS_FLIGHT_LIST (called program)
BC402_PCS_CONN_LIST (calling program)
Solution
BC402_MMS_FLIGHT_LIST (called program)
BC402_MMS_CONN_LIST (calling program)
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Export Data to ABAP Memory
Copy the called program, BC402_INS_FLIGHT_LIST(or your own program,
ZBC402_##_FLIGHT_LIST), to the name ZBC402_##_FLIGHT_LIST_MEM. Enhance the
program so that it can selectively output the flights in a list or save the internal table with its
data in ABAP memory. Create an invisible parameter on the selection screen that enables
storage in ABAP memory when the program is called with SUBMIT.
1. Copy the program and all its subcomponents.
2. Define an additional parameter for the selection screen (suggested name: PA_LIST). Type
the parameter with type ABAP_BOOL from the ABAP type group.
3. Check the keyword documentation to find a suitable addition for the PARAMETERS
statement that suppresses the parameter when displaying the selection screen.
4. Enhance the program so that it suppresses the list output when the parameter is not set
to its default value. In this case, you want to export the read data into ABAP memory.
Choose a suitable ID for your data cluster (suggested name: BC402_##_FLIGHTS).
© Copyright. All rights reserved.
83
Unit 2: Program Calls and Memory Management
5. Check, activate and test the program.
Copy and Modify the Calling Program
Copy the calling program BC402_PCS_CONN_LIST (or your own program,
ZBC402_##_CONN_LIST) to the name ZBC402_##_CONN_LIST_MEM and modify the name
of the called program in the SUBMIT statement. Call the program so that it saves the data in
ABAP memory instead of outputting the data directly.
1. Copy the calling program.
2. Modify the SUBMIT statement to call program ZBC402_##_FLIGHT_LIST_MEM. Supply
the new parameter with a value to suppress the list display and write the data to ABAP
memory.
Read the Data from ABAP Memory
After the program call, read the data from ABAP memory and use function module
BC402_DISPLAY_TABLE to display the data in an ALV grid. Delete the data in ABAP memory
after it is read.
1. After the program call, import the data from ABAP memory into a suitable internal table
which you will need to define. If an error occurs, issue error message 361 from message
class BC402.
2. Implement a call of function module BC402_DISPLAY_TABLE. Pass the data from ABAP
memory on to this function module for display.
3. Deal with the (class-based) exception of the function module.
4. Release the memory for your cluster to delete the data from ABAP memory.
Use SAP Memory to Pass Data to a Called Transaction
Find out if it is possible to preassign the input field on the first screen using a parameter in
SAP memory, and, if so, use this option. Remove the USING and MODE additions from the
CALL TRANSACTION statement and suppress the display of the first screen.
1. Analyze transaction BC402MCAR. Find out whether the input field from screen 0100 in
program SAPMBC402_IND_CARRIER is linked with a parameter ID. If so, find the
parameter ID name.
2. Check whether automatic pre-assignment from SAP memory is active for the field.
3. Use a suitable statement to set the value of the parameter to the desired value in SAP
memory before the transaction call.
4. Remove the USING and MODE additions from the CALL TRANSACTION statement.
Instead, use a suitable addition to suppress the first screen.
5. Check, activate and test the program.
84
© Copyright. All rights reserved.
Unit 2
Solution 4
Use ABAP Memory and SAP Memory to Share
Data Between Programs
Business Example
An existing program selects data based on user entries and outputs it in a list. You call this
program from within another program. Instead of displaying the data directly with the called
report, you want to load the data you select into ABAP memory, and process it further in the
calling program. You also want to use parameters in SAP memory to pre assign values to
fields when calling a transaction.
Use ABAP memory to exchange data between programs and SAP memory to preassign fields
in a transaction call.
Template
BC402_INS_FLIGHT_LIST (called program)
BC402_PCS_CONN_LIST (calling program)
Solution
BC402_MMS_FLIGHT_LIST (called program)
BC402_MMS_CONN_LIST (calling program)
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Export Data to ABAP Memory
Copy the called program, BC402_INS_FLIGHT_LIST(or your own program,
ZBC402_##_FLIGHT_LIST), to the name ZBC402_##_FLIGHT_LIST_MEM. Enhance the
program so that it can selectively output the flights in a list or save the internal table with its
data in ABAP memory. Create an invisible parameter on the selection screen that enables
storage in ABAP memory when the program is called with SUBMIT.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_FLIGHT_LIST.
c) Choose Display.
d) Right-click ZBC402_##_FLIGHT_LISTand choose Copy....
© Copyright. All rights reserved.
85
Unit 2: Program Calls and Memory Management
e) In the Copy Program ZBC402_##_FLIGHT_LISTdialog box, in the Target program field,
enter ZBC402_##_FLIGHT_LIST_MEM and choose Copy.
f) In the Copy Program ZBC402_##_FLIGHT_LIST to ZBC402_##_FLIGHT_LIST_MEM
dialog box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Define an additional parameter for the selection screen (suggested name: PA_LIST). Type
the parameter with type ABAP_BOOL from the ABAP type group.
a) In the Object Name panel, double-click ZBC402_01_FLIGHT_LIST_MEMand choose
the Display <-> Change button.
b) See the source code excerpt from the model solution.
3. Check the keyword documentation to find a suitable addition for the PARAMETERS
statement that suppresses the parameter when displaying the selection screen.
a) NO-DISPLAY addition. See source code excerpt from the model solution.
4. Enhance the program so that it suppresses the list output when the parameter is not set
to its default value. In this case, you want to export the read data into ABAP memory.
Choose a suitable ID for your data cluster (suggested name: BC402_##_FLIGHTS).
a) See the source code excerpt from the model solution.
5. Check, activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
Copy and Modify the Calling Program
Copy the calling program BC402_PCS_CONN_LIST (or your own program,
ZBC402_##_CONN_LIST) to the name ZBC402_##_CONN_LIST_MEM and modify the name
of the called program in the SUBMIT statement. Call the program so that it saves the data in
ABAP memory instead of outputting the data directly.
1. Copy the calling program.
a) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_CONN_LIST.
b) Choose Display.
c) Right-click ZBC402_##_CONN_LISTand choose Copy....
d) In the Copy Program ZBC402_##_CONN_LISTdialog box, in the Target program field,
enter ZBC402_##_CONN_LIST_MEM and choose Copy.
e) In the Copy Program ZBC402_##_CONN_LIST to ZBC402_##_CONN_LIST_MEM
dialog box, select all checkboxes and choose Copy.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Modify the SUBMIT statement to call program ZBC402_##_FLIGHT_LIST_MEM. Supply
the new parameter with a value to suppress the list display and write the data to ABAP
memory.
a) See the source code excerpt from the model solution.
86
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Read the Data from ABAP Memory
After the program call, read the data from ABAP memory and use function module
BC402_DISPLAY_TABLE to display the data in an ALV grid. Delete the data in ABAP memory
after it is read.
1. After the program call, import the data from ABAP memory into a suitable internal table
which you will need to define. If an error occurs, issue error message 361 from message
class BC402.
a) See the source code excerpt from the model solution.
2. Implement a call of function module BC402_DISPLAY_TABLE. Pass the data from ABAP
memory on to this function module for display.
a) See the source code excerpt from the model solution.
3. Deal with the (class-based) exception of the function module.
4. Release the memory for your cluster to delete the data from ABAP memory.
a) See the source code excerpt from the model solution.
Use SAP Memory to Pass Data to a Called Transaction
Find out if it is possible to preassign the input field on the first screen using a parameter in
SAP memory, and, if so, use this option. Remove the USING and MODE additions from the
CALL TRANSACTION statement and suppress the display of the first screen.
1. Analyze transaction BC402MCAR. Find out whether the input field from screen 0100 in
program SAPMBC402_IND_CARRIER is linked with a parameter ID. If so, find the
parameter ID name.
a) Run transaction BC402MCAR.
b) With your cursor in the input field, on your keyboard, press the F1 key and in the
Performance Assistancedialog box, choose Technical Information.
c) The Parameter ID field contains the value CAR.
2. Check whether automatic pre-assignment from SAP memory is active for the field.
a) To navigate to screen 0100, in the Technical Informationdialog box, double-click the
Screen Number field.
b) To analyze the attributes for the input screen, choose the Element list tab and choose
the Special attr. tab.
c) The GET parameters checkbox is selected.
3. Use a suitable statement to set the value of the parameter to the desired value in SAP
memory before the transaction call.
a) See the source code excerpt from the model solution.
4. Remove the USING and MODE additions from the CALL TRANSACTION statement.
Instead, use a suitable addition to suppress the first screen.
a) AND SKIP FIRST SCREEN addition. See source code excerpt from the model solution.
5. Check, activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
© Copyright. All rights reserved.
87
Unit 2: Program Calls and Memory Management
c) Choose the Direct Processingbutton.
BC402_MMS_FLIGHT_LIST (called program)
REPORT
bc402_mms_flight_list MESSAGE-ID bc402.
TYPE-POOLS: abap.
DATA: gt_flight TYPE TABLE OF sflight,
gs_flight TYPE
sflight.
PARAMETERS pa_car TYPE sflight-carrid.
SELECT-OPTIONS so_con FOR gs_flight-connid.
PARAMETERS pa_list TYPE abap_bool DEFAULT abap_true NO-DISPLAY.
START-OF-SELECTION.
SELECT * FROM sflight INTO TABLE gt_flight
WHERE carrid = pa_car AND
connid IN so_con.
IF sy-subrc <> 0.
MESSAGE e038.
ENDIF.
IF pa_list = abap_true.
LOOP AT gt_flight INTO gs_flight.
WRITE: /
gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate,
gs_flight-price
CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
ENDLOOP.
ELSE.
EXPORT flights FROM gt_flight
TO MEMORY ID 'BC402_FLIGHTS'.
ENDIF.
BC402_MMS_CONN_LIST (calling program), Method: on_double_click
METHOD on_double_click.
DATA lt_sflight TYPE TABLE OF sflight.
DATA ls_conn LIKE LINE OF gt_conn.
88
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
READ TABLE gt_conn INTO ls_conn INDEX row.
CASE column.
WHEN 'CARRID'.
SET PARAMETER ID 'CAR' FIELD ls_conn-carrid.
CALL TRANSACTION 'BC402MCAR'
AND SKIP FIRST SCREEN.
WHEN OTHERS.
SUBMIT bc402_mms_flight_list
AND RETURN
WITH pa_car EQ ls_conn-carrid
WITH so_con EQ ls_conn-connid
WITH pa_list EQ space.
IMPORT flights TO lt_sflight
FROM MEMORY ID 'BC402_FLIGHTS'.
IF sy-subrc <> 0.
MESSAGE e361.
ELSE.
CALL FUNCTION 'BC402_DISPLAY_TABLE'
CHANGING
ct_table = lt_sflight.
ENDIF.
FREE MEMORY ID 'BC402_FLIGHTS'.
ENDCASE.
ENDMETHOD.
© Copyright. All rights reserved.
"on_double_click
89
Unit 2: Program Calls and Memory Management
Dynamic Data Objects
Strings and internal tables are dynamic data objects (also called deep data objects) with
memory requirements that can change during the program runtime. The system manages the
working data of these data objects internally, using references.
Note:
Other deep data objects include references and structures that contain at least
one deep component.
Memory management treats deep data objects and flat data objects differently.
Memory Management for Flat Data Objects
Figure 46: Memory Management for Flat Data Objects
Flat data objects are elementary data objects with fixed lengths and structures that only have
flat components. The content of flat data objects represents actual working data. The system
reserves memory for flat data objects as soon as it loads the program into the internal
session. The system does not release the memory reserved for flat objects until it deletes the
internal session.
90
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Memory Management for Strings
Figure 47: Memory Management for Strings
When the system loads a program, it creates only a reference for the statically declared deep
data objects at first, such as strings and internal tables. The static memory requirement for
this reference is 8 bytes.
When you use the deep data object, additional working memory is requested at program
runtime. For dynamic data objects (strings and internal tables), this memory is for the
administration information (header) and the data object itself.
The memory requirement for a header depends on the hardware platform, but is around 100
bytes.
When the requested (allocated) memory is not sufficient for later access, additional memory
can be reserved.
The system allocates more memory than required for the current content of the data object,
to avoid frequent requests as the content increases. The system also limits the size of strings
to the largest contiguous block of memory that is requested. This limit is a maximum of 2 GB,
but is usually restricted further with profile parameter ztta/max_memreq_MB.
Caution:
The requested memory must be available in the current internal mode otherwise,
a runtime error occurs.
When you initialize a string with CLEAR or FREE, the system deletes the data, but the
reference variables and the header are retained and reused during the next memory request.
Accordingly, when a string has been used and then deleted, its memory requirement consists
of the reference and the requirement of the header.
© Copyright. All rights reserved.
91
Unit 2: Program Calls and Memory Management
Memory Management for Internal Tables
Figure 48: Memory Management for Internal Tables
Memory management for internal tables is similar to management for strings.
Memory management for internal tables works as follows:
●
The headers of internal tables require more memory than other headers, because internal
table data can be distributed among several blocks. This means that the internal table
header may need to manage references to these blocks.
●
The CLEAR, REFRESH, and FREE statements have different effects. CLEAR and REFRESH
only delete the data, while FREE can also delete the table header when it takes up too
much memory.
●
The amount of memory that is allocated during initial access can be changed when you
define the internal table (optional addition INITIAL SIZE).
You can specify the number of rows, n, as numeric literals or numeric constants in the INITIAL
SIZE addition. The system then selects the size of the first block in memory to fit the exact
number of lines.
Hint:
For global table types in the ABAP Dictionary, the Initial Number of Linesinput
field on the Initialization and Accesstab performs this function.
If you do not specify the addition, the system automatically specifies the number 0. When the
value of n exceeds a maximum value, the system automatically assigns a suitable memory
area during the first access. The system allocates additional memory based on the number of
lines that exceeds the specified value n during or after initial access. Therefore, n is not a fixed
upper limit for the memory capacity of the internal table.
92
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
Caution:
Exceeding the specified initial memory requirement when the internal table is
filled can cause the system to allocate more extra memory than actually needed.
Therefore, SAP recommends that you only specify the initial memory
requirement when you know the number of entries in the table and want to
specify the size of the initial main memory requirement.
Hint:
Specifying an initial memory requirement is appropriate when the internal tables
are components of table types (nested tables) and the inner tables only contain a
few lines.
Memory Optimization when Copying Dynamic Data Objects
Figure 49: Memory Optimization when Copying Dynamic Data Objects
To minimize runtime and conserve memory, assigned values are shared between strings and
between internal tables.
Sharing means the system initially does not copy the actual data values during an
assignment. Instead, it copies only the necessary management entries. The target object
therefore refers to the same data as the source object. When strings are involved, the second
internal reference is filled to point to the existing string header. The system cancels sharing
when you access either the source or the target in change mode. This approach is called
copy-on-write semantics. In this case, the system actually copies data values and changes the
references and header accordingly.
© Copyright. All rights reserved.
93
Unit 2: Program Calls and Memory Management
Memory Sharing Between Internal Tables
Figure 50: Sharing Between Internal Tables
With internal tables only the actual data is shared. The system assigns each table a separate
table header, which refers to the existing table body. Tables whose line types contain other
table types, are not shared.
Hint:
Sharing is also used to pass values to procedures. Therefore, there is no major
difference between using call by value and call by reference with regard to
runtime requirements for passing strings and internal tables to subroutines. A
runtime-intensive copy operation takes place if you use call by value and then
access the formal parameters in change mode within the procedure. In contrast,
when you use call by reference, the actual and formal parameters continue to
use the same memory.
Definition of Boxed Components
Large static data objects can use a large amount of memory even when they are INITIAL.
When you have many identical unused static data objects in your program, it can lead to
memory wastage.
Consider the following example:
94
●
An instance attribute with a static structure which is INITIAL in most of the instances of a
class.
●
An internal table where a large number of columns are not used for many table lines.
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
As of SAP NetWeaver 7.0 EhP2, you can use Boxed Components to reduce the memory
consumption of static data objects.
The following can be defined as boxed components:
●
Substructures of nested structures
●
Structured attributes of classes and interfaces
These components are also called static boxes. A static box is declared with the BOXED
addition when defining substructures using TYPES, or when declaring structured attributes of
classes or interfaces using DATA. For global structure types, classes, and interfaces, a new
value for the property Typing Method is available.
Hint:
It is not possible to use the BOXED addition in DATA statements that lie outside
class definitions. To define boxed components outside class definitions, you have
to use the TYPES statement or define a suitable global structure type.
Initial Value Sharing for Boxed Components
Figure 51: Initial Value Sharing for Boxed Components
The figure Initial Value Sharing for Boxed Components illustrates an example of a nested
structure with a boxed static substructure. The contents of the boxed subcomponent SUB are
not stored inside the structure GS_BOXED directly. Instead, the subcomponent is internally
represented by a reference. As long as the subcomponent is still INITIAL, this reference points
to an appropriately typed initial structure stored centrally in the PXA. This is called Initial
Value Sharing for boxed components.
© Copyright. All rights reserved.
95
Unit 2: Program Calls and Memory Management
The system revokes the initial value sharing, if, for example, a write access to the
substructure takes place, after which the substructure is no longer initial. As shown in the
figure Initial Value Sharing for Boxed Components, the system creates the substructure
dynamically within the internal session of the program, and changes the reference so that it
points to the new substructure.
Hint:
Once the initial value sharing is revoked, it remains like that. The CLEAR or FREE
statement only initializes the components of the substructure but does not
release the memory allocated for the substructure.
Operations that revoke the initial value sharing of a boxed component are as follows:
●
Using write access to the static box or one of its components
●
Using a static box or one of its components as an actual parameter for procedure calls
●
Addressing the static boxed component or one of its subcomponents with a data reference
or a field symbol
Hint:
A structure that contains a boxed component is always deep even when all its
components, including the boxed subcomponent, are of static length.
Examples of Boxed Components
Figure 52: Instance Attribute Defined as Boxed Component
96
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
The figure Instance Attribute Defined as Boxed Component illustrates an example of an
instance attribute of a class defined as a boxed component.
If the boxed attribute remains initial in many instances of the class, all instances share the
same initial value. This can significantly reduce the memory consumption of the program.
Example – Internal Tables and Boxed Components
Figure 53: Example – Internal Tables and Boxed Components
You can reduce the overall size of an internal table if you use a structure type that contains a
boxed component as the line type. This is illustrated in the figure Example — Internal Tables
and Boxed Components.
Use Cases for Boxed Components
Boxed components should only be used in the following circumstances:
●
Boxed components often remain initial
The advantage of boxed components lies in the reduced memory usage through initial
value sharing. This implies that a boxed component has no advantage if the component
never remains INITIAL.
●
Boxed components are not too small
If the substructure or structured attribute is small, the memory savings cannot
counterbalance the 8-byte overhead for the reference.
●
Boxed components are used often
The memory savings through boxed components scale with the number of times the initial
structure is actually shared.
© Copyright. All rights reserved.
97
Unit 2: Program Calls and Memory Management
Hint:
This does not necessarily mean that the class or nested structure has to have
several instances within the same execution of the program. As the PXA exists
only once per server instance, you can also benefit from boxed components if the
system executes the program many times on the same server instance.
98
© Copyright. All rights reserved.
Lesson: Describing the ABAP Runtime and Memory Management
LESSON SUMMARY
You should now be able to:
●
Generate and activate programs
●
Explain the memory management of user sessions
●
Transfer data between programs
●
Analyze the memory management of deep data objects
●
Use boxed components
© Copyright. All rights reserved.
99
Unit 2
Lesson 3
Using Shared Objects
LESSON OVERVIEW
This lesson explains how you can save data as shared objects in shared memory, and
examines this concept and its implementation.
Business Example
You want to develop a transaction in which many users can access the same data
concurrently without having to read it from the database each time. You know that shared
objects can be used to make data in the main memory accessible across session boundaries.
Accordingly, you must familiarize yourself with this technique. For this reason, you require the
following knowledge:
●
An understanding of how classes are created for shared objects
●
An understanding of how you can use shared objects to implement applications
●
An understanding of how to access shared objects from within an ABAP program
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain shared objects
●
Use shared objects
Motivation for Shared Objects
You can save data as shared objects in shared memory, across different programs and even
different user sessions. Accordingly, you can create applications which write data to this area.
Other applications can then read this data later.
The Potential Uses for Shared Objects
●
Saving a catalog
An author writes the catalog to the shared objects area. Many users can then access this
catalog at the same time.
●
Saving a shopping cart
The buyer fills the shopping cart and the seller reads the filled shopping cart later.
100
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Shared Memory Areas
Figure 54: Memory Model of an Application Server
Shared memory is a memory area on an application server that the ABAP programs running
on the same server can access.
Before SAP introduced shared objects, ABAP statements had to use the EXPORT and
IMPORT statements with the SHARED BUFFER and SHARED MEMORY additions to access
this memory area. Instances of classes were active exclusively in the internal session of an
ABAP program. With the introduction of shared objects, shared memory has been enhanced
with Shared Objects Memory, where an application can save shared objects. You can save
shared objects in areas of shared memory.
Note:
Instances of classes can be saved. It is not yet possible to save any data objects as
shared objects. However, data objects (except for reference variables) can be
saved as attributes of classes.
© Copyright. All rights reserved.
101
Unit 2: Program Calls and Memory Management
Access Shared Objects
Figure 55: Accessing Shared Objects
The figure Accessing Shared Objects explains how shared objects can be accessed from
multiple user sessions simultaneously.
Shared Objects
●
Should be used for cross-program buffering of data that is read often, but rarely written.
●
Concurrent read accesses are supported by shared objects.
●
Access is controlled by a lock mechanism.
●
Data is saved as attributes of objects.
●
Memory bottlenecks result in runtime errors and have to be caught.
The write accesses should not be frequent because writing data to the shared objects area is
performance intensive. Specifically, you want to optimize runtime, which would not be the
case if write access were more frequent.
Note:
SAP also uses shared objects. For example, this technique is used to navigate in
the ABAP Workbench. In addition to saving memory which is around 3 MB per user
logon, navigation during the first access is faster by up to a factor of 100.
A prerequisite for saving an object in shared memory is that you need to define the class with
the SHARED MEMORY ENABLED addition in the CLASS statement (if the class is local), or if
102
© Copyright. All rights reserved.
Lesson: Using Shared Objects
the class is a global class, select the SHARED MEMORY ENABLED attribute in the Class
Builder.
Areas and Area Instances
Figure 56: Areas and Area Instances
An area is the template for area instances in shared memory. One area can generate several
area instances, which differ by name. In addition, an area instance can have several versions
which differ in their version IDs or version numbers. In the simplest case, without version
management, an area instance consists of a single area instance version.
Area Classes and Area Handles
Figure 57: Creating an Area
© Copyright. All rights reserved.
103
Unit 2: Program Calls and Memory Management
You define an area in transaction SHMA. This creates a global, final area class of the same
name. This is a subclass of CL_SHM_AREA. In an ABAP program, you can access the area
exclusively using methods of the generated area class.
Hint:
As the area and area class have the same name, it is advised to name the area
according to the naming conventions for classes - ZCL_*, for example, in the
customer namespace.
You can use static methods (Attach methods) of an area class to attach an ABAP program, or
its internal session where the system processes the ABAP program, to an area instance in
shared memory. When you attach an ABAP program, an instance of the area class is created
as an area handle.
The figure Creating an Area also illustrates another class, which is the area root class. You can
create any number of objects in an area instance, depending on your specific program. You
access these objects uniformly through the instance of the area root class.
Note:
In the following example, only two classes are used.
Creation of Objects in Shared Memory
Figure 58: Example Application
A simple catalog application will be used as an example, where shared objects will be used to
create a catalog of flight dates, so that users can select any flight quickly.
104
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Accessing Areas
Figure 59: Accessing Areas
The figure Accessing Areas highlights the fact that any programs can access objects in
shared objects memory. In this case, two applications, which run in different user sessions,
access objects in the same area.
For the example application, the requirements are as follows:
●
Creating an area
●
Developing a program to create an area instance
●
Developing a program to read data from the area
Shared Memory Area – Definition
Figure 60: Area Management
Shared objects are saved in areas of shared memory. You can use transaction SHMA to create
and manage areas and their attributes.
© Copyright. All rights reserved.
105
Unit 2: Program Calls and Memory Management
Hint:
Note that you have to call transaction code SHMA directly as it has not yet been
integrated into the Object Navigator (transaction SE80).
Call transaction code SHMA and enter the name of the area. The usual namespace rules apply,
which means the area name has to start with Y or Z in a customer system. The system also
supports namespaces containing slashes.
Hint:
Note that, for this area, the system generates an identically named global and
final area class as a subclass of CL_SHM_AREA. Therefore, it is advised to
choose the area name wisely, as shown in the example.
In an ABAP program, an area is accessed exclusively using methods of the generated area
class.
Maintenance of Areas
Figure 61: Maintaining Areas
After you choose one of the buttons Create, Change, or Display, the system displays the
maintenance screen for areas.
Each area is linked with a global area root class, whose attributes can contain proprietary data
and references to other shared memory-enabled classes. You have to assign the area root
class to an area when you maintain it. If an area instance version is not empty, it has to
106
© Copyright. All rights reserved.
Lesson: Using Shared Objects
contain at least an instance of the area root class as its root object, which the system uses to
reference other objects. When you generate the area class, the system generates and types a
ROOT attribute with the static type of the area root class.
Important properties of an area are as follows:
●
Client-dependent area
Areas, and thus the objects within an area, do not have a client ID by default. You can
however specify an area as client-dependent. In client-dependent areas, the methods of
the area class for accessing an area instance refer to the active client by default. You can
use the optional importing parameter CLIENT to access another client explicitly.
●
Transactional area
An area instance version of a transactional area is not active immediately after you remove
a change lock with the DETACH_COMMIT method. It is not active until the next database
commit. This is particularly helpful in implementing shopping carts in shared objects
memory.
Shared Memory Area – Write Access
Figure 62: Before Creating an Area Instance
Once you have defined an area, and created the classes that will be instantiated, you need to
understand the statements which can be used to create an area instance. The previous
example will continue to be used.
When you create an area, the system creates a global final class with the same name.
To set up an area or access an existing area, you need a reference variable typed with
reference to the generated area class. This reference serves as a handle for accessing the
area.
© Copyright. All rights reserved.
107
Unit 2: Program Calls and Memory Management
Area Instance Creation
Figure 63: Area Instance Creation
When you instantiate the area class, the system creates an instance of the area in shared
memory. The program has a handle for this instance of the area. It performs all future
operations using this handle.
108
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Object Generation in Shared Memory
Figure 64: Object Generation in Shared Memory
Once you create the area instance, you can create the objects in the shared objects memory.
To do so, use the AREA HANDLE addition for the CREATE OBJECT statement. This statement
informs the system about the area instance where it should create the objects.
© Copyright. All rights reserved.
109
Unit 2: Program Calls and Memory Management
Object Generation in Shared Memory II
Figure 65: Object Generation in Shared Memory II
The figure Object Generation in Shared Memory II illustrates how you can instantiate both
objects from within the program.
Alternatively, you can instantiate only the root object from within the program. You can create
the other objects in this area instance from the constructor of the root without assigning
references.
110
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Root Object Setting
Figure 66: Root Object Setting
To address the objects that you create in the area instance, assign the reference to the root
object to the ROOT attribute of the area handle. To do so, use the SET_ROOT method of the
area handle.
As a consequence, any program of any application can access this area and the objects inside
it. To do so, the application merely has to fetch a reference to the area instance, and can then
immediately access the objects contained in that area instance.
© Copyright. All rights reserved.
111
Unit 2: Program Calls and Memory Management
Write Lock Releasing
Figure 67: Write Lock Releasing
Read access of an area instance is not possible until the release of the write lock. To release
the lock, use the DETACH_COMMIT method, which is inherited by the area class from
CL_SHM_AREA.
Shared Memory Monitor
Figure 68: Shared Memory Monitor
The Shared Memory Monitor (Transaction SHMM) provides an overview of the area instances
in the shared objects memory of the current application server, and offers selected functions
for it.
112
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Note:
Use the CL_SHM_UTILITIES class to programmatically query the attributes of
area instances.
The monitor provides the following four overview screens which follow on from each other:
●
Areas
●
Area instances
●
Versions
●
Locks
Double-clicking a row in the current overview takes you to the next overview, for example,
from the overview of area instances to the list of versions of this area instance. From the
instance overview, you can display the list of locks on a parallel tab.
In the list of areas, area instances, and area instance versions, you can select a view that
groups the displayed data. The following views are available:
●
Overview (displays the most important data)
●
Locks (lock statistics)
●
Users (who created/modified the area)
●
Control (memory usage and so on)
●
All columns
Read Access to Shared Memory
Figure 69: Accessing an Existing Object in Shared Memory
© Copyright. All rights reserved.
113
Unit 2: Program Calls and Memory Management
Once an area instance has been set up, other users and applications can access it.
The reading programs have to implement the following steps:
1. The read program first needs a reference variable that is typed with reference to the area
class. This reference variable serves as a handle for the area instance access.
2. The program obtains the handle for the area instance using method ATTACH_FOR_READ
from the area class. This sets a read lock that prevents the system from deleting the area
instance during the access.
3. The objects in this area instance are now accessible by using the area handle.
Read Lock Cancellation
Figure 70: Read Lock Cancellation
Once the read activity is complete, the application releases the read lock using the method
DETACH of the area handle. The application automatically releases the read lock when the
internal session is closed after a DETACH statement.
114
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Shared Memory Area Versioning
Figure 71: Setting a Read Lock on the Active Version
When you create an area, you can specify that the system allows several versions of an area
instance.
The figure Setting a Read Lock on the Active Version shows an area instance that has been
set up. Once the setup is complete using method DETACH_COMMIT, and the system sends a
database commit, the area instance version is active.
© Copyright. All rights reserved.
115
Unit 2: Program Calls and Memory Management
Version Being Set Up
Figure 72: Version Being Set Up
If the NUMBER OF VERSIONS attribute of the area is set appropriately, additional versions of
the area instance can exist in addition to the active version.
When a new catalog is being set up, several temporary versions of the same area instance
exist concurrently. As soon as an application sets a change lock for an area instance, a
“version being set up” is created and exists in parallel to the active version.
116
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Write Complete – Previous Version is Outdated
Figure 73: Write Complete – Previous Version is Outdated
If you complete the setup of the new version during a read access of the currently active
version, the version being set up becomes active. The previously active version is given the
attribute OUTDATED.
© Copyright. All rights reserved.
117
Unit 2: Program Calls and Memory Management
New Read Locks for the New Active Version
Figure 74: New Read Locks for the New Active Version
The read locks for the outdated version remain until the read operations are complete. In
contrast, new read locks for the area instance are always set for the active version. Therefore,
two different readers can produce two different read results in this case.
118
© Copyright. All rights reserved.
Lesson: Using Shared Objects
No More Read Locks for Outdated Version – Version Expired
Figure 75: No More Read Locks for Outdated Version – Version Expired
When you remove the last existing read lock from an outdated version, the outdated version
expires. The garbage collector then deletes the expired version. You cannot set any locks for
expired versions, nor are they used to determine the number of versions (the latter is
important if the number of area instance versions has been restricted).
© Copyright. All rights reserved.
119
Unit 2: Program Calls and Memory Management
New Read Locks for Active Version
Figure 76: New Read Locks for Active Version
New read locks are always set for the active version. There can only be one active version for
each area instance. Depending on the maximum number of versions, several outdated
versions for which read locks are still set can exist in parallel to the new version.
120
© Copyright. All rights reserved.
Unit 2
Exercise 5
Use Shared Objects
Business Example
You want to run an Internet shop based on an SAP system. To give your Internet customers
the fastest possible access to your catalog, you save it in shared objects memory.
Write a program to manage and fill the catalog and develop a test application to read the data.
Template
None
Solution
CL_BC402_SHS_ROOT (global class)
CL_BC402_SHS_CATALOG (global class)
BC402_SHS_WRITE_CATALOG (executable program)
BC402_SHS_READ_CATALOG (executable program)
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Create a Global Catalog Class
Create a global class where the catalog data is to be saved (suggested name:
ZCL_BC402_##_CATALOG). This class requires a method for writing the catalog data and
another method for retrieving the data. It also requires a global attribute (an internal table) to
store the catalog data.
1. Create the global class for the catalog data. Note that this class has to be shared memoryenabled.
2. Create a private instance attribute in the class (suggested name: GT_CATALOG). For its
type, use a suitable table type that has structure SDYN_CONN as a line type.
3. Create a public instance method to fill the catalog (suggested name: FILL_CATALOG).
This method requires an importing parameter that will be passed the internal table with
data. Implement the method. Use the details in the following table:
Parameter
Type
Associated Type
IT_CATALOG
Importing
BC402_T_SDYNCONN
4. Create a second public instance method that can be used for flight date queries
(suggested name: GET_FLIGHTS). This method requires one importing parameter each
for the departure and destination cities, as well as two additional parameters for the
© Copyright. All rights reserved.
121
Unit 2: Program Calls and Memory Management
different flight dates. The method also needs an exporting parameter that returns the
matching flights. Implement the method. Use the details in the following table:
Parameter
Type
Associated Type
IV_FROM_CITY
Importing
S_FROM_CIT
IV_TO_CITY
Importing
S_TO_CITY
IV_EARLIEST
Importing
S_DATE
IV_LATEST
Importing
S_DATE
ET_FLIGHTS
Exporting
BC402_T_SDYNCONN
Create an Area in Shared Objects Memory
Create an area in shared objects memory (suggested name: ZCL_BC402_##_AREA).
1. Create the area root class. It should merely contain a reference to the catalog class that
you created in the first task. Look at model solution class CL_BC402_SHS_ROOT. Define a
public instance attribute using the information in the following table:
Attribute
Type
Associated Type
MO_CATALOG
TYPE REF TO
ZCL_BC402_##_CATALOG
2. Use transaction SHMA to create an area in shared memory. This area should have the
following attributes:
●
Client-Specific Area
●
With Versioning
●
Displacement Not Possible
You must specify a root class. Enter ZCL_BC402_##_ROOT, which you created in the
previous step.
Create an Executable Program to Write to Shared Memory
Create an executable program that builds the area in shared objects memory (suggested
name: ZBC402_##_WRITE_CATALOG). This program is also supposed to read the catalog data
from the database and pass it on to the appropriate class.
1. In SE80, create an executable program.
2. Define three reference variables, one each for the area handle, the area root class, and the
catalog class.
3. Create an area, an instance of the catalog class, and an instance of the area root class. Set
up the area.
Read the necessary catalog data from tables SPFLI and SFLIGHT.
4. Ensure to delete the write lock after the data is written successfully.
5. Execute the program and use the Shared Objects Monitor to examine the shared memory
area.
122
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Create an Executable Program to Read from Shared Memory
Implement a read program to read data from the area you just created (suggested name:
ZBC402_##_READ_CATALOG). Output the data in a simple user dialog (using the provided
function module BC402_DISPLAY_TABLE).
1. Create an executable program.
2. Define a selection screen in which the user can enter the departure and destination cities.
The user should also be able to enter an earliest and latest possible flight date.
3. Make sure the data is read from the catalog object. Output the data in the user dialog.
© Copyright. All rights reserved.
123
Unit 2
Solution 5
Use Shared Objects
Business Example
You want to run an Internet shop based on an SAP system. To give your Internet customers
the fastest possible access to your catalog, you save it in shared objects memory.
Write a program to manage and fill the catalog and develop a test application to read the data.
Template
None
Solution
CL_BC402_SHS_ROOT (global class)
CL_BC402_SHS_CATALOG (global class)
BC402_SHS_WRITE_CATALOG (executable program)
BC402_SHS_READ_CATALOG (executable program)
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Create a Global Catalog Class
Create a global class where the catalog data is to be saved (suggested name:
ZCL_BC402_##_CATALOG). This class requires a method for writing the catalog data and
another method for retrieving the data. It also requires a global attribute (an internal table) to
store the catalog data.
1. Create the global class for the catalog data. Note that this class has to be shared memoryenabled.
a) In SE80, in the unnamed dropdown list on the left of the screen, choose Class/
Interface and specify the name of the class ZCL_BC402_##_CATALOG.
b) Choose Display.
A Create Class/Interfacedialog box appears.
c) To create the class, choose Yes.
A Create Class ZCL_BC402_##_CATALOGdialog box appears.
d) In the Create Class ZCL_BC402_##_CATALOGdialog box, enter a description and
choose Save.
e) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
124
© Copyright. All rights reserved.
Lesson: Using Shared Objects
f) In the Prompt for transportable Workbench requestdialog box, choose Continue.
g) In the Object list, double-click the program name.
2. Create a private instance attribute in the class (suggested name: GT_CATALOG). For its
type, use a suitable table type that has structure SDYN_CONN as a line type.
a) With ZCL_BC402_##_CATALOG open in the Class Builder, in the Attributes tab,
choose the Display <-> Change button.
b) Create the attribute GT_CATALOG as a private, instance attribute, with
BC402_T_SDYNCONN in the Associated Type column and choose Save.
3. Create a public instance method to fill the catalog (suggested name: FILL_CATALOG).
This method requires an importing parameter that will be passed the internal table with
data. Implement the method. Use the details in the following table:
Parameter
Type
Associated Type
IT_CATALOG
Importing
BC402_T_SDYNCONN
a) With ZCL_BC402_##_CATALOG open in the Class Builder, choose the Methods tab.
b) In the Method column, enter FILL_CATALOG and set the method as a public, instance
method.
c) Place your cursor in the FILL_CATALOG cell and choose the Parameters button.
d) Enter the details in the table above and, on your keyboard, press the Enter key.
e) Choose the Code button and write the code.
f) See the source code excerpt from the model solution.
g) Choose the Check button.
h) Choose the Activate button.
4. Create a second public instance method that can be used for flight date queries
(suggested name: GET_FLIGHTS). This method requires one importing parameter each
for the departure and destination cities, as well as two additional parameters for the
different flight dates. The method also needs an exporting parameter that returns the
matching flights. Implement the method. Use the details in the following table:
Parameter
Type
Associated Type
IV_FROM_CITY
Importing
S_FROM_CIT
IV_TO_CITY
Importing
S_TO_CITY
IV_EARLIEST
Importing
S_DATE
IV_LATEST
Importing
S_DATE
ET_FLIGHTS
Exporting
BC402_T_SDYNCONN
a) With ZCL_BC402_##_CATALOG open in the Class Builder, choose the Methods tab.
b) In the Method column, enter GET_FLIGHTS and set the method as a public, instance
method.
© Copyright. All rights reserved.
125
Unit 2: Program Calls and Memory Management
c) Place your cursor in the GET_FLIGHTS cell and choose the Parameters button.
d) Enter the details in the table above and, on your keyboard, press the Enter key.
e) Choose the Code button and write the code.
f) See the source code excerpt from the model solution.
g) Choose the Check button.
h) Choose the Activate button.
Create an Area in Shared Objects Memory
Create an area in shared objects memory (suggested name: ZCL_BC402_##_AREA).
1. Create the area root class. It should merely contain a reference to the catalog class that
you created in the first task. Look at model solution class CL_BC402_SHS_ROOT. Define a
public instance attribute using the information in the following table:
Attribute
Type
Associated Type
MO_CATALOG
TYPE REF TO
ZCL_BC402_##_CATALOG
a) In the Class builder create the class ZCL_BC402_##_ROOT, choose the Properties
tab, and select the Shared-Memory Enabledcheckbox.
b) Choose the Attributes tab and enter the information in the table above.
c) Save and activate the class.
2. Use transaction SHMA to create an area in shared memory. This area should have the
following attributes:
●
Client-Specific Area
●
With Versioning
●
Displacement Not Possible
You must specify a root class. Enter ZCL_BC402_##_ROOT, which you created in the
previous step.
a) In the Command field, enter transaction code SHMA.
b) In the Shared Objects: Area Managementscreen, in the Area Name field, enter
ZCL_BC402_##_AREA and choose Create.
c) In the Create Area ZCL_BC402_##_AREAscreen, ensure that the Client-Specific Area
and With Versioning checkboxes are selected.
d) In the Displacement Typefield, ensure that Displacement Not Possibleis selected.
e) In the Description field, enter a description and, in the Root Class field, enter
ZCL_BC402_##_ROOT. Choose Save.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
g) In the Prompt for transportable Workbench requestdialog box, choose Continue.
126
© Copyright. All rights reserved.
Lesson: Using Shared Objects
Create an Executable Program to Write to Shared Memory
Create an executable program that builds the area in shared objects memory (suggested
name: ZBC402_##_WRITE_CATALOG). This program is also supposed to read the catalog data
from the database and pass it on to the appropriate class.
1. In SE80, create an executable program.
a) In the unnamed dropdown list on the left of the screen, choose Program and specify
the name of the program ZBC402_##_WRITE_CATALOG.
b) Choose Display.
A Create Program dialog box appears.
c) To create the program, choose Yes.
A Create Program dialog box appears.
d) In the Create Program dialog box, choose Continue.
e) In the ABAP: Program Attributes ZBC402_##_WRITE_CATALOG Changedialog box,
choose Save.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
g) In the Prompt for transportable Workbench requestdialog box, choose Continue.
h) In the Object list, double-click the program name.
2. Define three reference variables, one each for the area handle, the area root class, and the
catalog class.
a) See the source code excerpt from the model solution.
3. Create an area, an instance of the catalog class, and an instance of the area root class. Set
up the area.
Read the necessary catalog data from tables SPFLI and SFLIGHT.
a) See the source code excerpt from the model solution.
4. Ensure to delete the write lock after the data is written successfully.
a) See the source code excerpt from the model solution.
5. Execute the program and use the Shared Objects Monitor to examine the shared memory
area.
a) Execute the program.
b) To examine the details of the shared memory area instance, enter transaction code
SHMM.
Create an Executable Program to Read from Shared Memory
Implement a read program to read data from the area you just created (suggested name:
ZBC402_##_READ_CATALOG). Output the data in a simple user dialog (using the provided
function module BC402_DISPLAY_TABLE).
1. Create an executable program.
a) Return to SE80.
© Copyright. All rights reserved.
127
Unit 2: Program Calls and Memory Management
b) In the unnamed dropdown list on the left of the screen, choose Program and specify
the name of the program ZBC402_##_READ_CATALOG.
c) Choose Display.
A Create Program dialog box appears.
d) To create the program, choose Yes.
A Create Program dialog box appears.
e) In the Create Program dialog box, choose Continue.
f) In the ABAP: Program Attributes ZBC402_##_READ_CATALOG Changedialog box,
choose Save.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
h) In the Prompt for transportable Workbench requestdialog box, choose Continue.
i) In the Object list, double-click the program name.
2. Define a selection screen in which the user can enter the departure and destination cities.
The user should also be able to enter an earliest and latest possible flight date.
a) See the source code excerpt from the model solution.
3. Make sure the data is read from the catalog object. Output the data in the user dialog.
a) See the source code excerpt from the model solution.
Class CL_BC402_SHS_CATALOG: Implementation
METHOD FILL_CATALOG.
gt_catalog = it_catalog.
ENDMETHOD.
METHOD GET_FLIGHTS.
DATA gs_catalog LIKE LINE OF gt_catalog.
LOOP AT gt_catalog INTO gs_catalog
WHERE cityfrom =
cityto
=
fldate
>
fldate
<
iv_from_city AND
iv_to_city
AND
iv_earliest AND
iv_latest.
APPEND gs_catalog TO et_flights.
ENDLOOP.
* Alternative option using field symbols in the loop
*
*
*
*
*
*
*
*
128
FIELD-SYMBOLS:
<fs> TYPE sdyn_conn.
LOOP AT gt_catalog ASSIGNING <fs>
WHERE cityfrom
cityto
fldate
fldate
=
=
>
<
iv_from_city AND
iv_to_city
AND
iv_earliest AND
iv_latest.
© Copyright. All rights reserved.
Lesson: Using Shared Objects
*
*
*
*
APPEND <fs> TO et_flights.
ENDLOOP.
ENDMETHOD.
Program BC402_SHS_WRITE_CATALOG
REPORT
bc402_shs_write_catalog.
DATA:
go_handle TYPE REF TO cl_bc402_shs_area,
go_root
TYPE REF TO cl_bc402_shs_root,
go_catalog TYPE REF TO cl_bc402_shs_catalog,
gt_flights TYPE
bc402_t_sdynconn.
START-OF-SELECTION.
go_handle = cl_bc402_shs_area=>attach_for_write( ).
CREATE OBJECT go_root
AREA HANDLE go_handle.
CREATE OBJECT go_catalog AREA HANDLE go_handle.
go_root->mo_catalog = go_catalog.
go_handle->set_root( root = go_root ).
SELECT *
FROM spfli JOIN sflight
ON
spfli~carrid = sflight~carrid AND
spfli~connid = sflight~connid
INTO CORRESPONDING FIELDS OF TABLE gt_flights.
go_handle->root->mo_catalog->fill_catalog(
it_catalog = gt_flights ).
go_handle->detach_commit( ).
Program BC402_SHS_READ_CATALOG
REPORT
bc402_shs_read_catalog.
DATA:
go_handle
gt_flights
gs_flight
TYPE REF TO
TYPE
LIKE LINE OF
cl_bc402_shs_area,
bc402_t_sdynconn,
gt_flights,
gv_startdate TYPE sydatum,
© Copyright. All rights reserved.
129
Unit 2: Program Calls and Memory Management
gv_enddate
PARAMETERS:
pa_from
pa_to
SELECT-OPTIONS:
so_date
TYPE sydatum.
TYPE spfli-cityfrom,
TYPE spfli-cityto.
FOR sy-datum NO-EXTENSION.
AT SELECTION-SCREEN.
READ TABLE so_date INDEX 1.
IF so_date IS INITIAL.
so_date-low = sy-datum.
so_date-high = sy-datum + 365.
ENDIF.
gv_startdate = sy-datum.
gv_enddate
= sy-datum + 365.
IF so_date-low > sy-datum.
gv_startdate = sy-datum.
ENDIF.
IF so_date-high < gv_enddate.
gv_enddate = so_date-high.
ENDIF.
START-OF-SELECTION.
go_handle = cl_bc402_shs_area=>attach_for_read( ).
go_handle->root->mo_catalog->get_flights(
EXPORTING
iv_from_city = pa_from
iv_to_city
= pa_to
iv_earliest = gv_startdate
iv_latest
= gv_enddate
IMPORTING
et_flights
= gt_flights ).
go_handle->detach( ).
CALL FUNCTION 'BC402_DISPLAY_TABLE'
CHANGING
ct_table = gt_flights.
130
© Copyright. All rights reserved.
Lesson: Using Shared Objects
LESSON SUMMARY
You should now be able to:
●
Explain shared objects
●
Use shared objects
© Copyright. All rights reserved.
131
Unit 2: Program Calls and Memory Management
132
© Copyright. All rights reserved.
Unit 2
Learning Assessment
1. If you use the ___________________ statement, the system terminates the current program
and starts the transaction with transaction code T_CODE.
Choose the correct answer.
X
A SUBMIT
X
B AND RETURN
X
C LEAVE TO TRANSACTION 'T_CODE'
X
D CALL TRANSACTION 'T_CODE'
2. A saved or buffered LOAD is considered obsolete if the developed version of the program
was changed.
Determine whether this statement is true or false.
X
True
X
False
3. The modifiable parts of a program are created in memory in roll areas during every
execution. When the program is executed several times by the same user, each execution
has its own roll area. Which of the following is an example of modifiable parts of a
program?
Choose the correct answer.
X
A Byte code for statements
X
B Values of constants and literals
X
C Program texts
X
D Screen definitions
X
E Data objects (variables)
© Copyright. All rights reserved.
133
Unit 2: Learning Assessment
4. Which of the following are true when you activate a new object, for example a program?
Choose the correct answers.
X
A The object is saved
X
B The syntax of the object is checked
X
C The newly created version becomes the current active version
X
D An executable binary file is generated
5. How many external sessions are possible in SAP NetWeaver 7.0 and later?
Choose the correct answer.
X
A 4
X
B 8
X
C 16
X
D 32
6. Which of the following are options for transferring data between programs?
Choose the correct answers.
X
A Using the interface of the called program
X
B ABAP memory
X
C SAP memory
X
D Database tables
7. When working with internal tables, which statement can also delete the table header if it
takes up too much memory?
Choose the correct answer.
134
X
A CLEAR
X
B REFRESH
X
C FREE
© Copyright. All rights reserved.
Unit 2: Learning Assessment
8. To define boxed components outside of class definitions, you have to use the DATA
statement.
Determine whether this statement is true or false.
X
True
X
False
9. Shared memory is a memory area on an application server that the ABAP programs
running on that server can access.
Determine whether this statement is true or false.
X
True
X
False
10. When working with shared objects, method __________ of the area handle is available for
the application to release the read lock.
Choose the correct answer.
X
A DETACH_COMMIT
X
B OUTDATED
X
C DETACH
© Copyright. All rights reserved.
135
Unit 2
Learning Assessment - Answers
1. If you use the ___________________ statement, the system terminates the current program
and starts the transaction with transaction code T_CODE.
Choose the correct answer.
X
A SUBMIT
X
B AND RETURN
X
C LEAVE TO TRANSACTION 'T_CODE'
X
D CALL TRANSACTION 'T_CODE'
2. A saved or buffered LOAD is considered obsolete if the developed version of the program
was changed.
Determine whether this statement is true or false.
X
True
X
False
3. The modifiable parts of a program are created in memory in roll areas during every
execution. When the program is executed several times by the same user, each execution
has its own roll area. Which of the following is an example of modifiable parts of a
program?
Choose the correct answer.
136
X
A Byte code for statements
X
B Values of constants and literals
X
C Program texts
X
D Screen definitions
X
E Data objects (variables)
© Copyright. All rights reserved.
Unit 2: Learning Assessment - Answers
4. Which of the following are true when you activate a new object, for example a program?
Choose the correct answers.
X
A The object is saved
X
B The syntax of the object is checked
X
C The newly created version becomes the current active version
X
D An executable binary file is generated
5. How many external sessions are possible in SAP NetWeaver 7.0 and later?
Choose the correct answer.
X
A 4
X
B 8
X
C 16
X
D 32
6. Which of the following are options for transferring data between programs?
Choose the correct answers.
X
A Using the interface of the called program
X
B ABAP memory
X
C SAP memory
X
D Database tables
7. When working with internal tables, which statement can also delete the table header if it
takes up too much memory?
Choose the correct answer.
X
A CLEAR
X
B REFRESH
X
C FREE
© Copyright. All rights reserved.
137
Unit 2: Learning Assessment - Answers
8. To define boxed components outside of class definitions, you have to use the DATA
statement.
Determine whether this statement is true or false.
X
True
X
False
9. Shared memory is a memory area on an application server that the ABAP programs
running on that server can access.
Determine whether this statement is true or false.
X
True
X
False
10. When working with shared objects, method __________ of the area handle is available for
the application to release the read lock.
Choose the correct answer.
138
X
A DETACH_COMMIT
X
B OUTDATED
X
C DETACH
© Copyright. All rights reserved.
UNIT 3
Statements, Functions, and
Expressions for Simple Data
Lesson 1
Explaining the Differences Between Statements, Functions, and Expressions
140
Lesson 2
Using Numeric Data Types in Arithmetic Expressions
Exercise 6: Use Numeric Data Types and Arithmetic Expressions
144
153
Lesson 3
Processing Character Strings and Byte Strings Using Classical Options
Exercise 7: Process Character Strings
Exercise 8: Split a Character String into an Internal Table
163
167
179
Lesson 4
Processing Character Strings and Byte Strings Using Functions and Expressions
188
UNIT OBJECTIVES
●
Describe the differences between statements, expressions, and functions
●
Use arithmetic expressions
●
Process strings using ABAP statements
●
Use logical operators
●
Use date and time fields
●
Process strings using functions and expressions
●
Process strings using regular expressions
© Copyright. All rights reserved.
139
Unit 3
Lesson 1
Explaining the Differences Between
Statements, Functions, and Expressions
LESSON OVERVIEW
This lesson explains statements, functions, and expressions and their correct use. It also
explains the pitfalls of inline declarations.
Business Example
As a developer working for a travel agency, you are asked to implement a new algorithm for a
report on flight data. To do so, you must familiarize yourself with how to use statements,
functions, and expressions correctly. For this reason, you require the following knowledge:
●
An understanding of how statements, functions, and expressions can be used
●
An understanding of the various pitfalls of using inline declarations
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Describe the differences between statements, expressions, and functions
Statements and Functions in ABAP
Figure 77: Moving from Statements to Expressions
In the past, ABAP was a statement-oriented language. With Release SAP NetWeaver 7.02,
ABAP took the first step towards expression enabling.
140
© Copyright. All rights reserved.
Lesson: Explaining the Differences Between Statements, Functions, and Expressions
An expression in a programming language like ABAP is a combination of constants, variables,
operators, functions, and values that is evaluated at runtime and returns a result. It can
therefore be used in program statements in places where a constant or variable could also be
used.
The ABAP language originally had relatively limited support for expressions and was very
imperative, leading to the need for sequences of statements and intermediate variables to
calculate results used in subsequent statements. The situation has improved considerably
over the last years, for example with the introduction of method call chaining, lots of new
built-in functions, string expressions with the new concatenation operator && combined with
string templates, and the ability to write expressions at many operand positions.
In SAP NetWeaver 7.40, ABAP has become even more expression-oriented. More expressions
and more expression positions are now possible. ABAP now supports inline data and field
symbol declarations, constructor expressions and table expressions.
This allows you to write ABAP code in a style that corresponds more to what you may be
accustomed to in other programming languages such as C or Java. It allows you to express
more about “what” you want to calculate, and less about “how” you want to calculate it. You
do not have to write a statement for each intermediate step in the calculation and therefore
need fewer local variables which are only used once.
Expressions and Inline Declarations
Figure 78: Expressions
Expressions are possible in both writer and reader positions.
An expression in a writer position produces a result to which a value is assigned, whereas an
expression in a reader position produces a result that is used as an operand in the statement.
Logical expressions can contain calculation expressions (arithmetic expressions, string
expressions, and bit expressions) as relational expressions. The three different calculation
expression types cannot currently be mixed in a single calculation expression.
© Copyright. All rights reserved.
141
Unit 3: Statements, Functions, and Expressions for Simple Data
The following expressions can be constructed in certain operand positions:
●
●
Writer positions include the following:
-
Declaration expressions
-
Certain constructor expressions
-
Certain table expressions
Reader positions include the following:
-
Logical expressions
-
Constructor expressions
-
Table expressions
-
Arithmetic expressions
-
String expressions
-
Bit expressions
Inline Declarations
Figure 79: Examples of Inline Declarations
Inline declarations are a particularly interesting kind of expression. Inline declarations are a
new way of declaring variables and field symbols at operand positions.
In ABAP there are many operand positions, where the value of the operand is changed by the
statement. One example of these write positions is the left hand side lhs of an assignment:
lhs = rhs.
The data objects you can use at these write positions are either parameters of the procedure
you are working in (for example a method), or variables declared using the DATA statement.
In many cases the variables filled by a statement are “helper variables” that you only need
temporarily. For each of these helper variables you had to write a data declaration with the
DATA statement and a suitable type.
142
© Copyright. All rights reserved.
Lesson: Explaining the Differences Between Statements, Functions, and Expressions
However, the operand type of most write positions is fixed and known to the ABAP compiler.
This is what makes inline data declarations possible. Inline declarations involve the use of
declaration positions (write positions with a fully known operand type) and the new
declaration operator DATA(...).
A very simple example of this is as follows. Without the use of inline declarations, you can
write the following ABAP code:
DATA text TYPE string.
text = ‘Hello World’.
Using an inline declaration, the code is written as follows:
DATA(text) = ‘Hello World’.
Potential Pitfalls of the Use of Expressions
One of the possible problems with the extensive use of expressions is that your ABAP code
becomes very difficult to read and understand.
Figure 80: Potential Pitfalls of the Use of Expressions: Clarity of Code
LESSON SUMMARY
You should now be able to:
●
Describe the differences between statements, expressions, and functions
© Copyright. All rights reserved.
143
Unit 3
Lesson 2
Using Numeric Data Types in Arithmetic
Expressions
LESSON OVERVIEW
This lesson discusses how ABAP evaluates arithmetic expressions. It also discusses how the
result of a calculation can depend on which arithmetic operation you use, as well as how the
numeric types of the involved data objects influence the selection of the arithmetic
operations.
Business Example
You want to avoid unexpected inaccuracies in calculation results. Therefore, you want to
know how the system evaluates and processes arithmetic expressions in ABAP. For this
reason, you require the following knowledge:
●
An understanding of the differences between integer arithmetic, floating-point arithmetic,
and fixed-point arithmetic
●
An understanding of how the runtime environment evaluates arithmetic expressions
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use arithmetic expressions
Numeric Data Objects and Arithmetic Expressions
There are five numeric data types in ABAP, which differ in their inner representation of values
and maximum value range. Therefore, the data type that you choose for a data object
depends on its required value range. In addition, each of the five data types is linked to a
specific type of arithmetic, which you can use for calculations involving data objects of the
respective type.
You can differentiate between the following data types:
●
Type i
Integer arithmetic
●
Type p
Fixed-point arithmetic
●
Type f
Binary floating-point arithmetic
●
Type DECFLOAT16 and Type DECFLOAT34
Decimal floating-point arithmetic
144
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
In this lesson, pure arithmetic expressions (that is, expressions in which all of the involved
data objects have the same type) are discussed first. Then, mixed arithmetic expressions and
the way the runtime environment determines which arithmetic to use is analyzed.
Integers and Integer Arithmetic
Figure 81: Integers and Integer Arithmetic
The system represents whole numbers with type i internally as binary numbers with a length
of 4 bytes and they therefore have a value range of -2 31 to 2 31-1.
Calculations with integer arithmetic are faster than calculations with fixed-point or floatingpoint arithmetic because the system executes them directly using the processor’s arithmetic
command set.
The system rounds the non-integer results to the next whole number.
© Copyright. All rights reserved.
145
Unit 3: Statements, Functions, and Expressions for Simple Data
Caution:
In contrast to many other programming languages, integer arithmetic in ABAP
rounds to the next whole number.
Example:
DATA int TYPE i.
int
=
4 / 10.
"
==> 0
int
=
5 / 10.
"
==> 1
Moreover, all interim results also round to the closest integer.
Example:
DATA int TYPE i.
int
=
int
=
10 * ( 4
( 10 *
4
/ 10 ).
) / 10 .
" ==> 0
" ==> 4
If an interim result lies outside the value range of data type i, a runtime error
occurs.
Floating Point Numbers and Binary Floating Point Arithmetic
Figure 82: Binary Floating-Point Arithmetic
Floating point numbers are represented by binary precision floating point numbers. Floating
point numbers are normalized, and both the exponent and the mantissa are stored in binary
form. This representation complies with the Institute of Electrical and Electronic Engineers
(IEEE) norm for double precision floating-point numbers (IEEE-754).
146
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
Caution:
The binary floating point operations of the relevant processors are used for
calculations in floating point arithmetic. Because algorithms are converted to
binary, inaccuracies can occur. The extent and effect of these inaccuracies are
difficult to estimate.
Example of a Floating Point Number
The following is an example that can give you a better understanding. Suppose you want to
calculate 7.27% of 73050 and display the result accurate to two decimal places. The answer
should be 5310.74 (73050 * 0.0727 = 5310.735).
However, the program returns the following:
DATA: float TYPE f,
pack TYPE p DECIMALS 2.
float = 73050 * '0.0727'. " ==> 5.3107349999999997E+03
pack = float.
WRITE pack. " ==> 5310.73
Due to these effects, floating-point arithmetic is unsuitable for business calculations because
business calculations have to be exact and comply with legal rounding regulations. You
should, therefore, use floating-point numbers only for approximations. When you compare
floating-point numbers, always use intervals and round up the values at the end of your
calculations.
The main advantage of floating-point numbers is their large range of values, from
2.2250738585072014E-308 to 1.7976931348623157E+308, including both positive and
negative numbers and zero. In addition, you need to use floating-point numbers for special
aggregation functions of the SELECT statement.
© Copyright. All rights reserved.
147
Unit 3: Statements, Functions, and Expressions for Simple Data
Packed Numbers and Fixed Point Arithmetic
Figure 83: Packed Numbers and Fixed-Point Arithmetic
SAP introduced packed numbers in ABAP to expand the value range of decimal numbers, but
avoiding the rounding problems associated with floating-point numbers.
When you define packed numbers, you can determine the length of the number, specified in
bytes. The system determines the connection between the value range and the length from
the internal representation of packed numbers.
Each decimal digit is represented by a half-byte; the last byte is reserved for the plus or minus
sign.
The system derives the number of decimal digits from the number of bytes according to the
following rule: n digits = 2 n bytes -1.
The DECIMALS addition determines how many of these decimal digits are handled as decimal
places. The maximum number of decimal places is 14. However, the number must contain at
least one digit to the left of the decimal point.
Decimal point-aligned, fixed-point arithmetic is used for calculations. Packed numbers are
therefore well-suited to business calculations where the correct rounding to the specified
number of decimal places is important. The algorithm for this arithmetic is similar to using
"pencil and paper". Interim results initially use packed numbers with 31 decimal places. In
case of an overflow, the entire expression is calculated again with an internal accuracy of 63
decimal places. If another overflow occurs, an exception is raised, and can be handled.
148
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
Hint:
You can switch off fixed-point arithmetic in the program attributes. If you do
switch off fixed-point arithmetic, the DECIMALS addition for defining a packed
number affects only the output of the number. Internally, the system interprets
all numbers as integers, regardless of the position of the decimal point. Fixedpoint arithmetic is active by default. You should always accept this value and use
packed numbers for business calculations.
Decimal Floating Point Numbers
SAP introduced decimal floating-point numbers in SAP NetWeaver 7.0 EhP2 to overcome the
drawbacks of binary floating-point numbers.
Type f data objects cannot represent every decimal number precisely due to the internal
binary representation. Results of calculations may depend on the platform, there is no
rounding to a specific number of decimal places, division by powers of 10 is inexact, and no
uniform behavior exists across database systems.
Decimal floating-point numbers have a range larger than type f, while the calculation accuracy
is identical to type p.
Table 10: Decimal Floating Point Numbers
The two kinds of decimal floating point numbers are as follows:
Type
Memory Consumption
Digits
Range
Decfloat16
8 bytes
16
+/- 1.0E-383 through
+/- 1.0E385
Decfloat34
16 bytes
34
+/- 1.0E-6143
through +/1.0E6145
Hint:
In the ABAP dictionary, SAP has defined the corresponding data types
(DF16_<A> and DF34_<A>, where <A> can be DEC, RAW, or SCL).
Decimal floating-point arithmetic is used for calculations using data objects of type
DECFLOAT16 and DECFLOAT34. The algorithm for this arithmetic is similar to using "pencil
and paper". Interim results use numbers with 16 (decfloat16) or 34 (decfloat34) decimal
places. The largest number in the arithmetic expression defines the exponent. Numbers that
are too small (according to the exponent and the number of decimals defined by the type) are
rounded.
If an overflow occurs when working with DECFLOAT16, the system calculates the entire
expression again with an accuracy and number range based on type decfloat34. The same
applies if the number of decimals (16) is too small to store the intermediate result without
having to round. If another overflow occurs, an exception is raised and can be handled.
© Copyright. All rights reserved.
149
Unit 3: Statements, Functions, and Expressions for Simple Data
Mixed Arithmetic Expressions
Figure 84: Results of Arithmetic for Mixed Expressions
An arithmetic expression can contain a mix of all the numeric data types. If an arithmetic
expression contains at least one data object with a numeric type, it can also contain
character-type data objects, provided their contents can be interpreted as numbers. The
values contained in these character-type objects are converted to numeric type objects.
The system determines the arithmetic to be used based on the data types involved before it
performs the calculation. Different types of arithmetic have different degrees of internal
accuracy. Thus, the same arithmetic expression can lead to different results, depending on
the data types involved. The examples in the figure illustrate this.
In order to determine the arithmetic, the system takes into account the data types of all
operands along with the data type of the result field. After determining the arithmetic, the
system converts all operands to the numeric type that corresponds to the chosen arithmetic.
The system performs the calculations using these converted values and ultimately converts
the result to the desired result type.
Hint:
Remember that conversions affect performance. To avoid conversions, ensure
that all operands and the result field have the same numeric type.
150
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
Arithmetic Used for Mixed Expressions
Figure 85: Arithmetic Used for Mixed Expressions
Rules to Determine the Arithmetic Used for Mixed Expressions
●
The system uses decimal floating-point arithmetic if at least one operand or the result field
is of data type decfloat16 or decfloat34.
●
The system uses binary floating-point arithmetic if at least one operand or the result field
is of data type f and none of the operands is of data type decfloat16 or decfloat34.
●
The system uses fixed-point arithmetic, which is the default, if at least one operand or the
result field is of data type p and none of the operands or the result field is of data type f,
decfloat16, or decfloat34.
●
The system uses integer arithmetic in all other cases, that is, if all operands and the result
field are of data type i.
Caution:
When trigonometric functions, other scientific functions, logarithms, and
exponential functions (including the ** operator) are used, the system uses
binary floating-point arithmetic or decimal-floating point arithmetic for
calculation.
Example:
DATA int TYPE i.
int = ( 1 / 4 ) * ( 2 * 2 ). " ==> 0
int = ( 1 / 4 ) * ( 2 ** 2 ). " ==> 1
Exercise caution when using numeric literals with large amounts. They only have
data type i, if they do not exceed the value range of data type i.
Example:
DATA int TYPE i.
int = 1000000000 / 300000000 * 3. " ==> 9
int = 10000000000 / 3000000000 * 3. " ==> 10
© Copyright. All rights reserved.
151
Unit 3: Statements, Functions, and Expressions for Simple Data
152
© Copyright. All rights reserved.
Unit 3
Exercise 6
Use Numeric Data Types and Arithmetic
Expressions
Business Example
As part of a new application you are developing, you have to ensure that the numeric data
types are used correctly. To do so, you develop some test programs to see how calculations
are performed using the different numeric data types.
Create three programs to test the effects of the addition (+), subtraction (-), division (/),
multiplication (*), integer division (DIV), modulus (remainder of integer division) (MOD), and
power (**) operations on different numeric data types (one data type for each program).
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Perform Calculations on Type I Data Objects
Copy program BC402_IDT_CALCto the name ZBC402_##_CALC_I. This program has a
selection screen where you can enter two values. These entries are then copied to type i data
objects. Use these two values to implement the calculation operations and output the results
in a list.
1. Copy the template and all its subcomponents.
2. Perform the calculations in the START-OF-SELECTION event block in sequence. Display
the result of each calculation in the list. Generate a list line for each calculation operation
and output the values, the respective operator, and the result.
When creating your list, use the following example as a guide:
List Output
Calculating with integers
Operand 1 =
Operand 2 =
2
2
2
2
2
2
2
2
1
+
*
/
DIV
MOD
**
1
1
1
1
1
1
1
=
=
=
=
=
=
=
3
1
2
2
2
0
2
3. Activate and test the program.
© Copyright. All rights reserved.
153
Unit 3: Statements, Functions, and Expressions for Simple Data
4. Does the result match your expectations? What do you notice?
Perform Calculations on Floating-Point Numbers
Copy your program ZBC402_##_CALC_I(or use the model solution, BC402_IDS_CALC_I)
and name it ZBC402_##_CALC_F. Modify the program to test the effects of the calculation
operations described on floating-point numbers.
1. Copy the program.
2. Change the typing of data objects gv_val1, gv_val2, and gv_result so that the calculations
are now carried out with type f data objects.
3. Activate and test your program.
4. What do you observe about your result?
Perform Calculations on Packed Numbers
Copy your program ZBC402_##_CALC_I(or use the model solution, BC402_IDS_CALC_I)
and give it the name ZBC402_##_CALC_P. Modify the program to test the effects of the
calculation operations described on packed numbers.
1. Copy the program.
2. Change the typing of data objects gv_val1, gv_val2, and gv_result so that the calculations
are now carried out with type p data objects. Choose a suitable number of decimal places
(not 0) for each data object.
3. Activate and test your program.
4. What do you observe about your result?
5. Remove the fixed-point arithmetic attribute in the program attributes. Test your program.
6. What do you observe about the result?
154
© Copyright. All rights reserved.
Unit 3
Solution 6
Use Numeric Data Types and Arithmetic
Expressions
Business Example
As part of a new application you are developing, you have to ensure that the numeric data
types are used correctly. To do so, you develop some test programs to see how calculations
are performed using the different numeric data types.
Create three programs to test the effects of the addition (+), subtraction (-), division (/),
multiplication (*), integer division (DIV), modulus (remainder of integer division) (MOD), and
power (**) operations on different numeric data types (one data type for each program).
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Perform Calculations on Type I Data Objects
Copy program BC402_IDT_CALCto the name ZBC402_##_CALC_I. This program has a
selection screen where you can enter two values. These entries are then copied to type i data
objects. Use these two values to implement the calculation operations and output the results
in a list.
1. Copy the template and all its subcomponents.
a) To start the Object Navigator, enter transaction code SE80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_IDT_CALC.
c) Choose Display.
d) Right-click BC402_IDT_CALCand choose Copy....
e) In the Copy Program BC402_IDT_CALCdialog box, in the Target program field, enter
ZBC402_##_CALC_I and choose Copy.
f) In the Copy Program BC402_IDT_CALC to ZBC402_##_CALC_Idialog box, select all
checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Perform the calculations in the START-OF-SELECTION event block in sequence. Display
the result of each calculation in the list. Generate a list line for each calculation operation
and output the values, the respective operator, and the result.
When creating your list, use the following example as a guide:
© Copyright. All rights reserved.
155
Unit 3: Statements, Functions, and Expressions for Simple Data
List Output
Calculating with integers
Operand 1 =
Operand 2 =
2
2
2
2
2
2
2
2
1
+
*
/
DIV
MOD
**
1
1
1
1
1
1
1
=
=
=
=
=
=
=
3
1
2
2
2
0
2
a) See the source code excerpt from the model solution.
3. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
d) On the selection screen, choose the Execute button.
4. Does the result match your expectations? What do you notice?
When dividing with /, commercial rounding is applied to the result.
Perform Calculations on Floating-Point Numbers
Copy your program ZBC402_##_CALC_I(or use the model solution, BC402_IDS_CALC_I)
and name it ZBC402_##_CALC_F. Modify the program to test the effects of the calculation
operations described on floating-point numbers.
1. Copy the program.
a) To return to the Editor, choose the Back button twice.
b) In the unnamed dropdown menu, on the left of the screen, choose Program and
specify the name of the program ZBC402_##_CALC_I.
c) Choose Display.
d) Right-click ZBC402_##_CALC_Iand choose Copy....
e) In the Copy Program ZBC402_##_CALC_Idialog box, in the Target program field, enter
ZBC402_##_CALC_F and choose Copy.
f) In the Copy Program ZBC402_##_CALC_I to ZBC402_##_CALC_Fdialog box, select
all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Change the typing of data objects gv_val1, gv_val2, and gv_result so that the calculations
are now carried out with type f data objects.
a) See the source code excerpt from the model solution.
3. Activate and test your program.
156
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
d) On the selection screen, choose the Execute button.
4. What do you observe about your result?
The accuracy depends on the absolute size of the result, 17 places are always displayed.
Perform Calculations on Packed Numbers
Copy your program ZBC402_##_CALC_I(or use the model solution, BC402_IDS_CALC_I)
and give it the name ZBC402_##_CALC_P. Modify the program to test the effects of the
calculation operations described on packed numbers.
1. Copy the program.
a) To return to the Editor, choose the Back button twice.
b) In the unnamed dropdown menu, on the left of the screen, choose Program and
specify the name of the program ZBC402_##_CALC_I.
c) Choose Display.
d) Right-click ZBC402_##_CALC_Iand choose Copy....
e) In the Copy Program ZBC402_##_CALC_Idialog box, in the Target program field, enter
ZBC402_##_CALC_P and choose Copy.
f) In the Copy Program ZBC402_##_CALC_I to ZBC402_##_CALC_Pdialog box, select
all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Change the typing of data objects gv_val1, gv_val2, and gv_result so that the calculations
are now carried out with type p data objects. Choose a suitable number of decimal places
(not 0) for each data object.
a) See the source code excerpt from the model solution.
3. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
d) On the selection screen, choose the Execute button.
4. What do you observe about your result?
Commercial rounding is now performed for the last place of the result field. You can define
the accuracy of the calculation by typing the result field.
5. Remove the fixed-point arithmetic attribute in the program attributes. Test your program.
© Copyright. All rights reserved.
157
Unit 3: Statements, Functions, and Expressions for Simple Data
a) Return to the ABAP Editor screen and choose Goto → Attributes.
b) In the Different original and logon languagesdialog box, choose Maint. in orig. lang.
c) In the ABAP: Program Attributes ZBC402_##_CALC_P Changedialog box, deselect the
Fixed point arithmeticcheckbox and choose Save.
6. What do you observe about the result?
The results are not correct because the position of the decimal point was considered only
in the input and output but not during calculation.
a)
REPORT
bc402_ids_calc_i.
DATA:
gv_result
gv_val1
gv_val2
TYPE i,
TYPE i,
TYPE i.
" result variable
" first operand
" second operand
PARAMETERS:
pa_val1
pa_val2
TYPE i DEFAULT 5,
TYPE i DEFAULT 3.
" input variable 1
" input variable 2
START-OF-SELECTION.
* copy from parameters to data objects
gv_val1 = pa_val1.
gv_val2 = pa_val2.
WRITE: / text-001.
" <-- 'calculate with integer data'
SKIP 1.
WRITE: / text-002, gv_val1, " <-- 'operand 1 = '
/ text-003, gv_val2. " <-- 'operand 2 = '
SKIP 2.
* addition:
a + b
* subtraction:
a - b
gv_result = gv_val1 - gv_val2.
WRITE: / gv_val1, ' - ', gv_val2, ' = ', gv_result.
SKIP 1.
* division:
a / b
gv_result = gv_val1 / gv_val2.
WRITE: / gv_val1, ' / ', gv_val2, ' = ', gv_result.
SKIP 1.
* multiplication: a * b
gv_result = gv_val1 * gv_val2.
WRITE: / gv_val1, ' * ', gv_val2, ' = ', gv_result.
SKIP 1.
* div
gv_result = gv_val1 DIV gv_val2.
WRITE: / gv_val1, 'div', gv_val2, ' = ', gv_result.
SKIP 1.
158
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
* mod
gv_result = gv_val1 MOD gv_val2.
WRITE: / gv_val1, 'mod', gv_val2, ' = ', gv_result.
SKIP 1.
* power
gv_result = gv_val1 ** gv_val2.
WRITE: / gv_val1, '** ', gv_val2, ' = ', gv_result.
SKIP 1.
Calculating with floating-point numbers
REPORT
bc402_ids_calc_f.
DATA:
gv_result
gv_val1
gv_val2
TYPE f,
TYPE f,
TYPE f.
PARAMETERS:
pa_val1
pa_val2
TYPE i DEFAULT 5,
TYPE i DEFAULT 3.
" result variable
" first operand
" second operand
" input variable 1
" input variable 2
START-OF-SELECTION.
* copy from parameters to data objects
gv_val1 = pa_val1.
gv_val2 = pa_val2.
WRITE: / text-001.
" <-- 'calculate with float data'
SKIP 1.
WRITE: / text-002, gv_val1, " <-- 'operand 1 = '
/ text-003, gv_val2. " <-- 'operand 2 = '
SKIP 2.
* addition:
a + b
gv_result = gv_val1 + gv_val2.
WRITE: / gv_val1, ' + ', gv_val2, ' = ', gv_result.
SKIP 1.
* subtraction:
a - b
gv_result = gv_val1 - gv_val2.
WRITE: / gv_val1, ' - ', gv_val2, ' = ', gv_result.
SKIP 1.
* division:
a / b
gv_result = gv_val1 / gv_val2.
WRITE: / gv_val1, ' / ', gv_val2, ' = ', gv_result.
SKIP 1.
* multiplication: a * b
gv_result = gv_val1 * gv_val2.
WRITE: / gv_val1, ' * ', gv_val2, ' = ', gv_result.
SKIP 1.
* div
gv_result = gv_val1 DIV gv_val2.
© Copyright. All rights reserved.
159
Unit 3: Statements, Functions, and Expressions for Simple Data
WRITE: / gv_val1, 'div', gv_val2, ' = ', gv_result.
SKIP 1.
* mod
gv_result = gv_val1 MOD gv_val2.
WRITE: / gv_val1, 'mod', gv_val2, ' = ', gv_result.
SKIP 1.
* power
gv_result = gv_val1 ** gv_val2.
WRITE: / gv_val1, '** ', gv_val2, ' = ', gv_result.
SKIP 1.
Calculating with packed numbers
REPORT
bc402_ids_calc_p.
DATA:
gv_result
gv_val1
gv_val2
TYPE p LENGTH 8 DECIMALS 4, " result variable
TYPE p LENGTH 8 DECIMALS 2, " first operand
TYPE p LENGTH 8 DECIMALS 3. " second operand
PARAMETERS:
pa_val1
pa_val2
TYPE i DEFAULT 5,
TYPE i DEFAULT 3.
" input variable 1
" input variable 2
START-OF-SELECTION.
* copy from parameters to data objects
gv_val1 = pa_val1.
gv_val2 = pa_val2.
WRITE: / text-001.
" <-- 'calculate with packed data'
SKIP 1.
WRITE: / text-002, gv_val1, " <-- 'operand 1 = '
/ text-003, gv_val2. " <-- 'operand 2 = '
SKIP 2.
* addition:
a + b
gv_result = gv_val1 + gv_val2.
WRITE: / gv_val1, ' + ', gv_val2, ' = ', gv_result.
SKIP 1.
* subtraction:
a - b
gv_result = gv_val1 - gv_val2.
WRITE: / gv_val1, ' - ', gv_val2, ' = ', gv_result.
SKIP 1.
* division:
a / b
gv_result = gv_val1 / gv_val2.
WRITE: / gv_val1, ' / ', gv_val2, ' = ', gv_result.
SKIP 1.
* multiplication: a * b
gv_result = gv_val1 * gv_val2.
WRITE: / gv_val1, ' * ', gv_val2, ' = ', gv_result.
SKIP 1.
160
© Copyright. All rights reserved.
Lesson: Using Numeric Data Types in Arithmetic Expressions
* div
gv_result = gv_val1 DIV gv_val2.
WRITE: / gv_val1, 'div', gv_val2, ' = ', gv_result.
SKIP 1.
* mod
gv_result = gv_val1 MOD gv_val2.
WRITE: / gv_val1, 'mod', gv_val2, ' = ', gv_result.
SKIP 1.
* power
gv_result = gv_val1 ** gv_val2.
WRITE: / gv_val1, '** ', gv_val2, ' = ', gv_result.
SKIP 1.
© Copyright. All rights reserved.
161
Unit 3: Statements, Functions, and Expressions for Simple Data
LESSON SUMMARY
You should now be able to:
●
162
Use arithmetic expressions
© Copyright. All rights reserved.
Unit 3
Lesson 3
Processing Character Strings and Byte Strings
Using Classical Options
LESSON OVERVIEW
This lesson discusses the basic techniques for processing character-type data objects and
byte-type data objects using statements.
Business Example
You want to implement an application that processes and manipulates character strings and
need to familiarize yourself with the ABAP statements and techniques that enable you to do
so. For this reason, you require the following knowledge:
●
An understanding of operators to analyze byte strings and character strings
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Process strings using ABAP statements
●
Use logical operators
●
Use date and time fields
Classical Statements for Character and Byte String Processing
All elementary data objects with a byte-type data type (x, xstring) are byte-type data objects.
All elementary data objects with a character-type data type (c, n, d, t, string) are character
type data objects.
In non-Unicode systems, byte-type data objects, as well as all flat structures, can be handled
in the same way as character-type data objects. In Unicode systems, in contrast, you have to
differentiate clearly between byte-type and character-type data objects.
Moreover, you can only handle flat structures as character-type data objects if they consist
entirely of character-type components.
© Copyright. All rights reserved.
163
Unit 3: Statements, Functions, and Expressions for Simple Data
Figure 86: Overview – Statements for Character and Byte String Processing
The figure Overview-Statements for Character and Byte String Processing provides an
overview of the ABAP statements for processing character-type data objects.
In each of these statements, the operands are treated like type c fields, regardless of their
actual field type. They are not converted. All of the statements apart from TRANSLATE and
CONDENSE set system field sy-subrc.
Note:
As of SAP NetWeaver 7.0, the statement FIND replaces the statement SEARCH.
String and Byte Sequence Processing
Figure 87: String and Byte Sequence Processing
With the exception of CONDENSE and OVERLAY, you can also use the statements listed in the
figure Overview-Statements for Character and Byte String Processing to process byte-type
data objects. In a Unicode system, you have to use the IN BYTE MODE addition to ensure that
each byte is examined individually, and not in pairs.
The corresponding IN CHARACTER MODE addition is optional for processing character-type
data objects.
164
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
Subfield Access
Figure 88: Access with Offset and Length Specification for Elementary Data Objects
You can access a fragment of a character-type or byte-type data object directly by specifying
the appropriate offset and length.
The specifications for length and offset are interpreted as numbers of bytes for byte-type
data objects, and as numbers of characters for character-type objects (that is, one or two
bytes, depending on the system setting).
Access with Offset and Length Specifications for Structures
Figure 89: Access with Offset and Length Specifications for Structures
In flat structures, offset access is possible even if they are not completely character-type
(that is, only the first field(s) are character-type), provided the access does not go beyond the
character-type area.
Caution:
If possible, avoid using this method to access structure contents. Using
components and string operations makes your program much more reliable and
easier to read.
© Copyright. All rights reserved.
165
Unit 3: Statements, Functions, and Expressions for Simple Data
166
© Copyright. All rights reserved.
Unit 3
Exercise 7
Process Character Strings
Business Example
In a sequential file, records are available as long character strings. You want to extract these
records and process them further in an appropriate format.
Split a character string and convert the extracted data by copying it to data objects with
suitable types.
Note:
For simplicity, the data in the exercise is provided by a function module to be
called by the application you are developing. In practice, this function module
could read this data from a sequential file, which in turn might be generated by
an external system.
Note:
You will limit the further processing of data to outputting it in a list. In practice,
you would probably write the data to the SAP system database. In this exercise,
you want to implement the first step for string processing. You will write a
program that accepts the string, splits it into its components, and outputs them
in structured form.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy and Analyze a Program
Copy program BC402_IDT_DATA_SETto the name ZBC402_##_DATA_SET, where ## is your
group number. Analyze the program.
1. Copy the program and all its subcomponents.
2. What are the components of the program?
Analyze and Call Function Module BC402_CREATE_SEP_STRING
Analyze and test function module BC402_CREATE_SEP_STRING in the Object Navigator. Call
the function module in your program to provide a character string with the data to be
processed. At first, use the default values for all the IMPORT parameters.
© Copyright. All rights reserved.
167
Unit 3: Statements, Functions, and Expressions for Simple Data
1. Open the function module in the Object Navigator and run a test.
2. Leave all the IMPORT parameters set to their default values. Analyze the return value of
the function module. What is the structure of the character string?
3. Familiarize yourself with the interface for function module BC402_CREATE_SEP_STRING.
4. How can you use the function module parameters to affect the behavior of the function
module? The individual parameters are used for what purpose?
5. Define a data object (suggested name is gv_datastring) with data type string, in which
your program accepts the string from the function module.
6. Call the function module BC402_CREATE_SEP_STRING in the START-OF-SELECTION
processing block. Use the default value for each IMPORT parameter. If the function
module raises an exception, your program should issue the termination message 038
from message class BC402.
Remove the Separators from the Character String
1. Remove the separators at the start of the character string. Several options are available
for doing so. For example, you could use the SHIFT or REPLACE statements, with the
appropriate additions.
Hint:
Refer to the keyword documentation to learn about the possible additions for
these statements.
2. Remove the separators at the end of the character string. Again, use the SHIFT or
REPLACE statement. You can also use the FIND statement to search for character
sequence “##” and then use a length access to cut the string before the separator.
Split the Character String
Split the character string into (character-type) parts, to ensure that each part corresponds to
the contents of one field. Use a structure consisting of character fields. Each field of the
structure must be the same length as the corresponding component in the structure.
1. Define a structure type (suggested name is ty_s_flight_c) and a structure (suggested
name is gs_flight_c). Use type ty_s_flight_c for the structure.
The components in the structure type are as follows:
168
Component Name
Type
Length
mandt
c
3
carrid
c
3
connid
n
4
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
Component Name
Type
Length
fldate
n
8
price
c
20
currency
c
5
planetype
c
10
seatsmax
n
10
seatsocc
n
10
paymentsum
c
22
seatsmax_b
n
10
seatsocc_b
n
10
seatsmax_f
n
10
seatsocc_f
n
10
2. Why can’t components such as price, seatsmax, seatsocc, and so on, be set to numeric
types?
3. Why can’t the price component be set to type n?
Convert the Extracted Data
Convert the extracted data by copying it to data objects with suitable types. Refer to
components with type SFLIGHT in the ABAP Dictionary. Again, create the target fields as
components of a structure.
Hint:
The type of a target field determines its display format. If you assign a source
field to a target field of a different type, the runtime system converts it.
1. Define a structure type (suggested name is ty_s_flight) and a structure (suggested
name is gs_flight). Use type ty_s_flight for the structure.
Refer to component types with type SFLIGHT in the ABAP Dictionary.
The structure type should consist of the following components:
Component name
Type
carrid
sflight-carrid
connid
sflight-connid
fldate
sflight-fldate
© Copyright. All rights reserved.
169
Unit 3: Statements, Functions, and Expressions for Simple Data
Component name
Type
price
sflight-price
currency
sflight-currency
planetype
sflight-planetype
seatsmax
sflight-seatsmax
seatsocc
sflight-seatsocc
2. Copy the identically named components of the character-type structure gs_flight_c to the
fields of the structure gs_flight. Note the conversion rule that the system uses for the price
component.
Output the Contents of Structure gs_flight in a List
1. Display the contents of the structure in a list. Use the appropriate formatting options for
the WRITE statement for the fldate and price components.
2. Activate and test your program.
170
© Copyright. All rights reserved.
Unit 3
Solution 7
Process Character Strings
Business Example
In a sequential file, records are available as long character strings. You want to extract these
records and process them further in an appropriate format.
Split a character string and convert the extracted data by copying it to data objects with
suitable types.
Note:
For simplicity, the data in the exercise is provided by a function module to be
called by the application you are developing. In practice, this function module
could read this data from a sequential file, which in turn might be generated by
an external system.
Note:
You will limit the further processing of data to outputting it in a list. In practice,
you would probably write the data to the SAP system database. In this exercise,
you want to implement the first step for string processing. You will write a
program that accepts the string, splits it into its components, and outputs them
in structured form.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy and Analyze a Program
Copy program BC402_IDT_DATA_SETto the name ZBC402_##_DATA_SET, where ## is your
group number. Analyze the program.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_IDT_DATA_SET.
c) Choose Display.
d) Right-click BC402_IDT_DATA_SETand choose Copy....
© Copyright. All rights reserved.
171
Unit 3: Statements, Functions, and Expressions for Simple Data
e) In the Copy Program BC402_IDT_DATA_SETdialog box, in the Target program field,
enter ZBC402_##_DATA_SET and choose Copy.
f) In the Copy Program BC402_IDT_DATA_SET to ZBC402_##_DATA_SETdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. What are the components of the program?
The components are the declaration of a local program structure type (flagged as
comments) and a text pool with a list header.
Analyze and Call Function Module BC402_CREATE_SEP_STRING
Analyze and test function module BC402_CREATE_SEP_STRING in the Object Navigator. Call
the function module in your program to provide a character string with the data to be
processed. At first, use the default values for all the IMPORT parameters.
1. Open the function module in the Object Navigator and run a test.
a) On the toolbar, choose the Other Object button.
b) Select the Enhanced Optionsradio button.
c) Choose the Function Group tab.
d) Select the Function Module radio button.
e) In the corresponding field, enter BC402_CREATE_SEP_STRING.
f) Choose the Display button.
The function module will open in the Function Builder.
g) Choose the Test/Execute button.
2. Leave all the IMPORT parameters set to their default values. Analyze the return value of
the function module. What is the structure of the character string?
The character string consists of several short character sequences, each separated by the
“#” character. You also see double “#” characters at the start and end of the character
string.
3. Familiarize yourself with the interface for function module BC402_CREATE_SEP_STRING.
a) To return to the Function Builder, choose the Back button twice.
b) To analyze the parameters of the function module, choose each of the tabs.
172
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
4. How can you use the function module parameters to affect the behavior of the function
module? The individual parameters are used for what purpose?
You can use the following individual parameters: im_number: the number of table entries
to be read to make up the string, im_table_name: the name of the table to read,
im_separator: the separator for each individual field in the record, im_unique: are identical
records allowed.
5. Define a data object (suggested name is gv_datastring) with data type string, in which
your program accepts the string from the function module.
a) To return to the source code, choose the Previous Object button.
b) See the source code extract from the model solution.
6. Call the function module BC402_CREATE_SEP_STRING in the START-OF-SELECTION
processing block. Use the default value for each IMPORT parameter. If the function
module raises an exception, your program should issue the termination message 038
from message class BC402.
a) See the source code excerpt from the model solution.
Remove the Separators from the Character String
1. Remove the separators at the start of the character string. Several options are available
for doing so. For example, you could use the SHIFT or REPLACE statements, with the
appropriate additions.
Hint:
Refer to the keyword documentation to learn about the possible additions for
these statements.
a) See the source code excerpt from the model solution.
2. Remove the separators at the end of the character string. Again, use the SHIFT or
REPLACE statement. You can also use the FIND statement to search for character
sequence “##” and then use a length access to cut the string before the separator.
a) See the source code excerpt from the model solution.
Split the Character String
Split the character string into (character-type) parts, to ensure that each part corresponds to
the contents of one field. Use a structure consisting of character fields. Each field of the
structure must be the same length as the corresponding component in the structure.
1. Define a structure type (suggested name is ty_s_flight_c) and a structure (suggested
name is gs_flight_c). Use type ty_s_flight_c for the structure.
The components in the structure type are as follows:
Component Name
Type
Length
mandt
c
3
carrid
c
3
connid
n
4
fldate
n
8
© Copyright. All rights reserved.
173
Unit 3: Statements, Functions, and Expressions for Simple Data
Component Name
Type
Length
price
c
20
currency
c
5
planetype
c
10
seatsmax
n
10
seatsocc
n
10
paymentsum
c
22
seatsmax_b
n
10
seatsocc_b
n
10
seatsmax_f
n
10
seatsocc_f
n
10
a) See the source code excerpt from the model solution.
2. Why can’t components such as price, seatsmax, seatsocc, and so on, be set to numeric
types?
When you split the character string, this first results in character-type parts. You have to
convert them to numeric data types in a second step.
3. Why can’t the price component be set to type n?
The corresponding parts also contain decimal points, but the decimal point is not in the
value range of type n.
Convert the Extracted Data
Convert the extracted data by copying it to data objects with suitable types. Refer to
components with type SFLIGHT in the ABAP Dictionary. Again, create the target fields as
components of a structure.
Hint:
The type of a target field determines its display format. If you assign a source
field to a target field of a different type, the runtime system converts it.
1. Define a structure type (suggested name is ty_s_flight) and a structure (suggested
name is gs_flight). Use type ty_s_flight for the structure.
Refer to component types with type SFLIGHT in the ABAP Dictionary.
The structure type should consist of the following components:
174
Component name
Type
carrid
sflight-carrid
connid
sflight-connid
fldate
sflight-fldate
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
Component name
Type
price
sflight-price
currency
sflight-currency
planetype
sflight-planetype
seatsmax
sflight-seatsmax
seatsocc
sflight-seatsocc
a) See the source code excerpt from the model solution.
2. Copy the identically named components of the character-type structure gs_flight_c to the
fields of the structure gs_flight. Note the conversion rule that the system uses for the price
component.
a) See the source code excerpt from the model solution.
Output the Contents of Structure gs_flight in a List
1. Display the contents of the structure in a list. Use the appropriate formatting options for
the WRITE statement for the fldate and price components.
a) See the source code excerpt from the model solution.
2. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_ids_data_set MESSAGE-ID bc402.
TYPES:
BEGIN OF ty_s_flight_c,
mandt
TYPE c LENGTH
carrid
TYPE c LENGTH
connid
TYPE n LENGTH
fldate
TYPE n LENGTH
price
TYPE c LENGTH
currency
TYPE c LENGTH
planetype TYPE c LENGTH
seatsmax
TYPE n LENGTH
seatsocc
TYPE n LENGTH
paymentsum TYPE c LENGTH
seatsmax_b TYPE n LENGTH
seatsocc_b TYPE n LENGTH
seatsmax_f TYPE n LENGTH
seatsocc_f TYPE n LENGTH
END OF ty_s_flight_c,
3,
3,
4,
8,
20,
5,
10,
10,
10,
22,
10,
10,
10,
10,
BEGIN OF ty_s_flight,
carrid
TYPE sflight-carrid,
connid
TYPE sflight-connid,
fldate
TYPE sflight-fldate,
price
TYPE sflight-price,
© Copyright. All rights reserved.
175
Unit 3: Statements, Functions, and Expressions for Simple Data
currency
TYPE sflight-currency,
planetype TYPE sflight-planetype,
seatsmax
TYPE sflight-seatsmax,
seatsocc
TYPE sflight-seatsocc,
END OF ty_s_flight.
DATA:
gv_datastring
gv_set_string
gv_offset
gs_flight_c
gs_flight
TYPE
TYPE
TYPE
TYPE
TYPE
string,
string,
i,
ty_s_flight_c,
ty_s_flight.
START-OF-SELECTION.
* retrieve character string with data
CALL FUNCTION 'BC402_CREATE_SEP_STRING'
*
EXPORTING
*
im_number
= '1'
*
im_table_name = 'SFLIGHT'
*
im_separator = '#'
*
im_unique
= 'X'
IMPORTING
ex_string
= gv_datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038.
ENDIF.
* remove leading and trailing separators
* solution 1 - SHIFT, FIND & Offset access
gv_set_string = gv_datastring.
SHIFT gv_set_string BY 2 PLACES.
FIND '##' IN gv_set_string
MATCH OFFSET gv_offset.
IF sy-subrc = 0.
gv_set_string = gv_set_string(gv_offset).
ENDIF.
* solution 2 - REPLACE
* gv_set_string = gv_datastring.
* REPLACE ALL OCCURRENCES OF '##'
*
IN gv_set_string WITH ''.
* solution 3 - SHIFT CIRCULAR & SHIFT
* gv_set_string = gv_datastring.
* SHIFT gv_set_string RIGHT CIRCULAR BY 2 PLACES.
* SHIFT gv_set_string LEFT BY 4 PLACES.
*
* solution 4 - SHIFT DELETING
* gv_set_string = gv_datastring.
* SHIFT gv_set_string LEFT DELETING LEADING '#'.
* SHIFT gv_set_string RIGHT DELETING TRAILING '#'.
* SHIFT gv_set_string LEFT DELETING LEADING ' '.
* split into (charlike) fragments corresponding to components
SPLIT gv_set_string AT '#' INTO
gs_flight_c-mandt
176
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
gs_flight_c-carrid
gs_flight_c-connid
gs_flight_c-fldate
gs_flight_c-price
gs_flight_c-currency
gs_flight_c-planetype
gs_flight_c-seatsmax
gs_flight_c-seatsocc
gs_flight_c-paymentsum
gs_flight_c-seatsmax_b
gs_flight_c-seatsocc_b
gs_flight_c-seatsmax_f
gs_flight_c-seatsocc_f.
* convert fragments into proper data types
MOVE-CORRESPONDING gs_flight_c TO gs_flight.
* output result
WRITE: /
gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate DD/MM/YYYY,
gs_flight-price CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
© Copyright. All rights reserved.
177
Unit 3: Statements, Functions, and Expressions for Simple Data
178
© Copyright. All rights reserved.
Unit 3
Exercise 8
Split a Character String into an Internal Table
Business Example
You want to enhance your program to save each record in the string in a separate line of an
internal table. From this table, you will then separate the individual records into their
elementary components and output them.
Note:
The character string from the exercise on character string processing will now
contain more than one data record. Enhance your program to save each record
in the string in a separate line of an internal table.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Use Function Module BC402_IDS_DATA_SET to Generate a String Containing Multiple
Records
Copy program BC402_IDS_DATA_SET (or your own program, ZBC402_##_DATA_SET) to
the name ZBC402_##_SPLIT_ITAB. Make sure the string contains more than one record
1. Copy the program and all its subcomponents.
2. Use function module BC402_CREATE_SEP_STRING to generate a string of 30 records. To
do this, supply parameter IM_NUMBER with an appropriately typed constant (suggested
name is C_NUMBER).
Break the Character String into Parts
After removing the separators at the start and end of the character string, break the
character string down into parts, each of which corresponds to a single record. Use the option
of specifying an internal table with an elementary, character-type line type as the target of the
SPLIT statement.
1. Check (for example, in the debugger) whether the technique used in the program for
removing the separators at the start and end of the string works even if the string contains
multiple records. What do you have to take into account here?
2. Define a standard, single-column internal table. The lines of the internal table should have
data type STRING (suggested name is IT_SETS).
© Copyright. All rights reserved.
179
Unit 3: Statements, Functions, and Expressions for Simple Data
3. Implement a new SPLIT statement directly before the existing SPLIT statement in which
you fill the internal table with the partial character strings. Split the character string so
that each partial string corresponds to exactly one record.
4. Make sure that the split into individual records, type conversion, and output of the
components occurs in a consecutive loop for all lines in the internal table.
5. Activate and test your program.
180
© Copyright. All rights reserved.
Unit 3
Solution 8
Split a Character String into an Internal Table
Business Example
You want to enhance your program to save each record in the string in a separate line of an
internal table. From this table, you will then separate the individual records into their
elementary components and output them.
Note:
The character string from the exercise on character string processing will now
contain more than one data record. Enhance your program to save each record
in the string in a separate line of an internal table.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Use Function Module BC402_IDS_DATA_SET to Generate a String Containing Multiple
Records
Copy program BC402_IDS_DATA_SET (or your own program, ZBC402_##_DATA_SET) to
the name ZBC402_##_SPLIT_ITAB. Make sure the string contains more than one record
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code SE80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_DATA_SET.
c) Choose Display.
d) Right-click ZBC402_##_DATA_SETand choose Copy....
e) In the Copy Program ZBC402_##_DATA_SETdialog box, in the Target program field,
enter ZBC402_##_SPLIT_ITAB and choose Copy.
f) In the Copy Program ZBC402_##_DATA_SET to ZBC402_##_SPLIT_ITABdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Use function module BC402_CREATE_SEP_STRING to generate a string of 30 records. To
do this, supply parameter IM_NUMBER with an appropriately typed constant (suggested
name is C_NUMBER).
a) See the source code excerpt from the model solution.
© Copyright. All rights reserved.
181
Unit 3: Statements, Functions, and Expressions for Simple Data
Break the Character String into Parts
After removing the separators at the start and end of the character string, break the
character string down into parts, each of which corresponds to a single record. Use the option
of specifying an internal table with an elementary, character-type line type as the target of the
SPLIT statement.
1. Check (for example, in the debugger) whether the technique used in the program for
removing the separators at the start and end of the string works even if the string contains
multiple records. What do you have to take into account here?
When multiple records are present, they are separated by the “##” character
combination. This can result in problems when you search for this pattern with the FIND or
REPLACE statements.
2. Define a standard, single-column internal table. The lines of the internal table should have
data type STRING (suggested name is IT_SETS).
a) See the source code excerpt from the model solution.
3. Implement a new SPLIT statement directly before the existing SPLIT statement in which
you fill the internal table with the partial character strings. Split the character string so
that each partial string corresponds to exactly one record.
a) See the source code excerpt from the model solution.
4. Make sure that the split into individual records, type conversion, and output of the
components occurs in a consecutive loop for all lines in the internal table.
a) See source code excerpt from the model solution.
5. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT bc402_ids_split_itab MESSAGE-ID bc402.
TYPES:
BEGIN OF ty_s_flight_c,
mandt
TYPE c LENGTH
carrid
TYPE c LENGTH
connid
TYPE n LENGTH
fldate
TYPE n LENGTH
price
TYPE c LENGTH
currency
TYPE c LENGTH
planetype TYPE c LENGTH
seatsmax
TYPE n LENGTH
seatsocc
TYPE n LENGTH
paymentsum TYPE c LENGTH
seatsmax_b TYPE n LENGTH
seatsocc_b TYPE n LENGTH
seatsmax_f TYPE n LENGTH
seatsocc_f TYPE n LENGTH
3,
3,
4,
8,
20,
5,
10,
10,
10,
22,
10,
10,
10,
10,
END OF ty_s_flight_c,
182
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
BEGIN OF ty_s_flight,
carrid
TYPE sflight-carrid,
connid
TYPE sflight-connid,
fldate
TYPE sflight-fldate,
price
TYPE sflight-price,
currency
TYPE sflight-currency,
planetype TYPE sflight-planetype,
seatsmax
TYPE sflight-seatsmax,
seatsocc
TYPE sflight-seatsocc,
END OF ty_s_flight.
CONSTANTS c_number TYPE i VALUE 30.
DATA:
gv_datastring
gv_set_string
gs_flight_c
gs_flight
TYPE
TYPE
TYPE
TYPE
string,
string,
ty_s_flight_c,
ty_s_flight.
DATA:
gt_sets TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY.
START-OF-SELECTION.
* retrieve character string with data (several data sets
* this time)
CALL FUNCTION 'BC402_CREATE_SEP_STRING'
EXPORTING
im_number
= c_number
*
im_table_name = 'SFLIGHT'
*
im_separator = '#'
*
im_unique
= 'X'
IMPORTING
ex_string
= gv_datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038.
ENDIF.
* remove leading and trailing separators
* solution 1 - doesn't work here
* gv_set_string = gv_datastring.
* SHIFT gv_set_string BY 2 PLACES.
* FIND '##' IN gv_set_string
*
MATCH OFFSET gv_offset.
* IF sy-subrc = 0.
*
gv_set_string = gv_set_string(gv_offset).
* ENDIF.
* solution 2 - doesn't work here
* gv_set_string = gv_datastring.
* REPLACE ALL OCCURRENCES OF '##'
*
IN gv_set_string WITH ''.
* solution 3 - works fine
gv_set_string = gv_datastring.
SHIFT gv_set_string RIGHT CIRCULAR BY 2 PLACES.
SHIFT gv_set_string LEFT BY 4 PLACES.
© Copyright. All rights reserved.
183
Unit 3: Statements, Functions, and Expressions for Simple Data
* solution 4 - works fine
* gv_set_string = gv_datastring.
* SHIFT gv_set_string LEFT DELETING LEADING '#'.
* SHIFT gv_set_string RIGHT DELETING TRAILING '#'.
* SHIFT gv_set_string LEFT DELETING LEADING ' '.
*
split into fragments, each corresponding to one data set
SPLIT gv_set_string AT '##' INTO TABLE gt_sets.
LOOP AT gt_sets INTO gv_set_string.
*
split into (charlike) fragments corresponding to components
SPLIT gv_set_string AT '#' INTO
gs_flight_c-mandt
gs_flight_c-carrid
gs_flight_c-connid
gs_flight_c-fldate
gs_flight_c-price
gs_flight_c-currency
gs_flight_c-planetype
gs_flight_c-seatsmax
gs_flight_c-seatsocc
gs_flight_c-paymentsum
gs_flight_c-seatsmax_b
gs_flight_c-seatsocc_b
gs_flight_c-seatsmax_f
gs_flight_c-seatsocc_f.
*
convert fragments into proper data types
MOVE-CORRESPONDING gs_flight_c TO gs_flight.
* output result
WRITE: / gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate DD/MM/YYYY,
gs_flight-price CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
ENDLOOP.
184
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
Logical Operators
The following operators are available to compare the content of character-type data objects:
CO, CN, CA, NA, CS, NS, CP, and NP. With the introduction of Unicode, corresponding
operators with the prefix BYTE- are available for byte-type data objects.
Figure 90: Comparison Operators
Date and Time Fields
Figure 91: Date Fields
© Copyright. All rights reserved.
185
Unit 3: Statements, Functions, and Expressions for Simple Data
ABAP uses separate data types for dates and times. They are character-type data types that
consist of eight and six numeric characters, respectively. However, these data types also have
a number of special attributes.
The special attributes are as follows:
●
For input and output, the preferences for the current users are taken into account for
formatting of the data.
●
If a data object with type D is used in arithmetic expressions or assigned to a numeric data
object, its contents are converted to the number of days since January 1, 0001.
●
If a data object with type T is used in arithmetic expressions or assigned to a numeric data
object, its contents are converted to the number of seconds since midnight.
Caution:
If you have to specify start values for date or time fields (in the VALUE addition of
the DATA statement), the value must be supplied as a text literal. This is because
numeric literals have type I, which means they would be interpreted incorrectly
as the number of days.
186
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Classical Options
LESSON SUMMARY
You should now be able to:
●
Process strings using ABAP statements
●
Use logical operators
●
Use date and time fields
© Copyright. All rights reserved.
187
Unit 3
Lesson 4
Processing Character Strings and Byte Strings
Using Functions and Expressions
LESSON OVERVIEW
This lesson discusses other new techniques for processing character-type data objects and
byte-type data objects through functions and expressions. By using these functions and
expressions, you can simplify your code and make it easier to read.
Business Example
You want to implement an application that processes and manipulates character strings and
need to familiarize yourself with the newer techniques that enable you to do so. For this
reason, you require the following knowledge:
●
An understanding of string templates to define character strings
●
An understanding of regular expressions to define search patterns
LESSON OBJECTIVES
After completing this lesson, you will be able to:
188
●
Process strings using functions and expressions
●
Process strings using regular expressions
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Functions and Expressions
String Functions
Figure 92: Examples of Descriptive String Functions
As well as ABAP statements, predefined ABAP functions can be used to analyze character
strings and byte strings.
ABAP functions are divided into three groups as follows:
●
Descriptive functions (returning a numeric result)
●
Processing functions (returning a character-type result)
●
Predicate functions (returning TRUE or FALSE)
Predicate functions can only be used as conditions in control statements, as arguments of
Boolean functions, or in relationships with Boolean operators. Important descriptive string
functions for character-type arguments can be used to determine the length of strings, to find
character patterns in strings, or to count the occurrence of character patterns in strings.
To determine the occupied length of a string, use the standard function STRLEN( ). The
corresponding function, XSTRLEN( ), is available for byte-type data objects.
© Copyright. All rights reserved.
189
Unit 3: Statements, Functions, and Expressions for Simple Data
Examples of Processing Functions
Figure 93: Examples of Processing Functions
Processing functions have a character-like result. They can be declared at general expression
positions and character-like expression positions. The return values have the type string.
As well as those displayed in the figure, the following processing functions are available:
190
●
Cmax and cmin – return the values of the largest / smallest character-like argument
●
Concat_lines_of – concatenates all row contents of an internal table and returns the result
as a character string
●
Escape - takes the content of a character string, and hides certain special characters with
escape characters according to a specified rule
●
Match - returns a subfield of a character-like argument that matches a regular expression
●
Repeat - returns a character string that contains content repeated as many times as
specified
●
Reverse – returns a reversed character string
●
To_lower - converts all letters in the character string to lowercase letters
●
To_mixed - converts all letters in the character string to lowercase letters from the second
position
●
From_mixed – inserts an underscore before each uppercase letter (from left to right and
from the second position). A different separator can be specified if an underscore is not
suitable
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Functions and Expressions
●
Translate – replaces characters in a character string
For full details about all of the processing functions, including their parameters and examples,
see the ABAP Keyword documentation.
Examples of Predicate Functions
Figure 94: Examples of Predicate Functions
Finally, two predictive functions exist: CONTAINS...() and MATCHES().
These can be used to find out if a certain substring or search pattern exists in a character
string. MATCHES( ) accepts regular expressions only, while CONTAINS...( ) also supports
strings defining search patterns. In addition, CONTAINS...( ) allows you to check for multiple
occurrences of search patterns.
The code samples listed in the figure represent frequently used variants of these functions,
but some of them contain additional interface parameters not shown.
Depending on the function, the following interface parameters may be permitted:
●
val: String to be analyzed.
●
sub: Substring or search pattern.
●
regex: Regular expression defining search pattern.
●
off, len: Offset and length, used to restrict operation on segment of string.
●
occ: Number of matches that are to be searched for in the search range (integer value).
Counted from the right if negative.
If invalid values are assigned to the interface parameters, catchable exceptions are raised.
© Copyright. All rights reserved.
191
Unit 3: Statements, Functions, and Expressions for Simple Data
See the ABAP Keyword documentation for full details of the interface parameters for each
function.
String Expressions and String Templates
Figure 95: String Expressions and String Templates
Hint:
This section describes functionality available as of SAP NetWeaver 7.0 EhP 2.
A string expression formulates an operation with character-like operands. The result of a
string expression is a character string. A string expression consists either of one string
template or of two or more operands concatenated as a character string using the string
operator &&. Each of the operands can itself be a string template.
Note:
In operands with a fixed length, trailing blanks are not taken into account.
A string template is enclosed in two “|” characters. A string template defines a character
string. The character string is determined by any sequence of the following syntax elements:
192
●
Text literals
●
Embedded expressions such as, data objects, calculated expressions, predefined
functions, or function methods surrounded by { }
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Functions and Expressions
●
Control characters
Note:
A string template that starts with “|” must be closed with “|” within the same line
of source code. The only exceptions to this rule are line breaks in embedded
expressions.
String templates can only be specified in Unicode programs.
The data type of the expression must be an elementary data type and the value of the
expression must be character-type or must be convertible to a string.
Formatting Options for Embedded Expressions
Figure 96: Formatting Options for Embedded Expressions
When a string template is analyzed, the value of each embedded expression is converted to a
character string. By default, the string is formatted according to the data type of the
expression (predefined formatting). However, a number of formatting options can be used
with the embedded expression. Formatting options have to be listed in the delimiting
characters ({, }) behind the expression.
Formatting Options that can be used in String Expressions
●
width
Output length (decreasing minimum length is not possible)
●
align
Output alignment (left, center, or right)
●
pad
Replacement sign for excess spaces in output string
© Copyright. All rights reserved.
193
Unit 3: Statements, Functions, and Expressions for Simple Data
●
case
Letter format (upper case, lower case, or raw)
●
sign
Visibility and position of sign in numeric type expressions
●
exponent
Exponent value for numeric expressions
●
decimals
Number of decimal places for numeric expressions
●
zero
Visibility of value 0 for numeric expressions (yes or no)
●
style
Output style for numeric expressions (for example, position of sign, usage of exponent)
●
currency
Number of decimal spaces when formatting expressions of type i, p, or f, valid values are
defined in database table TCURC, column WAERS
●
number
Format of decimal and thousand separators for numeric expressions
●
date
Format for expressions of type d
●
time
Format for expressions of type t
●
timestamp
Format for expressions of type timestamp or timestampl (both data elements defined in
ABAP Dictionary)
●
timezone
Time zone used to convert expressions of type timestamp or timestampl. Valid values are
defined in database table TTZZ, column TZONE
●
country
Country used to set format options number, date, time, and timestamp in one step.
Note:
Constants that may be assigned to the formatting parameters are defined in the
class CL_ABAP_FORMAT.
194
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Functions and Expressions
Regular Expressions
Figure 97: Problems Which can be Solved by Regular Expressions
This section explains the concept of regular expressions and provides details of how to use
them for complex string processing.
Parsing and processing character strings is a frequent programming requirement. ABAP has
for a long time provided a range of functions to do this (for example, FIND, REPLACE, SPLIT,
OVERLAY, SEARCH, and so on). In many cases, a combination of various commands is
necessary, mostly with IF queries and the use of loops.
With SAP NetWeaver 7.0, so-called regular expressions were introduced in ABAP to simplify
string processing. They are used to find and, if necessary, replace special character strings
that correspond to a pattern in a character string.
Often, the structure of a character string you are analyzing cannot be described precisely,
because parts of it are variable. For this reason, patterns with special placeholders that
represent certain characters or sequences must be used. Although it was possible in the past
to use patterns in ABAP for searching (when working with the SEARCH statement, * could be
used to represent any number of characters and + to represent any character), the options
were limited and processing more complex character strings was very complicated.
© Copyright. All rights reserved.
195
Unit 3: Statements, Functions, and Expressions for Simple Data
Special Operators used in Regular Expressions
Figure 98: Special Operators used in Regular Expressions
A regular expression is a literal containing all kinds of characters. However, some characters
or character combinations have a special syntactical meaning.
Special Character Combinations to Describe a Single Character
To describe a single character, the following special character combinations can be used:
●
.
Placeholder for single character
●
\<c>
Placeholder for group of characters. Group depends on value of <c>. Example: \u = single
upper case letter, \d = single digit
●
[]
Value set for single character. Example: [ABC] = ’A’, ’B’, or ’C’
●
[^ ]
Negation of a value set for single character. Example: [^ABC] = not ( ’A’, ’B’, or ’C’)
●
[-]
Value range for single characters. Example: [A-D] = any character between ’A’ and ’D’
●
[[:<c>:]]
Description for group of characters. Group depends on value of <c>. Example: [[:upper:]]
= single upper case letter and [[:digit:]] = single digit
196
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Functions and Expressions
Note:
To use one of the special characters ( \, ^, [, ], .) in a regular expression, the
escape character \ has to be put in front of the special character. For example: ’[’
defines the beginning of a value set, ’\[’ defines the character [.
Hint:
The expression [a-h][0-4] defines a character string consisting of a lower case
letter between ’a’ and ’h’ followed by any digit between 0 and 4 (for
example ’a3’). In contrast, [a-h0-4] defines a character string consisting of one
lower case letter between ’a’ and ’h’ or one digit between 0 and 4 (for example ’a’
or ’3’).
Additional Special Character Combinations to Describe a Character String Expression
Additional special character combinations to describe a character string by a regular
expression include the following:
●
{n}
Concatenation of n single characters. Example: ’A{5}’ = ’AAAAA’
●
{n,m}
Concatenation of n to m single characters. Example: ’A{2,4}’ = ’AA’, ’AAA’, or ’AAAA’
●
?
One or no single character. Thus ? = {0,1}. Example: ’A?’ = ’A’ or empty string.
●
*
Arbitrary number of characters (including empty string). Thus * = {0,}. Example: ’A*’ =
empty string, ’A’, ’AA’, ’AAA’, ...
●
+
Arbitrary number of characters (excluding empty string). Thus * = {1,}. Example: ’A+’
= ’A’, ’AA’, ’AAA’, ...
●
|
Logical OR. Example: ’AB|CD’ = ’AB’ or ’CD’
●
(?: )
Subgroup definition (without registration). An operator following the character
combination acts on subgroup. Example: ’AB(?:A|a)P’ = ’ABAP’ or ’ABaP’
●
()
Subgroup definition with registration. In addition to simple subgroup definition, the
character patterns matching the subgroups are stored for latter reference. The matching
pattern for subgroup n can be referred to using the character combination \n. In text
replacements, the character combination $n can be used to access the matching pattern.
Example: ’(>|-)ABAP\1’ = ’>ABAP>’ or ″-ABAP-″.
© Copyright. All rights reserved.
197
Unit 3: Statements, Functions, and Expressions for Simple Data
Examples of the use of Regular Expressions
Figure 99: Examples of the Use of Regular Expressions
Regular expressions can be used in the statements FIND and REPLACE.
String Functions that Support the Use of Regular Expressions
String functions that support the use of regular expressions include the following:
●
COUNT ()
●
COUNT_... ()
●
CONTAINS... ()
●
FIND ()
●
FIND_... ()
●
MATCH ()
●
MATCHES ()
●
REPLACE ()
●
SUBSTRING ()
●
SUBSTRING_... ()
One of the principle uses of regular expressions is the search for substrings in character
strings. In general, a user is interested in a specific selection of character strings that match a
regular expression.
In ABAP, the search of regular expressions is realized using the addition REGEX of the
statement FIND, whereby the substrings found are determined without overlapping according
to the leftmost-longest rule:
198
© Copyright. All rights reserved.
Lesson: Processing Character Strings and Byte Strings Using Functions and Expressions
First, the substring is determined that is the furthest to the left in the character string, and
that matches the regular expression (leftmost). If there are several substrings, the longest
sequence is chosen (longest). This procedure is then repeated for the remaining sequence
after the found location.
Special Character Combinations that Support Searching in a Character String
The special character combinations that support searching in a character string are as
follows:
●
^ Anchor for offset before first character of line.
●
$ Anchor for offset after last character in a line.
●
\A Anchor for offset before first character of character string. If character string does not
contain control characters, \A and ^ behave identically.
●
\z Anchor for offset after last character of character string. If character string does not
contain control characters, \z and $ behave identically.
●
\< Begin of word.
●
\> End of word. Example: ’(one)’ matched by ’one’ but also by ’done’ or ’lonely’. In
contrast ’\<(one)\>’ is only matched by ’one’
●
• (?= ) Subsequent condition for previous regular expression. String has to match previous
regular expression. In addition, the substring following matching position has to fulfil
subsequent condition. Example: ’(AB)(?=AP)’ is matched by ’ABAP_BC402’ since ’AB’ is
contained in literal and ’AP’ is contained directly behind ’AB’
●
(?! ) Subsequent condition for previous regular expression. String has to match previous
regular expression. In addition, the substring following matching position must not fulfil
subsequent condition. Example: ’(AB)(?!AP)’ is not matched by ’ABAP_BC402’, the
substring following ’AB’ matches the subsequent condition.
After searching, the replacement of substrings in character strings is the most important
application of regular expressions. When replacing, the found locations of a search (or the
substrings that match a regular expression), are replaced by one or more different character
strings. The replacement is realized using regular expressions with the addition REGEX of the
statement REPLACE.
In contrast to normal text replacements, when you use regular expressions, you can use
operators in the replacement text that refers to the relevant found location.
Character Combinations that can be Used in the Replacement Text
The character combinations that can be used in the replacement text are as follows:
●
$`
Complete text before current found location
●
$'
Complete text after current found location
●
$n
Character string stored in the register of subgroups for the n-th found location
●
$&
© Copyright. All rights reserved.
199
Unit 3: Statements, Functions, and Expressions for Simple Data
Complete text
LESSON SUMMARY
You should now be able to:
200
●
Process strings using functions and expressions
●
Process strings using regular expressions
© Copyright. All rights reserved.
Unit 3
Learning Assessment
1. Which of the following are included in writer positions?
Choose the correct answers.
X
A Declaration expressions
X
B Bit expressions
X
C Certain constructor expressions
X
D Certain table expressions
2. Inline declarations are a way of declaring variables and field symbols at operand positions.
Determine whether this statement is true or false.
X
True
X
False
3. Decimal floating-point numbers have a range larger than type f, while the calculation
accuracy is identical to type p.
Determine whether this statement is true or false.
X
True
X
False
4. In flat structures, offset access is possible even if the fields are not completely charactertype (that is, only the first field(s) are character-type), provided the access does not go
beyond the character-type area.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
201
Unit 3: Learning Assessment
5. Which of the following logical operators are available to compare the content of charactertype data objects?
Choose the correct answers.
X
A CO
X
B CN
X
C CA
X
D NA
X
E CS
X
F NS
X
G CP
X
H NP
6. Which of the following kinds of functions return a character-type result?
Choose the correct answer.
X
A Descriptive
X
B Processing
X
C Predicate
X
D String
7. One of the principle uses of regular expressions is the search for substrings in character
strings.
Determine whether this statement is true or false.
X
True
X
False
8. Which of the following operators are available to compare the content of character-type
data objects?
Choose the correct answers.
202
X
A CO
X
B CN
X
C CA
X
D AC
© Copyright. All rights reserved.
Unit 3: Learning Assessment
9. What type of result is returned by a predicate function?
Choose the correct answer.
X
A A numeric result
X
B A character-type result
X
C TRUE or FALSE
10. In ABAP, the search of regular expressions is realized using the addition REGEX of which
statement?
Choose the correct answer.
X
A FIND
X
B MATCH
X
C REPLACE
X
D CONTAINS
© Copyright. All rights reserved.
203
Unit 3
Learning Assessment - Answers
1. Which of the following are included in writer positions?
Choose the correct answers.
X
A Declaration expressions
X
B Bit expressions
X
C Certain constructor expressions
X
D Certain table expressions
2. Inline declarations are a way of declaring variables and field symbols at operand positions.
Determine whether this statement is true or false.
X
True
X
False
3. Decimal floating-point numbers have a range larger than type f, while the calculation
accuracy is identical to type p.
Determine whether this statement is true or false.
X
True
X
False
4. In flat structures, offset access is possible even if the fields are not completely charactertype (that is, only the first field(s) are character-type), provided the access does not go
beyond the character-type area.
Determine whether this statement is true or false.
204
X
True
X
False
© Copyright. All rights reserved.
Unit 3: Learning Assessment - Answers
5. Which of the following logical operators are available to compare the content of charactertype data objects?
Choose the correct answers.
X
A CO
X
B CN
X
C CA
X
D NA
X
E CS
X
F NS
X
G CP
X
H NP
6. Which of the following kinds of functions return a character-type result?
Choose the correct answer.
X
A Descriptive
X
B Processing
X
C Predicate
X
D String
7. One of the principle uses of regular expressions is the search for substrings in character
strings.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
205
Unit 3: Learning Assessment - Answers
8. Which of the following operators are available to compare the content of character-type
data objects?
Choose the correct answers.
X
A CO
X
B CN
X
C CA
X
D AC
9. What type of result is returned by a predicate function?
Choose the correct answer.
X
A A numeric result
X
B A character-type result
X
C TRUE or FALSE
10. In ABAP, the search of regular expressions is realized using the addition REGEX of which
statement?
Choose the correct answer.
206
X
A FIND
X
B MATCH
X
C REPLACE
X
D CONTAINS
© Copyright. All rights reserved.
UNIT 4
Internal Tables
Lesson 1
Using Standard, Sorted, and Hashed Tables
Exercise 9: Use a Sorted Table with Unique Key
208
223
Lesson 2
Using Special Techniques with Internal Tables
Exercise 10: Use Special Techniques with Internal Tables
231
237
Lesson 3
Using Data References and Field Symbols
Exercise 11: Use Field Symbols and Data References to Access Internal Tables
250
257
Lesson 4
Using Inline Declarations and Table Expressions
Exercise 12: Use Inline Declarations and Table Expressions
265
271
UNIT OBJECTIVES
●
Explain the differences between standard, sorted, and hashed tables
●
Process internal tables
●
Use special techniques with internal tables
●
Use secondary keys for internal tables
●
Use data references and field symbols
●
Use inline declarations and table expressions
© Copyright. All rights reserved.
207
Unit 4
Lesson 1
Using Standard, Sorted, and Hashed Tables
LESSON OVERVIEW
This lesson discusses internal tables and the differences between the three table types:
standard, sorted, and hashed. The lesson also discusses how to differentiate index accesses
from key accesses.
Business Example
You develop applications in which large volumes of data are stored and processed in internal
tables. Sorted tables and hashed tables can vastly improve performance, and you want to
learn how to use these table types.
For this reason, you require the following knowledge:
●
An understanding of how to differentiate between standard, sorted, and hashed tables
●
An understanding of how to differentiate between key access and index access to internal
tables
●
An understanding of how to use the different table types correctly
LESSON OBJECTIVES
After completing this lesson, you will be able to:
208
●
Explain the differences between standard, sorted, and hashed tables
●
Process internal tables
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Internal Table Categories
Figure 100: Comparison of Different Internal Table Types
When you define internal tables, you can select one of three table types: standard, sorted, or
hashed. The table type determines how an application can store and access data in the table.
Storage and access are simplest for standard tables. In terms of functionality, there is little
difference between the standard table type and other table types, except for the option of
using unique keys. In fact, some access types that use indexes are not possible with sorted
and hashed tables.
The main reason for using sorted and hashed tables is not to gain additional features but to
improve efficiency when accessing large internal tables. An exception to this is the selection
of a unique key for sorted tables. This subject is discussed further in the lesson.
© Copyright. All rights reserved.
209
Unit 4: Internal Tables
Access Time for Internal Tables
Figure 101: Access Time for Internal Tables of Different Sizes
The figure Access Time for Internal Tables of Different Sizes illustrates how access time
changes with the size of the table for the various table types. While access times are similar
when tables are small, the more lines that a table contains, the larger the differences become.
A notable exception is that the access times for key access to hashed tables is not dependent
on table size.
210
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Standard Tables
Figure 102: Sequential Search for Key Access to a Standard Table
Standard tables are managed internally using a table index (line numbers). You can append
new lines at the end of the table or insert them at specific positions. The lines within the
internal table can be in any sequence and, consequently, the system has to search the entire
table sequentially during a key access. While this can be done relatively quickly for small
tables, the search effort increases linearly with the number of lines.
Note:
If the internal table is explicitly sorted by using the SORT statement, the BINARY
SEARCH addition can significantly speed up access. This will be discussed later in
the lesson.
© Copyright. All rights reserved.
211
Unit 4: Internal Tables
Sorted Tables
Figure 103: Binary Search for Key Access to Standard Table
Like standard tables, sorted tables are managed using a table index. The entries are always
sorted in ascending order by the table key. As a result, the system automatically performs a
binary search during table key accesses.
Based on the total number of lines, the runtime environment determines an index in the
middle and reads a line by index access there. By comparing the key field values of this line
with the search criteria, the system determines whether the sought entry is before or after the
current line. This step halves the data in a single step and is repeated until the sought entry is
found or the system determines that no entry in the table matches the criteria.
Hint:
If the sorted table has a non-unique key, several lines could match the criteria.
The result of sorting is that all lines with the same key are in a contiguous block,
and the system always returns the first line of the block, that is, the one with the
smallest index.
You must never change the sort sequence of a sorted table, even temporarily. In many cases,
the system automatically ensures that the table contents are sorted correctly, such as when a
sorted table is specified for a database access after INTO TABLE or when a MOVE statement
copies the contents of a table into a sorted table. The runtime environment also ensures the
correct sort sequence for key accesses.
212
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Caution:
When performing index accesses that modify the table, the developer must make
sure that the sort sequence is retained. If the sort sequence is changed, an
ITAB_ILLEGAL_SORT_ORDER runtime error occurs.
Hashed Tables
Figure 104: Access Using Hash Board for Hashed Tables
Hashed tables are managed internally using a hash algorithm. To enable this, a hash board is
created in addition to the actual table and the memory addresses of the table lines are
managed in that table. Whereas the table contents are completely unsorted, a hash function
makes it possible to directly calculate the position of the entry in the hash board from the key
values. Accordingly, the key of a hashed table must always be unique.
The effort required to calculate the position in the hash board and then read the table line is
identical for all lines, regardless of the number of table entries. The entries in the hash board
are not consecutive but are instead spread over a certain memory area. These gaps make it
possible to insert additional lines later. The hash function that is used determines how large
the gaps are. If the system calculates that the entries in the hash board are too close to one
another when inserting a line, it reorganizes the hash board. To do so, the positions are
calculated with a different hash function that distributes the entries over a larger memory
area.
© Copyright. All rights reserved.
213
Unit 4: Internal Tables
Hint:
Loops (LOOP ... ENDLOOP) ignore the hash board and search the table
contents directly. The content is unsorted, but for this purpose, it can be sorted
by using the SORT statement.
Index Access and Key Access
Figure 105: Overview of Basic Operations
When working with the different table types, it is essential to understand the difference
between index access and key access. The system does not allow index access to hashed
tables. You must be careful when using index access statements that modify a sorted table,
because doing so may violate the sort sequence, which causes a runtime error.
While the syntax check ensures that no index accesses are made to hashed tables,
developers of sorted tables must be able to spot index accesses that modify the internal table
and avoid using them incorrectly.
214
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Single Record Read Accesses
Figure 106: Reading Internal Tables by Index and Key Access
Single records from internal tables are read using the READ TABLE statement.
Index accesses are characterized by the INDEX addition, which specifies an explicit index. The
INDEX addition is not allowed for hashed tables. Key accesses can be performed with an
implicit specification of the key (using the FROM addition), and an explicit specification (using
WITH (TABLE) KEY). Keys can be either implicit or explicit as follows:
●
Key is implicit
When you specify the key implicitly, the key field values are taken from the structure after
the FROM addition. FROM and INTO do not need to have the same structure.
●
Key is explicit
When the key is specified explicitly, the full table key can be specified using WITH TABLE
KEY, or any other key can be specified using the WITH KEY addition. If you use the WITH
TABLE KEY addition, the syntax check demands that all of the key fields in the table be
listed and supplied with a value. If a key field is missing, this causes a syntax error. If you
use the WITH KEY addition, you can specify any column identifier. The syntax check does
not compare them with the key fields.
© Copyright. All rights reserved.
215
Unit 4: Internal Tables
Hint:
The addition does not have a direct impact on runtime. When accessing sorted
and hashed tables, the system uses the binary search or hash algorithm
respectively, even if you use the WITH KEY addition. The only prerequisite is that
you must specify all the key fields.
By using the optional TRANSPORTING addition, you can copy selected columns instead of the
entire line into the specified structure defined in the program (after INTO).
Hint:
If you use the special TRANSPORTING NO FIELDS addition, no data is read.
Accordingly, INTO is not needed. The system looks for a line with the specified
index and/or key, setting the SY-SUBRC and SY-TABIX system fields
accordingly. This is an efficient way to check whether the table contains a
specific line.
Single Record Write Access
Figure 107: Write Access Using the Index and Using the Key
There are various ways to modify records in internal tables, depending on whether you need
to add a new entry, change an existing entry, or delete an entry. The differences between
index access and key access are particularly important because index access statements that
modify a sorted table can cause runtime errors.
216
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Hint:
In all single record write accesses by key, the keyword TABLE appears next to the
name of the internal table (that is, INTO TABLE, MODIFY TABLE, and DELETE
TABLE). You cannot use this addition for single record write accesses by index
(that is, INTO lt_conn, MODIFY lt_conn, and DELETE lt_conn). Therefore,
INDEX and TABLE are mutually exclusive.
Important Considerations for Specific Statements
Some important considerations for individual statements are as follows:
●
DELETE by key
The table key is either implicit (FROM) or explicit (WITH TABLE KEY). WITH KEY is not
supported. Depending on the table type, the system searches for the line to be deleted
sequentially, using a binary search, or hash algorithm.
●
MODIFY by key
Only an implicit key can be used. Depending on the table type, the system determines
which line is to be changed sequentially, using a binary search, or a hash algorithm.
Only non-key fields are changed. The explicit specification of key fields after
TRANSPORTING causes a syntax error with sorted and hashed tables.
●
INSERT by key
Only an implicit key can be used. For hashed tables, a line is appended to the table
contents, an entry is added to the hash board, and the table is reorganized if necessary.
For sorted tables, a binary search determines the insert position. For standard tables, it
simply adds a line to the end.
●
APPEND and INSERT by index
This statement is allowed for sorted tables, but only use it if you are sure that the insert
position is correct and the sort sequence is retained. If in doubt, insert by key access.
●
MODIFY by index
This statement also allows changes to key fields. This is risky for sorted tables because it
potentially impacts the sort sequence.
Using the optional TRANSPORTING addition with MODIFY works in a way similar to using
READ TABLE to copy only selected components to the desired line in the internal table.
© Copyright. All rights reserved.
217
Unit 4: Internal Tables
Abbreviated Syntax for Index Access in Loops
Figure 108: Abbreviated Syntax for Index Access in Loops
When you perform single-record write accesses by index, you can omit the explicit index
specification in a loop. In this case, the system implicitly uses the current value from SYTABIX. These syntax variants are only relevant within the loops of the corresponding internal
table and can only be used there.
Caution:
The constraint that these statements can only be used within loops is not verified
by the syntax check. If you use them outside of loops, it causes a fatal exception
(TABLE_ILLEGAL_STATEMENT).
218
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Use of the WHERE Condition
Figure 109: Mass Access with WHERE Condition
You should be familiar with restrictions using WHERE from processing internal tables in
LOOPs. You can also specify WHERE conditions in special variants of MODIFY and DELETE.
Hint:
Although key accesses are involved here, you should specify the internal table
without the TABLE addition in these statements.
If you combine MODIFY and WHERE, you must use the TRANSPORTING addition.
© Copyright. All rights reserved.
219
Unit 4: Internal Tables
Accessing Standard Tables with WHERE
Figure 110: Accessing Standard Tables with WHERE
With the use of WHERE, the runtime required to locate the line depends primarily on the table
type. In standard tables, the entire table contents must be searched sequentially to find the
required lines. The runtime requirement increases linearly with the number of lines and can
become large.
In hashed tables, the system ignores the hash board and searches the table contents
completely.
Hint:
The performance of hashed tables is not better than the performance of
standard tables in mass accesses using WHERE.
220
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
Accessing Sorted Tables with WHERE
Figure 111: Accessing Sorted Tables with WHERE
In sorted tables, the system optimizes access automatically if the WHERE condition restricts
the first n key fields to one value, when a left-aligned, gap-free part of the key is specified. In
this case, the desired entries are not scattered throughout the table, but instead are in a
contiguous block. In this case, the system uses a binary search to determine the start of the
block and then begins sequential processing from there. As soon as an entry that does not
match the key fields is reached, the system completes the block and immediately ends
processing.
Hint:
Mass access to sorted tables has better performance compared to other table
types, as long as the WHERE condition limits the first n key fields to one value.
© Copyright. All rights reserved.
221
Unit 4: Internal Tables
Sorted Table with Unique Key
Figure 112: Insert by Key Access into Sorted Table with Unique Key
Sorted tables with a unique key represent a special application case of this table type. In this
case, when you insert a new line, the system immediately determines whether the table
already contains a row with an identical key.
The system only inserts a new line if no line with an identical key is found. In this case, SYSUBRC is set to 0. If the insert is not possible, system field SY-SUBRC is set to 4.
Hint:
Ensuring unique keys does not impact performance. When a new line is inserted
into a sorted table, the right insert point needs to be found for non-unique keys
as well.
222
© Copyright. All rights reserved.
Unit 4
Exercise 9
Use a Sorted Table with Unique Key
Business Example
Enhance your program from the earlier exercise such that the records are held in an internal
table in sorted form, with only unique records. You want to move the duplicate records to a
separate internal table.
Template
BC402_IDS_SPLIT_ITAB
Solution
BC402_IDS_TABKIND
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Use Function Module BC402_IDS_SPLIT_ITAB to Generate a String
Copy program BC402_IDS_SPLIT_ITAB (or your own program ZBC402_##_SPLIT_ITAB)
and name it ZBC402_##_TABKIND. Make sure the string contains non-unique records.
1. Copy the program and all its subcomponents.
2. Use function module BC402_CREATE_SEP_STRING to generate a string with non-unique
records. Set parameter IM_UNIQUE to constant SPACE.
3. Activate and test the program.
Output Records in a List
Buffer the records completely in an internal table and then use a loop to output the contents
of the internal table in the list.
1. Define an internal table that can hold flight data sorted by airline, flight number, and flight
date (suggested name: GT_FLIGHTS).
2. Insert the converted records (the contents of structure GS_FLIGHT) into this internal
table.
3. Use a loop to output the contents of the internal table in a list.
4. Test the program and check whether the result contains identical records.
Allow Only Unique Records in an Internal Table
Create a second internal table of the same type. Fill the tables such that the first table only
contains unique records, while all additional records are inserted in the second table.
© Copyright. All rights reserved.
223
Unit 4: Internal Tables
1. Change the definition of the first table so that only records with unique table keys can be
added.
2. Define another internal table to hold the duplicate records (suggested name:
GT_DOUBLES).
3. Why should you not define this second table with a unique key?
4. Insert each record in one of the two tables. Check the SY-SUBRC return code after the
INSERT statements to find out whether a record with the same key already exists in the
first table.
5. Output the contents of the second internal table at the end of the program.
6. Test the program and check whether the result contains identical records.
224
© Copyright. All rights reserved.
Unit 4
Solution 9
Use a Sorted Table with Unique Key
Business Example
Enhance your program from the earlier exercise such that the records are held in an internal
table in sorted form, with only unique records. You want to move the duplicate records to a
separate internal table.
Template
BC402_IDS_SPLIT_ITAB
Solution
BC402_IDS_TABKIND
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Use Function Module BC402_IDS_SPLIT_ITAB to Generate a String
Copy program BC402_IDS_SPLIT_ITAB (or your own program ZBC402_##_SPLIT_ITAB)
and name it ZBC402_##_TABKIND. Make sure the string contains non-unique records.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_SPLIT_ITAB.
c) Choose Display.
d) Right-click ZBC402_##_SPLIT_ITABand choose Copy....
e) In the Copy Program ZBC402_##_SPLIT_ITABdialog box, in the Target program field,
enter ZBC402_##_TABKIND and choose Copy.
f) In the Copy Program ZBC402_##_SPLIT_ITAB to ZBC402_##_TABKINDdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Use function module BC402_CREATE_SEP_STRING to generate a string with non-unique
records. Set parameter IM_UNIQUE to constant SPACE.
a) See the source code excerpt from the model solution.
3. Activate and test the program.
© Copyright. All rights reserved.
225
Unit 4: Internal Tables
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Output Records in a List
Buffer the records completely in an internal table and then use a loop to output the contents
of the internal table in the list.
1. Define an internal table that can hold flight data sorted by airline, flight number, and flight
date (suggested name: GT_FLIGHTS).
a) See the source code excerpt from the model solution.
2. Insert the converted records (the contents of structure GS_FLIGHT) into this internal
table.
a) See source code excerpt from the model solution.
3. Use a loop to output the contents of the internal table in a list.
a) See source code excerpt from the model solution.
4. Test the program and check whether the result contains identical records.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Allow Only Unique Records in an Internal Table
Create a second internal table of the same type. Fill the tables such that the first table only
contains unique records, while all additional records are inserted in the second table.
1. Change the definition of the first table so that only records with unique table keys can be
added.
a) See the source code excerpt from the model solution.
2. Define another internal table to hold the duplicate records (suggested name:
GT_DOUBLES).
a) See the source code excerpt from the model solution.
3. Why should you not define this second table with a unique key?
Some records appear in the string more than twice and you do not want to lose them.
4. Insert each record in one of the two tables. Check the SY-SUBRC return code after the
INSERT statements to find out whether a record with the same key already exists in the
first table.
a) See the source code excerpt from the model solution.
5. Output the contents of the second internal table at the end of the program.
a) See the source code excerpt from the model solution.
6. Test the program and check whether the result contains identical records.
a) Choose the Check button.
226
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_ids_tabkind MESSAGE-ID bc402.
TYPES:
BEGIN OF ty_s_flight_c,
mandt
TYPE c LENGTH
carrid
TYPE c LENGTH
connid
TYPE n LENGTH
fldate
TYPE n LENGTH
price
TYPE c LENGTH
currency
TYPE c LENGTH
planetype TYPE c LENGTH
seatsmax
TYPE n LENGTH
seatsocc
TYPE n LENGTH
paymentsum TYPE c LENGTH
seatsmax_b TYPE n LENGTH
seatsocc_b TYPE n LENGTH
seatsmax_f TYPE n LENGTH
seatsocc_f TYPE n LENGTH
END OF ty_s_flight_c,
3,
3,
4,
8,
20,
5,
10,
10,
10,
22,
10,
10,
10,
10,
BEGIN OF ty_s_flight,
carrid
TYPE sflight-carrid,
connid
TYPE sflight-connid,
fldate
TYPE sflight-fldate,
price
TYPE sflight-price,
currency
TYPE sflight-currency,
planetype TYPE sflight-planetype,
seatsmax
TYPE sflight-seatsmax,
seatsocc
TYPE sflight-seatsocc,
END OF ty_s_flight.
CONSTANTS c_number TYPE i VALUE 30.
DATA:
gv_datastring
gv_set_string
gs_flight_c
gs_flight
DATA:
gt_sets
TYPE
TYPE
TYPE
TYPE
string,
string,
ty_s_flight_c,
ty_s_flight.
TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY.
DATA:
gt_flights TYPE SORTED TABLE OF ty_s_flight
WITH UNIQUE KEY carrid connid fldate,
gt_doubles TYPE SORTED TABLE OF ty_s_flight
WITH NON-UNIQUE KEY carrid connid fldate.
START-OF-SELECTION.
* retrieve character string (duplicate data sets this time)
CALL FUNCTION 'BC402_CREATE_SEP_STRING'
EXPORTING
© Copyright. All rights reserved.
227
Unit 4: Internal Tables
*
*
im_number
= c_number
im_table_name = 'SFLIGHT'
im_separator = '#'
im_unique
= ' '
IMPORTING
ex_string
= gv_datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038.
ENDIF.
* remove leading and trailing separators
gv_set_string = gv_datastring.
SHIFT gv_set_string RIGHT CIRCULAR BY 2 PLACES.
SHIFT gv_set_string LEFT BY 4 PLACES.
* split into fragments, each corresponding to one data set
SPLIT gv_set_string AT '##' INTO TABLE gt_sets.
LOOP AT gt_sets INTO gv_set_string.
* split into (charlike) fragments corresponding to components
SPLIT gv_set_string AT '#' INTO
gs_flight_c-mandt
gs_flight_c-carrid
gs_flight_c-connid
gs_flight_c-fldate
gs_flight_c-price
gs_flight_c-currency
gs_flight_c-planetype
gs_flight_c-seatsmax
gs_flight_c-seatsocc
gs_flight_c-paymentsum
gs_flight_c-seatsmax_b
gs_flight_c-seatsocc_b
gs_flight_c-seatsmax_f
gs_flight_c-seatsocc_f.
* convert fragments into proper data types
MOVE-CORRESPONDING gs_flight_c TO gs_flight.
* store data in tables - one for unique sets, one for doubles
INSERT gs_flight INTO TABLE gt_flights.
IF sy-subrc <> 0.
INSERT gs_flight INTO TABLE gt_doubles.
ENDIF.
ENDLOOP.
* output result
LOOP AT gt_flights INTO gs_flight.
WRITE: /
gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate DD/MM/YYYY,
gs_flight-price CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
228
© Copyright. All rights reserved.
Lesson: Using Standard, Sorted, and Hashed Tables
ENDLOOP.
SKIP.
WRITE: / text-dob COLOR COL_HEADING.
LOOP AT gt_doubles INTO gs_flight.
WRITE: /
gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate DD/MM/YYYY,
gs_flight-price CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
ENDLOOP.
© Copyright. All rights reserved.
229
Unit 4: Internal Tables
LESSON SUMMARY
You should now be able to:
230
●
Explain the differences between standard, sorted, and hashed tables
●
Process internal tables
© Copyright. All rights reserved.
Unit 4
Lesson 2
Using Special Techniques with Internal Tables
LESSON OVERVIEW
This lesson discusses specific techniques for using internal tables, including binary search for
standard tables, removal of duplicate lines, and totaling during insertion.
Business Example
You want to develop applications that can store and process large volumes of data in internal
tables. To ensure efficient data processing, you want to find out about specific techniques for
using internal tables. For this reason, you require the following knowledge:
●
An understanding of how to use the BINARY SEARCH addition correctly
●
An understanding of how to use the DELETE ADJACENT DUPLICATES and COLLECT
statements correctly
●
An understanding of the function of secondary keys for internal tables and how to apply
them correctly
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use special techniques with internal tables
●
Use secondary keys for internal tables
© Copyright. All rights reserved.
231
Unit 4: Internal Tables
Binary Search for Standard Tables
Figure 113: Incorrect Use of the BINARY SEARCH Addition
When sorted tables are accessed using their keys, the system performs a binary search to
reduce the access time for large tables. The BINARY SEARCH addition instructs the system
to use a binary search during key access to standard tables. Using a binary search during key
access is helpful when the internal table is already sorted by the fields you use to restrict
access. However, as shown in the figure Incorrect Use of the BINARY SEARCH Addition, using
a binary search when the table is not sorted leads to incorrect results.
If the system performs a binary search on an unsorted table, the algorithm continues
searching in the first half of the table because it expects flight LH 0400 before LH 0402. In
this case, because the table is not sorted, the sought entry appears in the second half of the
table and is therefore not found.
Caution:
When using the BINARY SEARCH addition for key access to standard tables, the
table must be sorted by the fields used to restrict access. Otherwise, entries may
not be found, even though they are contained in the table.
When calculating performance, you must remember to sort the internal table before
performing the binary search, even though sorting the internal table adds an extra step to the
procedure. This extra preparation time is beneficial only if several key accesses are
performed with binary search.
232
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
Hint:
You cannot optimize a single access with the BINARY SEARCH addition if you
must sort the table specifically for that access.
An explicit binary search also helps you design more efficient LOOP statements over standard
tables. As a prerequisite, you must sort the table by the fields restricted in the WHERE
condition.
Improving Performance using BINARY SEARCH
Figure 114: Improving Performance using BINARY SEARCH
As a result of the sort sequence, the entries that satisfy the WHERE condition are located in a
contiguous block. The READ TABLE ... BINARY SEARCH statement determines the
position of the first item in this block through the contents of system field SY-TABIX .
Because the position is required only initially, the TRANSPORTING NO FIELDS addition can
be used.
Hint:
If several entries satisfy the condition, READ TABLE always returns the first
entry.
During the subsequent LOOP, the determined line is used as the starting point (the FROM
addition). An explicit termination (EXIT statement) ends processing as soon as the execution
reaches a line that does not satisfy the condition; that is, a line that lies outside the block.
© Copyright. All rights reserved.
233
Unit 4: Internal Tables
Note:
The source code shown in the figure implements the same algorithm that the
system automatically uses for sorted tables.
Deletion of Duplicates
Figure 115: DELETE ADJACENT DUPLICATES Statement
The DELETE ADJACENT DUPLICATES statement lets you remove duplicate lines from an
internal table. The system deletes all lines in which the contents of certain fields are identical
to the contents of the immediately preceding lines.
In the example shown in the figure, the internal table contains several instances of multiple
lines with the same value in the CARRID column. The DELETE ADJACENT DUPLICATES
statement retains the first line of each group in the internal table and deletes all the others.
Caution:
The comparison only compares adjacent table lines. The table must therefore be
sorted by the comparison fields if the statement is to find and remove all
duplicates.
The COMPARING Addition
The COMPARING addition lets you control the fields that are compared by the system, using
the following options:
●
234
Without the COMPARING addition
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
The system compares contents of the key fields. This variant is only justified for internal
tables with non-unique keys. With unique keys, there cannot be two lines with the same
contents in the key fields. The table must be sorted by the table key.
●
COMPARING col1 col2 ...
The system compares the contents of columns col1, col2, ... . You can specify any number
of column names, as well as any combination of key fields and non-key fields. For sorted
tables, this variant is usually justified when you specify the first n key fields.
●
COMPARING ALL FIELDS
The system compares all fields. Therefore, it deletes only those lines that are identical to
the preceding lines.
Subtotals During Insert (COLLECT)
Figure 116: COLLECT-Insert or Add to Total
The COLLECT statement is a special technique for filling an internal table. The system
aggregates the table during the insert operation.
If the table does not have a line with the same key yet, the COLLECT statement has the same
effect as inserting by key access. If the table already contains one or more lines with this key,
the system sums the values of all non-key fields in the new line to the corresponding values in
the top line.
© Copyright. All rights reserved.
235
Unit 4: Internal Tables
Hint:
The COLLECT statement is only allowed when all non-key fields are numeric. The
syntax check reports an error when this prerequisite is not met.
The simplest way to ensure that all non-key fields are numeric is to define an
internal table with a standard key (the WITH DEFAULT KEY addition). The
standard key is defined such that all non-numeric fields are key fields and all nonkey fields have a numeric type.
Aggregating an Internal Table with COLLECT
Figure 117: Aggregating an Internal Table with COLLECT
The figure Aggregating an Internal Table with COLLECT illustrates how you can use the
COLLECT statement to aggregate an existing internal table; that is, create subtotals by group.
The COLLECT statement is a key access, which means you can use it for all three table types.
Caution:
We recommend that you only use the COLLECT statement for sorted or hashed
tables. Using the COLLECT statement with standard tables results in poor
performance because the system first sequentially searches the table to be filled
during each execution of COLLECT. Performance slows as the table becomes
larger.
236
© Copyright. All rights reserved.
Unit 4
Exercise 10
Use Special Techniques with Internal Tables
Business Example
You want to enhance a program that outputs customer flight bookings. Based on the list of
bookings, you also want to output the total bookings by currency and an alphabetical list of
the involved travel agencies.
Template
BC402_IDT_ITAB_TECH
Solution
BC402_IDS_ITAB_TECH
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy the Template BC402_IDT_ITAB_TECH
Copy the template BC402_IDT_ITAB_TECH and name it ZBC402_##_ITAB_TECH. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Which input options are available on the selection screen?
3. What data is output in the list? What missing data do you still need?
Implement subroutine GET_TRAVELAGS
Implement subroutine GET_TRAVELAGS to determine the travel agencies that made the
bookings. Make sure that each travel agency appears only once and the travel agencies are
sorted alphabetically by name.
Hint:
Reading from the database or accessing global data objects of the program from
within the subroutine is not needed. All the necessary data is provided in the
USING parameter of the subroutine.
© Copyright. All rights reserved.
237
Unit 4: Internal Tables
1. Analyze the interface of the subroutine, particularly the typing of the interface
parameters. Which table type does CHANGING parameter CT_TRAVELAGS have?
2. Which components does the line type of CT_TRAVELAGS have?
3. Implement a loop through the bookings and fill CT_TRAVELAGS with the data for all travel
agencies.
4. Remove all duplicate entries from CT_TRAVELAGS.
5. Sort CT_TRAVELAGS by the travel agency name.
Implement subroutine GET_SUMS
Implement subroutine GET_SUMS to calculate the booking totals separated by currency.
1. Analyze the interface of the subroutine, particularly the typing of the interface
parameters. Which table type does CHANGING parameter CT_SUMS have?
2. Which components does the line type of CT_SUMS contain?
3. Implement a loop through the bookings and fill CT_SUMS. Use a technique that forms the
totals at the same time as it fills the table with data.
4. Why can this technique be used in this case?
5. Activate and test your program.
238
© Copyright. All rights reserved.
Unit 4
Solution 10
Use Special Techniques with Internal Tables
Business Example
You want to enhance a program that outputs customer flight bookings. Based on the list of
bookings, you also want to output the total bookings by currency and an alphabetical list of
the involved travel agencies.
Template
BC402_IDT_ITAB_TECH
Solution
BC402_IDS_ITAB_TECH
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy the Template BC402_IDT_ITAB_TECH
Copy the template BC402_IDT_ITAB_TECH and name it ZBC402_##_ITAB_TECH. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_IDT_ITAB_TECH.
c) Choose Display.
d) Right-click BC402_IDT_ITAB_TECHand choose Copy....
e) In the Copy Program BC402_IDT_ITAB_TECHdialog box, in the Target program field,
enter ZBC402_##_ITAB_TECH and choose Copy.
f) In the Copy Program BC402_IDT_ITAB_TECH to ZBC402_##_ITAB_TECHdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Which input options are available on the selection screen?
An airline customer number.
© Copyright. All rights reserved.
239
Unit 4: Internal Tables
3. What data is output in the list? What missing data do you still need?
The data output in the list is the customer name, address, and a list of all bookings for the
customer, excluding cancellations. You still need a list of total bookings, separated by
currency, and a list of the travel agencies that made the bookings.
Implement subroutine GET_TRAVELAGS
Implement subroutine GET_TRAVELAGS to determine the travel agencies that made the
bookings. Make sure that each travel agency appears only once and the travel agencies are
sorted alphabetically by name.
Hint:
Reading from the database or accessing global data objects of the program from
within the subroutine is not needed. All the necessary data is provided in the
USING parameter of the subroutine.
1. Analyze the interface of the subroutine, particularly the typing of the interface
parameters. Which table type does CHANGING parameter CT_TRAVELAGS have?
Standard table with non-unique key.
2. Which components does the line type of CT_TRAVELAGS have?
AGENCYNUM: Travel agency number, NAME: Travel agency name, CITY: City.
3. Implement a loop through the bookings and fill CT_TRAVELAGS with the data for all travel
agencies.
a) See the source code excerpt from the model solution.
4. Remove all duplicate entries from CT_TRAVELAGS.
a) See the source code excerpt from the model solution.
5. Sort CT_TRAVELAGS by the travel agency name.
a) See the source code excerpt from the model solution.
Implement subroutine GET_SUMS
Implement subroutine GET_SUMS to calculate the booking totals separated by currency.
1. Analyze the interface of the subroutine, particularly the typing of the interface
parameters. Which table type does CHANGING parameter CT_SUMS have?
Sorted table with unique key.
2. Which components does the line type of CT_SUMS contain?
FORCURAM: Price of booking in foreign currency (dependent on booking location),
FORCURKEY: Payment currency.
3. Implement a loop through the bookings and fill CT_SUMS. Use a technique that forms the
totals at the same time as it fills the table with data.
a) See the source code excerpt from the model solution.
240
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
4. Why can this technique be used in this case?
Because all non-key fields (FORCURAM in this case) in the table are numeric.
5. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_ids_itab_tech.
TYPES: BEGIN OF gty_s_sums,
forcuram TYPE bc402_scus_book-forcuram,
forcurkey TYPE bc402_scus_book-forcurkey,
END OF gty_s_sums.
TYPES: BEGIN OF gty_s_travelags,
agencynum TYPE bc402_scus_book-agencynum,
name
TYPE bc402_scus_book-name,
city
TYPE bc402_scus_book-city,
END OF gty_s_travelags.
TYPES:
gty_t_sums
TYPE SORTED TABLE OF gty_s_sums
WITH UNIQUE KEY forcurkey,
gty_t_bookings
TYPE STANDARD TABLE OF bc402_scus_book
WITH NON-UNIQUE KEY
carrid connid fldate bookid,
gty_t_travelags TYPE STANDARD TABLE OF gty_s_travelags
WITH NON-UNIQUE KEY agencynum.
DATA:
gs_customer
gt_bookings
gt_sums
gt_travelags
TYPE
TYPE
TYPE
TYPE
scustom,
gty_t_bookings,
gty_t_sums,
gty_t_travelags.
PARAMETERS:
pa_cust TYPE sbook-customid DEFAULT '00000001'.
START-OF-SELECTION.
SELECT SINGLE * FROM scustom INTO gs_customer
WHERE id = pa_cust.
SELECT * FROM bc402_scus_book
INTO TABLE gt_bookings
WHERE customid = pa_cust
AND cancelled <> 'X'.
PERFORM get_sums USING
gt_bookings
CHANGING gt_sums.
PERFORM get_travelags USING
© Copyright. All rights reserved.
gt_bookings
241
Unit 4: Internal Tables
CHANGING gt_travelags.
PERFORM output_list USING gs_customer
gt_bookings
gt_sums
gt_travelags.
*&-----------------------------------------------*
*&
Form GET_SUMS
*&-----------------------------------------------*
FORM get_sums USING pt_bookings TYPE gty_t_bookings
CHANGING ct_sums
TYPE gty_t_sums.
DATA:
ls_bookings LIKE LINE OF pt_bookings,
ls_sums
LIKE LINE OF ct_sums.
LOOP AT pt_bookings INTO ls_bookings.
MOVE-CORRESPONDING ls_bookings TO ls_sums.
COLLECT ls_sums INTO ct_sums.
ENDLOOP.
ENDFORM.
" GET_SUMS
*&--------------------------------------------*
*&
Form GET_TRAVELAGS
*&--------------------------------------------*
FORM get_travelags USING pt_bookings TYPE gty_t_bookings
CHANGING ct_travelags TYPE gty_t_travelags.
DATA:
ls_bookings LIKE LINE OF pt_bookings,
ls_travelags LIKE LINE OF ct_travelags.
LOOP AT pt_bookings INTO ls_bookings.
MOVE-CORRESPONDING ls_bookings TO ls_travelags.
APPEND ls_travelags TO ct_travelags.
ENDLOOP.
SORT ct_travelags BY agencynum.
DELETE ADJACENT DUPLICATES FROM ct_travelags
COMPARING agencynum.
SORT ct_travelags BY name.
ENDFORM.
" GET_TRAVELAGS
*&------------------------------------------------*
*&
Form OUTPUT_LIST
*&------------------------------------------------*
FORM output_list USING ps_customer TYPE scustom
pt_bookings TYPE gty_t_bookings
pt_sums
TYPE gty_t_sums
pt_travelags TYPE gty_t_travelags.
DATA:
242
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
ls_bookings LIKE LINE OF pt_bookings,
ls_sums
LIKE LINE OF pt_sums,
ls_travelags LIKE LINE OF pt_travelags.
DATA lv_text TYPE string.
CONCATENATE text-wcm
ps_customer-form
ps_customer-name
INTO lv_text
SEPARATED BY space.
CONDENSE lv_text.
WRITE: / lv_text.
SKIP.
WRITE / text-lob.
ULINE.
SKIP.
LOOP AT pt_bookings INTO ls_bookings.
WRITE: /
ls_bookings-bookid,
ls_bookings-carrid RIGHT-JUSTIFIED,
ls_bookings-connid,
ls_bookings-fldate,
ls_bookings-cityfrom RIGHT-JUSTIFIED,
'->',
ls_bookings-cityto,
ls_bookings-forcuram CURRENCY ls_bookings-forcurkey,
ls_bookings-forcurkey.
ENDLOOP.
SKIP 2.
WRITE: / text-sum.
ULINE.
SKIP.
LOOP AT pt_sums INTO ls_sums.
WRITE: /
ls_sums-forcuram CURRENCY ls_sums-forcurkey,
ls_sums-forcurkey.
ENDLOOP.
SKIP 2.
WRITE / text-tag.
ULINE.
SKIP.
LOOP AT pt_travelags INTO ls_travelags.
WRITE: /
ls_travelags-name,
ls_travelags-city.
ENDLOOP.
ENDFORM.
© Copyright. All rights reserved.
" OUTPUT_LIST
243
Unit 4: Internal Tables
Definition of Secondary Keys
As of SAP NetWeaver 7.0 EhP2, it is possible to define secondary keys for internal tables.
Secondary keys can be hashed or sorted. A sorted secondary key can be unique or nonunique. The maximum number of secondary keys per internal table is 15.
Figure 118: Examples of Internal Tables with Secondary Keys
You can define secondary keys for table types in the TYPES statement or the DATA
statement. For global table types in ABAP Dictionary, a new Secondary Key tab is available.
The figure Examples of Internal Tables with Secondary Keys shows examples of secondary
key definitions.
You must specify a key name for each secondary key. The key name can be random, but must
be unique for this table.
In addition to secondary keys, the syntax for defining the primary key has been enhanced. For
compatibility reasons, all additions are optional.
244
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
Access to Secondary Keys
Figure 119: Using Secondary Keys in Operations
The figure Using Secondary Keys in Operations shows how you can use a secondary key in a
processing statement by specifying the key name with additions USING KEY key_name or
WITH KEY key_name .
Secondary keys can be used in most processing statements, except for the following:
●
APPEND
●
INSERT (either key or index access)
●
READ TABLE ... WITH TABLE KEY ...
●
DELETE TABLE ... WITH TABLE KEY ...
A secondary key is not selected automatically. Unless you specify a secondary key during a
processing statement, the system always uses a primary key or primary table index. If you
have defined a secondary key for a set of components but do not use it within a processing
statement that is coded for the same set of components, the syntax check issues a warning.
Hint:
When you use a sorted secondary key in an index access, the index you specify is
applied according to the sort order in the secondary key. After an access through
a sorted secondary key, the SY-TABIX field contains the position of the line in
the secondary key.
In a key access (single record or with WHERE), the components in the condition
must match the components of the secondary key.
© Copyright. All rights reserved.
245
Unit 4: Internal Tables
Update of Secondary Keys
Figure 120: Lazy Update of Non-Unique Secondary Key
The system does not always update the secondary keys immediately when you change the
content of the internal table. The system treats unique and non-unique secondary keys
differently.
A non-unique secondary key is only created when it is used explicitly for the first time. After a
write access to the internal table, the update of the secondary key is delayed until the next
statement that explicitly uses this secondary key. This type of update is referred to as a lazy
update.
Hint:
As a consequence of the lazy update, the first access through a secondary key
appears to be expensive in the performance analysis tools.
246
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
Update of Unique Secondary Key Is Not Delayed
Figure 121: Update of Unique Secondary Key Is Not Delayed
A unique secondary key forms a boundary condition for the internal table and is therefore
treated differently.
For any write access that adds or removes lines, the secondary key is updated immediately. If
the uniqueness is violated, the system raises an exception that can be caught and handled
(exception class CX_SY_ITAB_DUPLICATE_KEY).
For MODIFY statements that change the key fields of a unique secondary key, the system
updates the secondary key immediately. If the uniqueness of the key is violated, the system
raises an exception that cannot be handled.
The system only delays the update of a unique secondary key for direct changes through field
symbols or data references.
Unlike non-unique keys, the system updates the unique secondary key at the successive
access to the internal table. In this context, it is not necessary that this secondary key is
actually used in this access.
Use of Secondary Keys
The following points are significant when considering the use of secondary keys:
●
Do not neglect the additional costs of creating or updating the secondary key.
●
Only use secondary keys when they are used often.
Hint:
Building a secondary key is more expensive than sorting a standard table.
© Copyright. All rights reserved.
247
Unit 4: Internal Tables
Use non-unique secondary keys because the system always delays the update and performs
the update only when the respective secondary key is actually used. In addition, when an
internal table has a unique secondary key, any write access to the table risks incurring
runtime errors because of a uniqueness violation.
Be careful when using index operations. After an operation that uses a sorted secondary key,
SY-TABIX returns the position of the respective line in this sorted secondary key. To use SYTABIX to address the line in a subsequent index access, specify the same secondary key.
Recommendations for Using Secondary Keys
248
●
Use secondary keys only when deployed often because they are expensive and pay back
only when used frequently.
●
Use non-unique secondary keys as the update is always delayed and as there is no danger
of runtime errors due to duplicate entries. The secondary key is updated only when it is
used.
●
Remember that the sort order in secondary keys differs from the sort order in primary
keys; SY-TABIX returns the line index with the secondary key but not with the primary key.
The secondary key should, therefore, be used in a subsequent index access.
© Copyright. All rights reserved.
Lesson: Using Special Techniques with Internal Tables
LESSON SUMMARY
You should now be able to:
●
Use special techniques with internal tables
●
Use secondary keys for internal tables
© Copyright. All rights reserved.
249
Unit 4
Lesson 3
Using Data References and Field Symbols
LESSON OVERVIEW
This lesson explains what data references and field symbols are, the differences between
them, and how to use them. It also explains how you can use data references and field
symbols to improve performance when accessing internal tables.
Business Example
You want to improve performance when accessing the contents of internal tables by using
data references and field symbols. For this reason, you require the following knowledge:
●
An understanding of the syntax for working with data references and field symbols
●
An understanding of how to use field symbols and data references to access the content of
internal tables
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use data references and field symbols
Data References
Figure 122: Data References
250
© Copyright. All rights reserved.
Lesson: Using Data References and Field Symbols
Data references and object references were introduced alongside field symbols as part of the
enhancements in SAP R/3 4.6A. From this point on, ABAP features full “reference
semantics”.
Data reference variables contain data references or pointers to data objects.
Use the TYPE REF TO addition for the TYPES statement to define a reference type for a data
object. You can specify the data type explicitly or choose the generic variation by using TYPE
REF TO DATA. In this case, your data reference can point to any type of data object.
The corresponding DATA statement defines the data reference variable. Reference variables
are data objects that contain the address of any other data object of the specified type.
Data references use reference semantics; that is, when a data reference variable is accessed,
the data reference is addressed. This means any changes to the data references affect the
addresses.
Data reference variables are handled in ABAP like other data objects with an elementary data
type. This means a reference variable can be defined not only as a single field, but also as the
smallest indivisible unit of complex data objects such as structures or internal tables.
After a reference variable has been defined, it is INITIAL (empty), and thus contains a blank
pointer. For a data reference variable to contain a reference that points to a data object, use
the statement GET REFERENCE OF to obtain a reference to a data object that has already
been defined.
You can also assign an existing data reference from another data reference variable or create
a data object dynamically with the reference.
Use the dereferencing operator ->* to dereference statically-typed data objects directly. This
means that the dereferencing operator directly accesses the content of the data object that
the reference is pointing to. For compatibility reasons, you must dereference generically
typed data references (TYPE REF TO data) and assign them to a field symbol, which you then
use to access the content.
When you type data references statically with a structure type, you can address the
components of the referenced data object directly. Components are addressed by using the
component selector ->.
Checking the Validity of References
Example:
DATA:
gs_flight TYPE
sflight,
gr_flight TYPE REF TO
sflight.
GET REFERENCE OF gs_flight INTO gr_flight.
gr_flight->fldate = gr_flight->fldate + 5.
WRITE: / gr_flight->seatsmax.
In this case, the component selector corresponds to the hyphen for regular component
access to structured data objects.
Validity of References – Logical Expression
... ref IS [NOT] BOUND ...
© Copyright. All rights reserved.
251
Unit 4: Internal Tables
Use the expression ref IS [NOT] BOUND to query whether the reference variable “ref”
contains a valid reference. The reference variable “ref” must be a data reference variable or
an object reference variable.
When a data reference is involved, this logical expression is true if it is dereferenced. When an
object reference is involved, it is true if it points to an object. The logical expression is always
false if “ref” contains a null reference. In contrast, you only use the expression ref IS
[NOT] INITIAL to determine whether “ref” contains the null reference.
Field Symbols
Figure 123: Field Symbols
Before the introduction of data references, field symbols were used in ABAP as dereferenced
pointers. Field symbols provide symbolic access to an existing data object. All accesses you
make to the field symbol are made to the data object assigned to that field symbol. Therefore,
you can only access the content of the data object to which the field symbol points. This
technique is referred to as the value semantics of field symbols.
You declare field symbols using the FIELD-SYMBOLS statement. Note that the angle brackets
(<>) in the field symbol name are part of the syntax. Use the ASSIGN statement to assign a
data object to the field symbol.
By specifying a type for the field symbol, you can ensure that only compatible objects are
assigned to the field symbol.
Example:
DATA: gv_date TYPE d VALUE '20040101',
gv_time TYPE t.
FIELD-SYMBOLS: <fs_date> TYPE d,
<fs_time> TYPE t.
ASSIGN: gv_date TO <fs_date>,
gv_time TO <fs_time>.
* possible?
<fs_time> = <fs_date>.
252
© Copyright. All rights reserved.
Lesson: Using Data References and Field Symbols
Use the expression IS ASSIGNED to find out whether the field symbol is assigned to a field.
The statement UNASSIGN sets the field symbol so that it points to nothing. The logical
expression IS ASSIGNED is then false.
Access to Internal Tables Using Data References and Field Symbols
Figure 124: Using Field Symbols and References for Line Access
Data references and field symbols provide new access options when combined with internal
tables.
You can use the statements described in the figure Using Field Symbols and References for
Line Access to define field symbols and references that are capable of pointing to individual
lines in an internal table. This makes it possible to use these field symbols, or the
dereferencing operator, to access these records.
Hint:
Field symbols and references point to the assigned row even after the internal
table is re-sorted.
Unless there are compelling reasons to the contrary, always type the field symbols and
references using types that are compatible with the internal table. Generic types are also
possible within the dynamic programming framework. However, in such cases, you cannot
use the CASTING addition.
© Copyright. All rights reserved.
253
Unit 4: Internal Tables
Referencing During Read and Loop Processing
Figure 125: Referencing During Read and Loop Processing
When you read a table row using READ TABLE or a series of table rows using LOOP AT, you
can assign the rows of the internal table to a field symbol by using the ASSIGNING
<field_symbol> addition. The <field_symbol> field symbol then points to the line that
you assigned, allowing you to access the field content directly. Consequently, the system
does not copy the entry from the internal table to a work area and back again.
The restrictions for using this technique are as follows:
●
You can only change the contents of key fields when the table is a standard table.
●
You cannot reassign field symbols within the loop. The statements ASSIGN TO
<fs_line> and UNASSIGN <fs_line> cause runtime errors.
●
You cannot use the SUM statement for control level processing.
The same restrictions apply for the variant REFERENCE INTO ref_name, which you can use
to point a reference to the lines.
This technique of using the variant REFERENCE INTO ref_name to point a reference to the
lines is useful for accessing multiple table lines or nested tables within a loop. Copying values
to and from a work area in this kind of operation significantly increases the runtime.
Note:
These access techniques are also useful for dynamic programming.
254
© Copyright. All rights reserved.
Lesson: Using Data References and Field Symbols
References to Inserted or Changed Single Lines
Figure 126: References to Inserted or Changed Single Lines
If you use one of the three statements in the figure References to Inserted or Changed Single
Lines to exchange data with the internal table through a work area, you can also use the
optional additions ASSIGNING <field_symbol> and REFERENCE INTO ref_name to point
a field symbol or reference to the processed line.
© Copyright. All rights reserved.
255
Unit 4: Internal Tables
256
© Copyright. All rights reserved.
Unit 4
Exercise 11
Use Field Symbols and Data References to
Access Internal Tables
Business Example
You are asked to improve a program that outputs a list of bookings. To improve performance,
replace work areas with field symbols and data references when processing internal tables.
Template
BC402_IDS_ITAB_TECH
Solution
BC402_IDS_FSYM_DREF
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy program BC402_IDS_ITAB_TECH (or your own program ZBC402_##_ITAB_TECH) and
name it ZBC402_##_FSYM_DREF. Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test the program.
Edit Subroutine GET_SUMS
Edit the subroutine GET_SUMS. Wherever necessary, use data references instead of explicit
work areas.
1. Examine the source code of the subroutine. For which of the two internal tables can the
work area be replaced completely by a data reference?
2. Define a suitably typed data reference.
3. Modify the LOOP statement such that the data reference is filled during each loop pass
and not the work area.
4. Replace the structure LS_BOOKINGS with the data reference and then comment out the
definition of structure LS_BOOKINGS.
© Copyright. All rights reserved.
257
Unit 4: Internal Tables
Edit Subroutine GET_TRAVELAGS
Now edit subroutine GET_TRAVELAGS. Wherever necessary, use field symbols instead of
explicit work areas.
1. Examine the source code of the subroutine. For which of the two internal tables can the
work area be replaced completely by a field symbol?
2. Define a suitably typed field symbol.
3. Modify the LOOP statement such that the current line is assigned to the field symbol
during each loop pass and not copied to the work area.
4. Replace structure LS_BOOKINGS with the field symbol and then comment out the
definition of structure LS_BOOKINGS.
Edit Subroutine OUTPUT_LIST
Edit subroutine OUTPUT_LIST. Use field symbols or data references instead of explicit work
areas wherever you like.
1. Define suitably-typed field symbols or data references.
2. Modify the LOOP statements.
3. Replace the respective structure with the field symbol or data reference.
4. Activate and test the program.
258
© Copyright. All rights reserved.
Unit 4
Solution 11
Use Field Symbols and Data References to
Access Internal Tables
Business Example
You are asked to improve a program that outputs a list of bookings. To improve performance,
replace work areas with field symbols and data references when processing internal tables.
Template
BC402_IDS_ITAB_TECH
Solution
BC402_IDS_FSYM_DREF
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy program BC402_IDS_ITAB_TECH (or your own program ZBC402_##_ITAB_TECH) and
name it ZBC402_##_FSYM_DREF. Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_ITAB_TECH.
c) Choose Display.
d) Right-click ZBC402_##_ITAB_TECHand choose Copy....
e) In the Copy Program ZBC402_##_ITAB_TECHdialog box, in the Target program field,
enter ZBC402_##_FSYM_DREF and choose Copy.
f) In the Copy Program ZBC402_##__ITAB_TECH to ZBC402_##_FSYM_DREFdialog
box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
© Copyright. All rights reserved.
259
Unit 4: Internal Tables
Edit Subroutine GET_SUMS
Edit the subroutine GET_SUMS. Wherever necessary, use data references instead of explicit
work areas.
1. Examine the source code of the subroutine. For which of the two internal tables can the
work area be replaced completely by a data reference?
Only for internal table PT_BOOKINGS. Because of the write access to CT_SUMS
(COLLECT statement), structure LS_SUMS is not replaced by a data reference.
2. Define a suitably typed data reference.
a) See the source code excerpt from the model solution.
3. Modify the LOOP statement such that the data reference is filled during each loop pass
and not the work area.
a) See the source code excerpt from the model solution.
4. Replace the structure LS_BOOKINGS with the data reference and then comment out the
definition of structure LS_BOOKINGS.
a) See the source code excerpt from the model solution.
Edit Subroutine GET_TRAVELAGS
Now edit subroutine GET_TRAVELAGS. Wherever necessary, use field symbols instead of
explicit work areas.
1. Examine the source code of the subroutine. For which of the two internal tables can the
work area be replaced completely by a field symbol?
Only the work area for internal table PT_BOOKINGS is replaced completely by a field
symbol. Because of the write access to CT_TRAVELAGS (APPEND statement), structure
LS_TRAVELAGS is not replaced by a field symbol.
2. Define a suitably typed field symbol.
a) See the source code excerpt from the model solution.
3. Modify the LOOP statement such that the current line is assigned to the field symbol
during each loop pass and not copied to the work area.
a) See the source code excerpt from the model solution.
4. Replace structure LS_BOOKINGS with the field symbol and then comment out the
definition of structure LS_BOOKINGS.
a) See the source code excerpt from the model solution.
Edit Subroutine OUTPUT_LIST
Edit subroutine OUTPUT_LIST. Use field symbols or data references instead of explicit work
areas wherever you like.
1. Define suitably-typed field symbols or data references.
2. Modify the LOOP statements.
a) See the source code excerpt from the model solution.
3. Replace the respective structure with the field symbol or data reference.
a) See the source code excerpt from the model solution.
260
© Copyright. All rights reserved.
Lesson: Using Data References and Field Symbols
4. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
Subroutine GET_SUMS
*&------------------------------------------------*
*&
Form GET_SUMS
*&------------------------------------------------*
FORM get_sums USING
pt_bookings TYPE gty_t_bookings
CHANGING ct_sums
TYPE gty_t_sums.
*
DATA:
ls_bookings LIKE LINE OF pt_bookings,
lr_bookings TYPE REF TO bc402_scus_book,
ls_sums
LIKE LINE OF ct_sums.
LOOP AT pt_bookings REFERENCE INTO lr_bookings.
MOVE-CORRESPONDING lr_bookings->* TO ls_sums.
COLLECT ls_sums INTO ct_sums.
ENDLOOP.
ENDFORM.
" GET_SUMS
Subroutine GET_TRAVELAGS
*&--------------------------------------------*
*&
Form GET_TRAVELAGS
*&--------------------------------------------*
FORM get_travelags USING
pt_bookings TYPE gty_t_bookings
CHANGING ct_travelags TYPE gty_t_travelags.
*
DATA:
ls_bookings LIKE LINE OF pt_bookings,
ls_travelags LIKE LINE OF ct_travelags.
FIELD-SYMBOLS:
<fs_bookings> LIKE LINE OF pt_bookings.
LOOP AT pt_bookings ASSIGNING <fs_bookings>.
MOVE-CORRESPONDING <fs_bookings> TO ls_travelags.
APPEND ls_travelags TO ct_travelags.
ENDLOOP.
SORT ct_travelags BY agencynum.
DELETE ADJACENT DUPLICATES FROM ct_travelags
COMPARING agencynum.
SORT ct_travelags BY name.
ENDFORM.
" GET_TRAVELAGS
Subroutine OUTPUT_LIST
*&-------------------------------------------------*
© Copyright. All rights reserved.
261
Unit 4: Internal Tables
*&
Form OUTPUT_LIST
*&-------------------------------------------------*
FORM output_list USING ps_customer TYPE scustom
pt_bookings TYPE gty_t_bookings
pt_sums
TYPE gty_t_sums
pt_travelags TYPE gty_t_travelags.
*
*
*
*
DATA:
ls_bookings LIKE LINE OF pt_bookings,
ls_sums
LIKE LINE OF pt_sums,
ls_travelags LIKE LINE OF pt_travelags.
FIELD-SYMBOLS:
<fs_bookings>
<fs_sums>
<fs_travelags>
LIKE LINE OF pt_bookings,
LIKE LINE OF pt_sums,
LIKE LINE OF pt_travelags.
DATA lv_text TYPE string.
CONCATENATE text-wcm
ps_customer-form
ps_customer-name
INTO lv_text
SEPARATED BY space.
CONDENSE lv_text.
WRITE: / lv_text.
SKIP.
WRITE / text-lob.
ULINE.
SKIP.
LOOP AT pt_bookings ASSIGNING <fs_bookings>.
WRITE: /
<fs_bookings>-bookid,
<fs_bookings>-carrid RIGHT-JUSTIFIED,
<fs_bookings>-connid,
<fs_bookings>-fldate,
<fs_bookings>-cityfrom RIGHT-JUSTIFIED,
'->',
<fs_bookings>-cityto,
<fs_bookings>-forcuram CURRENCY <fs_bookings>-forcurkey,
<fs_bookings>-forcurkey.
ENDLOOP.
SKIP 2.
WRITE: / text-sum.
ULINE.
SKIP.
LOOP AT pt_sums ASSIGNING <fs_sums>.
WRITE: /
<fs_sums>-forcuram CURRENCY <fs_sums>-forcurkey,
<fs_sums>-forcurkey.
ENDLOOP.
SKIP 2.
WRITE / text-tag.
ULINE.
SKIP.
262
© Copyright. All rights reserved.
Lesson: Using Data References and Field Symbols
LOOP AT pt_travelags ASSIGNING <fs_travelags>.
WRITE: /
<fs_travelags>-name,
<fs_travelags>-city.
ENDLOOP.
ENDFORM.
© Copyright. All rights reserved.
" OUTPUT_LIST
263
Unit 4: Internal Tables
LESSON SUMMARY
You should now be able to:
●
264
Use data references and field symbols
© Copyright. All rights reserved.
Unit 4
Lesson 4
Using Inline Declarations and Table
Expressions
LESSON OVERVIEW
This lesson details the use of inline declarations for internal tables. It also explains how to
simplify the code by replacing statements with table expressions.
Business Example
You want to use inline declarations for internal tables. To do so, you must familiarize yourself
with the techniques for using inline declarations for internal tables. For this reason, you
require the following knowledge:
●
An understanding of how to use inline declarations for internal tables
●
An understanding of table expressions and chaining
●
An understanding of the built-in functions of internal tables
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use inline declarations and table expressions
Inline Declarations of Internal Tables
Generally, the support for expressions in the ABAP language has improved, particularly as of
SAP NetWeaver 7.40 SPS5.
One group of expressions that can be useful when processing internal tables allows the inline
declaration of data objects, using an expression containing the DATA( ) operator. Because
internal tables often go hand in hand with a work area to allow the individual records to be
processed, these inline declarations can be used for this work area.
The equivalent also works for field symbols using the FIELD-SYMBOL( ) operator.
Another particularly helpful group of expressions are table expressions.
Table expressions allow you to access table rows in a similar way to a READ TABLE
statement, for example by specifying the index of the row you want to access, or by specifying
the value of a column. You can use table expressions directly as part of statements, without
reading into a work area first. You can also directly reference fields of the resulting row and
chain such expressions.
With table expressions and inline declarations, far fewer READ TABLE statements and
individual local variables are necessary to hold intermediate results, making ABAP code more
readable.
© Copyright. All rights reserved.
265
Unit 4: Internal Tables
Inline Declarations when Working with Internal Tables
Figure 127: Inline Declarations when Working with Internal Tables
The figure Inline Declarations when Working with Internal Tables shows examples of the use
of inline declarations of a work area when working with an internal table, and an inline
declaration of a field symbol in a loop.
266
© Copyright. All rights reserved.
Lesson: Using Inline Declarations and Table Expressions
From Statements to Table Expressions
Figure 128: From Statements to Table Expressions
The figure From Statements to Table Expressions shows how relatively long and complicated
ABAP code can be simplified through the use of table expressions.
© Copyright. All rights reserved.
267
Unit 4: Internal Tables
Table Expressions
Figure 129: Table Expressions
A table expression consists of an internal table itab, followed directly by a row (itab_line)
specified in square brackets [ ]. The expression finds the specified row in the internal table
and returns it as the result of the corresponding row type, which can be used as follows:
●
●
Reader positions
-
A table expression can be specified in general expression positions and functional
operand positions with an appropriate operand type. The result is used here as an
operand. The category of the result can be controlled in operand positions using
constructor operators.
-
A table expression can be specified as a special expression variant for the memory area
in the statement ASSIGN.
-
A table expression can be specified as an argument of the table function line_index and
the predicate function line_exists.
Writer positions
-
A table expression can be specified as a writable expression in result positions. Once
found, the row in question can be modified directly here.
The internal table itab must be specified directly using its name, a field symbol, or a
dereferenced data reference.
The structure component selector - can be used to access components of the row in question
and direct chainings [ ... ][ ... ] of multiple table expressions. Table expressions cannot yet,
however, be specified on the left side of the object component selector ->.
If the specified row is not found, a catchable exception of the class
CX_SY_ITAB_LINE_NOT_FOUND is raised in all operand positions, except in the following
cases:
268
© Copyright. All rights reserved.
Lesson: Using Inline Declarations and Table Expressions
●
When a table expression is used in the statement ASSIGN, where sy-subrc is set to the
value 4
●
When used in the predicate function line_exists, where the logical value false is returned
●
When used in the table function line_index, where the value 0 is returned
Note:
In table expressions, empty square brackets [] cannot be specified behind itab. In
other operand positions, these empty brackets distinguish the table body from
header lines.
Each table expression can be viewed as a short form for a variant of the statement READ
TABLE that enables reads to be performed on rows of internal tables in operand positions.
Unlike READ TABLE, a table expression does not modify the value of the system field sy-tabix.
Like the statement READ TABLE, a table expression is a single row read. If multiple rows of an
internal table are to be read, the statement LOOP should be used.
Table Expressions: Chaining
Figure 130: Table Expressions: Chaining
Not only can table expressions now be used, but they can also be chained. The figure Table
Expressions: Chaining shows an example of this.
© Copyright. All rights reserved.
269
Unit 4: Internal Tables
Internal Tables: Built-in Functions
Figure 131: Internal Tables: Built-in Functions
The table function line_index returns the number of the row found for the table expression
specified. The return value has the type i.
The predicate function line_exists checks whether the row of an internal table specified in the
table expression exists and returns the appropriate logical value.
270
© Copyright. All rights reserved.
Unit 4
Exercise 12
Use Inline Declarations and Table Expressions
Business Example
You want to further refine the code in your program which outputs a list of bookings. You have
heard about the possibility of using inline declarations at certain places in ABAP code, and
would like to see if they can be used in your program. You also want to experiment with table
expressions to avoid the need to use lengthy READ TABLE statements.
Template
BC402_IDT_INLINE_TABEXPR
Solution
BC402_IDS_INLINE_TABEXPR
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy the program ZBC402_##_FSYM_DREF and name it ZBC402_##_INLINE_TABEXPR.
Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test your program.
Edit the Subroutine GET_SUMS
Wherever possible, use inline declarations instead of static data declarations.
1. Examine the source code of the subroutine. How many local declarations are there, and
what are they for?
2. Comment out the DATA statement for the data reference, and replace it with an inline
declaration instead.
3. Check if it is possible to use an inline declaration for the structure LS_SUMS.
Edit Subroutine GET_TRAVELAGS
Wherever possible, use inline declarations instead of static declarations.
© Copyright. All rights reserved.
271
Unit 4: Internal Tables
1. Examine the source code of the subroutine. How many local declarations are there, and
what are they for?
2. Comment out the FIELD-SYMBOLS statement for the field symbol, and replace it with an
inline declaration instead.
Edit Subroutine OUTPUT_LIST
Wherever possible, use inline declarations instead of static declarations
1. Examine the source code of the subroutine. How many local declarations are there, and
what are they for?
2. Comment out all three FIELD-SYMBOLS statements, and replace them with an inline
declaration instead.
Define an Additional Selection Screen Parameter
Define an additional selection screen parameter (suggested name PA_CITY of type
BC402_SCUS_BOOK-CITY) where the home city of the chosen customer can be entered.
1. Define the parameter PA_CITY of type BC402_SCUS_BOOK-CITY.
Use the Table Function LINE_EXISTS
Just after the SELECT statement from BC402_SCUS_BOOK, use the table function
LINE_EXISTS to determine whether any of the bookings for the customer depart from the
home city entered on the selection screen. Use an appropriate table expression in this table
function to check for the record in question. If bookings depart from this city, use a table
expression with an inline declaration of a structure to read one of these bookings, and then
output the two lines below in the report. Otherwise, output a suitable text.
At least one flight booking departs from customers home city.
Arrival city for this flight is: XXXXXXXX.
1. Use the table function LINE_EXISTS to check whether any of the bookings are from the
city entered by the user on the selection screen.
2. If bookings do depart from this city, use a table expression with an inline declaration of a
structure to read one of these bookings and output the information in the report,
otherwise output a suitable message.
3. Activate and test the program.
272
© Copyright. All rights reserved.
Unit 4
Solution 12
Use Inline Declarations and Table Expressions
Business Example
You want to further refine the code in your program which outputs a list of bookings. You have
heard about the possibility of using inline declarations at certain places in ABAP code, and
would like to see if they can be used in your program. You also want to experiment with table
expressions to avoid the need to use lengthy READ TABLE statements.
Template
BC402_IDT_INLINE_TABEXPR
Solution
BC402_IDS_INLINE_TABEXPR
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy the program ZBC402_##_FSYM_DREF and name it ZBC402_##_INLINE_TABEXPR.
Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_FSYM_DREF.
c) Choose Display.
d) Right-click ZBC402_##_FSYM_DREFand choose Copy....
e) In the Copy Program ZBC402_##_FSYM_DREFdialog box, in the Target program field,
enter ZBC402_##_INLINE_TABEXPR and choose Copy.
f) In the Copy Program ZBC402_##_FSYM_DREF to ZBC402_##_INLINE_TABEXPR
dialog box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
© Copyright. All rights reserved.
273
Unit 4: Internal Tables
c) Choose the Direct Processingbutton.
Edit the Subroutine GET_SUMS
Wherever possible, use inline declarations instead of static data declarations.
1. Examine the source code of the subroutine. How many local declarations are there, and
what are they for?
There are two declarations – one is a data reference which is used in the LOOP through
the bookings internal table, and the other is a structure, which is used to add entries to the
sums internal table.
2. Comment out the DATA statement for the data reference, and replace it with an inline
declaration instead.
a) See the source code excerpt from the model solution.
3. Check if it is possible to use an inline declaration for the structure LS_SUMS.
a) Comment out the DATA statement for LS_SUMS.
b) Change the MOVE-CORRESPONDING statement to the following:
MOVE-CORRESPONDING lr_bookings->* TO DATA(ls_sums).
c) Choose the Syntax Check button (or, on your keyboard press the Ctrl and F2 keys).
A syntax error The inline declaration DATA(ls_sums) is not possible in this position
appears.
d) Because it is not possible to use an inline declaration for LS_SUMS, change the code
back to how it was at the end of step 2 (see the source code excerpt from the model
solution).
Edit Subroutine GET_TRAVELAGS
Wherever possible, use inline declarations instead of static declarations.
1. Examine the source code of the subroutine. How many local declarations are there, and
what are they for?
There are two declarations – one is a field symbol which is used in the LOOP through the
bookings internal table, and the other is a structure, which is used to add entries to the
travel agencies internal table.
2. Comment out the FIELD-SYMBOLS statement for the field symbol, and replace it with an
inline declaration instead.
a) See the source code excerpt from the model solution.
Edit Subroutine OUTPUT_LIST
Wherever possible, use inline declarations instead of static declarations
1. Examine the source code of the subroutine. How many local declarations are there, and
what are they for?
There are three declarations of field symbols, all used in LOOPs through the three internal
tables.
274
© Copyright. All rights reserved.
Lesson: Using Inline Declarations and Table Expressions
2. Comment out all three FIELD-SYMBOLS statements, and replace them with an inline
declaration instead.
a) See the source code excerpt from the model solution.
Define an Additional Selection Screen Parameter
Define an additional selection screen parameter (suggested name PA_CITY of type
BC402_SCUS_BOOK-CITY) where the home city of the chosen customer can be entered.
1. Define the parameter PA_CITY of type BC402_SCUS_BOOK-CITY.
a) See the source code excerpt from the model solution.
Use the Table Function LINE_EXISTS
Just after the SELECT statement from BC402_SCUS_BOOK, use the table function
LINE_EXISTS to determine whether any of the bookings for the customer depart from the
home city entered on the selection screen. Use an appropriate table expression in this table
function to check for the record in question. If bookings depart from this city, use a table
expression with an inline declaration of a structure to read one of these bookings, and then
output the two lines below in the report. Otherwise, output a suitable text.
At least one flight booking departs from customers home city.
Arrival city for this flight is: XXXXXXXX.
1. Use the table function LINE_EXISTS to check whether any of the bookings are from the
city entered by the user on the selection screen.
a) Just after the SELECT from BC402_SCUS_BOOK, add the following code:
IF line_exists( gt_bookings[ cityfrom = pa_city ] ).
ENDIF.
2. If bookings do depart from this city, use a table expression with an inline declaration of a
structure to read one of these bookings and output the information in the report,
otherwise output a suitable message.
a) Extend the logic as follows:
IF line_exists( gt_bookings[ cityfrom = pa_city ] ).
DATA(gs_booking) = gt_bookings[ cityfrom = pa_city ].
WRITE:/ 'At least one flight booking departs from customers home
city'.
WRITE:/ 'Arrival city for this flight is:', gs_booking-cityto.
ELSE.
WRITE:/ 'None of the customers flights depart from city', pa_city.
ENDIF.
3. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
© Copyright. All rights reserved.
275
Unit 4: Internal Tables
Source code excerpt from the model solution:
*&----------------------------------------------------------------*
*& Report BC402_IDS_ITAB_TECH
*&
*&----------------------------------------------------------------*
*&
*&
*&----------------------------------------------------------------*
REPORT
zbc402_##_inline_tabexpr.
TYPES: BEGIN OF gty_s_sums,
forcuram TYPE bc402_scus_book-forcuram,
forcurkey TYPE bc402_scus_book-forcurkey,
END OF gty_s_sums.
TYPES: BEGIN OF gty_s_travelags,
agencynum TYPE bc402_scus_book-agencynum,
name
TYPE bc402_scus_book-name,
city
TYPE bc402_scus_book-city,
END OF gty_s_travelags.
TYPES:
gty_t_sums
TYPE SORTED TABLE OF gty_s_sums
WITH UNIQUE KEY forcurkey,
gty_t_bookings
TYPE STANDARD TABLE OF bc402_scus_book
WITH NON-UNIQUE KEY
carrid connid fldate bookid,
gty_t_travelags TYPE STANDARD TABLE OF gty_s_travelags
WITH NON-UNIQUE KEY agencynum.
DATA:
gs_customer
gt_bookings
gt_sums
gt_travelags
TYPE
TYPE
TYPE
TYPE
scustom,
gty_t_bookings,
gty_t_sums,
gty_t_travelags.
PARAMETERS:
pa_cust TYPE sbook-customid DEFAULT '00000001',
PA_CITY type BC402_SCUS_BOOK-CITY. " Line to be inserted
START-OF-SELECTION.
SELECT SINGLE * FROM scustom INTO gs_customer
WHERE id = pa_cust.
SELECT * FROM bc402_scus_book
INTO TABLE gt_bookings
WHERE customid = pa_cust
AND cancelled <> 'X'.
*lines to be inserted
IF line_exists( gt_bookings[ cityfrom = pa_city ] ).
DATA(gs_booking) = gt_bookings[ cityfrom = pa_city ].
WRITE:/ 'At least one flight booking departs from customers home
city'.
276
© Copyright. All rights reserved.
Lesson: Using Inline Declarations and Table Expressions
WRITE:/ 'Arrival city for this flight is:', gs_booking-cityto.
ELSE.
WRITE:/ 'None of the customers flights depart from city', pa_city.
ENDIF.
PERFORM get_sums USING gt_bookings
CHANGING gt_sums.
PERFORM get_travelags USING gt_bookings
CHANGING gt_travelags.
PERFORM output_list USING gs_customer
gt_bookings
gt_sums
gt_travelags.
*&----------------------------------------------------------------*
*&
Form GET_SUMS
*&----------------------------------------------------------------*
FORM get_sums USING
pt_bookings TYPE gty_t_bookings
CHANGING ct_sums
TYPE gty_t_sums.
DATA:
* ls_bookings LIKE LINE OF pt_bookings,
*)
ls_sums
LIKE LINE OF ct_sums.
Line to be changed (commented
LOOP AT pt_bookings REFERENCE INTO data(lr_bookings).
MOVE-CORRESPONDING lr_bookings->* TO ls_sums.
COLLECT ls_sums INTO ct_sums.
ENDLOOP.
ENDFORM.
" GET_SUMS
*&----------------------------------------------------------------*
*&
Form GET_TRAVELAGS
*&----------------------------------------------------------------*
FORM get_travelags USING
pt_bookings TYPE gty_t_bookings
CHANGING ct_travelags TYPE gty_t_travelags.
DATA:
* ls_bookings LIKE LINE OF pt_bookings, "Line to be commented
ls_travelags LIKE LINE OF ct_travelags. " Line to be inserted
*
*
FIELD-SYMBOLS:
<fs_bookings> LIKE LINE OF pt_bookings.
LOOP AT pt_bookings ASSIGNING FIELD-SYMBOL(<fs_bookings>).
MOVE-CORRESPONDING <fs_bookings> TO ls_travelags.
APPEND ls_travelags TO ct_travelags.
ENDLOOP.
SORT ct_travelags BY agencynum.
DELETE ADJACENT DUPLICATES FROM ct_travelags
COMPARING agencynum.
© Copyright. All rights reserved.
277
Unit 4: Internal Tables
SORT ct_travelags BY name.
ENDFORM.
" GET_TRAVELAGS
*&----------------------------------------------------------------*
*&
Form OUTPUT_LIST
*&----------------------------------------------------------------*
FORM output_list USING
ps_customer TYPE scustom
pt_bookings TYPE gty_t_bookings
pt_sums
TYPE gty_t_sums
pt_travelags TYPE gty_t_travelags.
*
*
*
*
FIELD-SYMBOLS:
<fs_bookings> LIKE LINE OF pt_bookings,
<fs_sums>
LIKE LINE OF pt_sums,
<fs_travelags> LIKE LINE OF pt_travelags.
DATA lv_text TYPE string.
CONCATENATE text-wcm
ps_customer-form
ps_customer-name
INTO lv_text
SEPARATED BY space.
CONDENSE lv_text.
WRITE: / lv_text.
SKIP.
WRITE / text-lob.
ULINE.
SKIP.
LOOP AT pt_bookings ASSIGNING FIELD-SYMBOL(<fs_bookings>).
WRITE: /
<fs_bookings>-bookid,
<fs_bookings>-carrid RIGHT-JUSTIFIED,
<fs_bookings>-connid ,
<fs_bookings>-fldate,
<fs_bookings>-cityfrom RIGHT-JUSTIFIED,
'->',
<fs_bookings>-cityto,
<fs_bookings>-forcuram CURRENCY <fs_bookings>-forcurkey,
<fs_bookings>-forcurkey.
ENDLOOP.
SKIP 2.
WRITE: / text-sum.
ULINE.
SKIP.
LOOP AT pt_sums ASSIGNING FIELD-SYMBOL(<fs_sums>).
WRITE: /
<fs_sums>-forcuram CURRENCY <fs_sums>-forcurkey,
<fs_sums>-forcurkey.
ENDLOOP.
SKIP 2.
WRITE / text-tag.
ULINE.
SKIP.
278
© Copyright. All rights reserved.
Lesson: Using Inline Declarations and Table Expressions
LOOP AT pt_travelags ASSIGNING FIELD-SYMBOL(<fs_travelags>).
WRITE: /
<fs_travelags>-name,
<fs_travelags>-city.
ENDLOOP.
ENDFORM.
© Copyright. All rights reserved.
" OUTPUT_LIST
279
Unit 4: Internal Tables
LESSON SUMMARY
You should now be able to:
●
280
Use inline declarations and table expressions
© Copyright. All rights reserved.
Unit 4
Learning Assessment
1. The access times for key access to hashed tables are independent of the table size.
Determine whether this statement is true or false.
X
True
X
False
2. When using the BINARY SEARCH addition in a read on a ____________ internal table, it is
important to sort the data first by the fields you use to restrict access.
Choose the correct answer.
X
A Standard
X
B Sorted
X
C Hashed
3. Which of the following types of secondary key can be defined for an internal table?
Choose the correct answers.
X
A Non-unique standard
X
B Unique standard
X
C Non-unique sorted
X
D Non-unique hashed
X
E Unique hashed
4. What is the maximum number of secondary keys in an internal table?
Choose the correct answer.
X
A 5
X
B 10
X
C 15
X
D 25
© Copyright. All rights reserved.
281
Unit 4: Learning Assessment
5. When you use READ TABLE to read a table row or you use ___________ to read a series of
table rows, you can assign the rows of the internal table to a field symbol by using the
ASSIGNING <field_symbol> addition.
Choose the correct answer.
X
A SUM
X
B ASSIGN do TO <fs_line>
X
C LOOP AT
X
D UNASSIGN <fs_line>
X
E REFERENCE INTO ref_name
6. A table expression can be viewed as a short form for a variant of the statement
_____________ that enables access to rows of internal tables in operand positions.
Choose the correct answer.
282
X
A LOOP
X
B DELETE
X
C READ TABLE
© Copyright. All rights reserved.
Unit 4
Learning Assessment - Answers
1. The access times for key access to hashed tables are independent of the table size.
Determine whether this statement is true or false.
X
True
X
False
2. When using the BINARY SEARCH addition in a read on a ____________ internal table, it is
important to sort the data first by the fields you use to restrict access.
Choose the correct answer.
X
A Standard
X
B Sorted
X
C Hashed
3. Which of the following types of secondary key can be defined for an internal table?
Choose the correct answers.
X
A Non-unique standard
X
B Unique standard
X
C Non-unique sorted
X
D Non-unique hashed
X
E Unique hashed
© Copyright. All rights reserved.
283
Unit 4: Learning Assessment - Answers
4. What is the maximum number of secondary keys in an internal table?
Choose the correct answer.
X
A 5
X
B 10
X
C 15
X
D 25
5. When you use READ TABLE to read a table row or you use ___________ to read a series of
table rows, you can assign the rows of the internal table to a field symbol by using the
ASSIGNING <field_symbol> addition.
Choose the correct answer.
X
A SUM
X
B ASSIGN do TO <fs_line>
X
C LOOP AT
X
D UNASSIGN <fs_line>
X
E REFERENCE INTO ref_name
6. A table expression can be viewed as a short form for a variant of the statement
_____________ that enables access to rows of internal tables in operand positions.
Choose the correct answer.
284
X
A LOOP
X
B DELETE
X
C READ TABLE
© Copyright. All rights reserved.
UNIT 5
Dynamic Programming
Lesson 1
Explaining the Dynamic Programming Techniques of ABAP
287
Lesson 2
Using Dynamic Statements and Dynamic Calls
Exercise 13: Implement a Dynamic Method Call
289
299
Lesson 3
Using Generic Data Types
Exercise 14: Use Dynamically Typed Field Symbols in Dynamic SQL Statements
Exercise 15: Access Structure Components Dynamically
307
315
325
Lesson 4
Describing Data Types, Data Objects, and Objects at Runtime
Exercise 16: Provide Column Headers Using RTTI
335
347
Lesson 5
Creating Data Types, Data Objects, and Objects at Runtime
Exercise 17: Create Data Objects at Runtime
Exercise 18: Create Data Types at Runtime with RTTC
359
365
375
UNIT OBJECTIVES
●
Explain the dynamic programming techniques of ABAP
●
Define parts of ABAP statements at runtime
●
Call procedures, methods, and programs dynamically
●
Generate programs at runtime
●
Explain generic data types of ABAP
●
Use generic data types
●
Access data objects dynamically
© Copyright. All rights reserved.
285
Unit 5: Dynamic Programming
286
●
Use generically typed data references
●
Explain Runtime Type Identification (RTTI)
●
Describe data types and data objects at runtime
●
Describe object types and objects at runtime
●
Create objects at runtime
●
Create data objects at runtime
●
Create data types at runtime
© Copyright. All rights reserved.
Unit 5
Lesson 1
Explaining the Dynamic Programming
Techniques of ABAP
LESSON OVERVIEW
This lesson gives an overview of the different dynamic programming techniques supported in
ABAP.
Business Example
You are asked to develop a flexible application. You want to learn the different dynamic
techniques that are available in the ABAP language. For this reason, you require the following
knowledge:
●
An understanding of the various techniques for dynamic programming available in ABAP
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain the dynamic programming techniques of ABAP
Dynamic Programming in ABAP
Figure 132: Overview of Dynamic Programming Techniques in ABAP
© Copyright. All rights reserved.
287
Unit 5: Dynamic Programming
Dynamic programming can involve activities such as specifying the type, length, offset,
number of lines, or the name of a program object at runtime. At the extreme end of the scale,
the program object itself can be generated at runtime.
The following types of dynamic programming are supported by ABAP:
●
Dynamic extension of internal tables and strings
●
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
The following techniques can be used:
●
Dynamic language elements
For example, you can specify a function module name at runtime in the CALL FUNCTION
statement.
●
Generating programs from within programs
You can store ABAP code in an internal table and generate it as a program at runtime.
●
Field symbols
Dynamic ASSIGN, dynamic type specification, ASSIGN COMPONENT.
●
Runtime type services
Dynamic type generation and data object generation at runtime.
LESSON SUMMARY
You should now be able to:
●
288
Explain the dynamic programming techniques of ABAP
© Copyright. All rights reserved.
Unit 5
Lesson 2
Using Dynamic Statements and Dynamic Calls
LESSON OVERVIEW
This lesson explains how to specify components of ABAP statements dynamically at runtime.
This technique can be used to design dynamic database accesses, calls of modularization
units, and program calls. In this lesson, you will also learn how to generate complete
programs at runtime.
Business Example
You are asked to develop a flexible application using dynamic calls of modularization units
and database accesses. You want to learn about techniques that use dynamic syntax
components (tokens), as well as how to apply these techniques in calls and database
accesses. For this reason, you require the following knowledge:
●
An understanding of how to define ABAP syntax components (tokens) dynamically
●
An understanding of how to define parts of SELECT statements at runtime
●
An understanding of how to call function modules dynamically
●
An understanding of how to call transactions and programs dynamically
●
An understanding of how to generate a complete program dynamically
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Define parts of ABAP statements at runtime
●
Call procedures, methods, and programs dynamically
●
Generate programs at runtime
© Copyright. All rights reserved.
289
Unit 5: Dynamic Programming
Dynamic Tokens in ABAP Statements
Figure 133: Tokens – Replacing Literals
In many ABAP statements, parts of the statement are not defined until runtime. The parts of
the statement that will be defined at runtime are replaced with a data object. The system
evaluates the content of the data object at runtime and executes the statement accordingly.
We differentiate between two cases with regard to syntax, depending on whether the
developer uses the data object in place of a literal or an identifier.
When a literal is replaced by a data object, no special additions are required. Logically,
numeric literals are replaced by integer data objects, and text literals are replaced by
character-type objects with type c or string.
Hint:
In some cases, you can replace text literals by internal tables with character-type
line types.
Caution:
Many of the errors that the syntax check detects and resolves using static
specifications result in runtime errors when you use dynamic specification.
Therefore, the developer needs to catch and handle these runtime errors to
ensure that no program terminations occur. For example, if the dynamic length
and offset access shown in the figure Tokens – Replacing Literals exceed the
length of the character string, the catchable runtime error
DATA_OFFSET_LENGTH_TOO_LARGE occurs (exception class
CX_SY_RANGE_OUT_OF_BOUNDS).
290
© Copyright. All rights reserved.
Lesson: Using Dynamic Statements and Dynamic Calls
Tokens – Replacing Identifiers
Figure 134: Tokens – Replacing Identifiers
When you replace identifiers, you have to flag the data objects specifically to make it clear
whether the contents of the data object should be used, or the data object itself. Therefore, to
avoid ambiguity, specify the data object whose content appears in place of an identifier in
parentheses.
Hint:
No spaces are allowed within the parentheses when using data objects that
replace identifiers.
Not all ABAP syntax supports the dynamic specification of certain components of an ABAP
statement. For details, see the documentation for the respective statement.
© Copyright. All rights reserved.
291
Unit 5: Dynamic Programming
Dynamic Open SQL
Figure 135: Dynamic Components of the SELECT Statement
An important application for tokens is the flexible design of database accesses that use Open
SQL. This is particularly relevant for read access with SELECT, but statements for write
accesses also offer this option.
You can replace nearly all components of a SELECT statement with data objects, either as a
character-type elementary data object or as an internal table with a character-type line type.
The figure Dynamic Components of the SELECT Statement shows several examples.
Alongside the FROM addition, the field list, and the WHERE clause, you can also use the ORDER
BY addition option for the sort sequence along with GROUPING and HAVING additions. The
INTO clause is the only one that does not support the use of this dynamic technique.
Hint:
Field symbols and data references are used to dynamically determine the data
object that is filled by the SELECT statement.
Caution:
If the dynamic values do not produce an SQL statement with correct semantics
and syntax, runtime errors occur (exception classes
CX_SY_DYNAMIC_OSQL_SEMANTICS and CX_SY_DYNAMIC_OSQL_SYNTAX).
If you use dynamic SQL statements, be sure to always catch and handle these
errors in order to avoid program terminations.
292
© Copyright. All rights reserved.
Lesson: Using Dynamic Statements and Dynamic Calls
Dynamic Calls
Figure 136: Dynamic Calls – Overview
ABAP enables you to call modularization units and programs dynamically. With this approach,
the developer replaces the name of the modularization unit, the transaction, or the program
with a character-type data object in the call syntax.
When making dynamic calls, the following rules apply:
●
Do not use parentheses for function modules or transaction codes because variables
replace text literals.
●
Use parentheses for subroutines, methods, and executable programs because here you
replace an identifier not a literal.
You can pass parameters in dynamic calls statically or dynamically. Specifying static
parameters is only feasible if you call modularization units or programs with the same
interface.
Note:
Because parameters are always passed dynamically in transaction calls
(specifying a table with the USING addition), no special handling is needed.
© Copyright. All rights reserved.
293
Unit 5: Dynamic Programming
Dynamic Function Module Calls
Figure 137: Dynamic Call of Function Modules
When dynamically calling function modules, the actual parameters are assigned to the formal
parameters dynamically by specifying an appropriately typed internal table after the
PARAMETER-TABLE addition. You cannot combine the PARAMETER-TABLE addition with
IMPORTING, EXPORTING, CHANGING, or TABLES.
The internal table must have table type ABAP_FUNC_PARMBIND_TAB from type group ABAP.
The line type includes the following components:
●
NAME
This is the name of the formal parameter.
Note:
Specify NAME in uppercase.
●
KIND
This is the type of parameter transfer (exporting, importing, changing, or tables). This is an
integer type field. The ABAP type group provides the constants abap_func_exporting,
abap_func_importing, and so on, to fill it. Note that a parameter defined as an export
parameter in the function module must be assigned the constant abap_func_importing,
just like if the function module is not called dynamically.
●
294
VALUE
© Copyright. All rights reserved.
Lesson: Using Dynamic Statements and Dynamic Calls
This is the data reference to the value supplied for the parameter.
This field has the generic type TYPE REF TO DATA, which means that it can point to any
type of data object. It is easy to fill the field with a GET REFERENCE OF act_par INTO
gs_partab-value statement. In this statement, act_par stands for the actual
parameter and gs_partab stands for the work area of the parameter table.
Caution:
Table type ABAP_FUNC_PARMBIND_TAB defines a sorted table. Avoid using the
APPEND statement to fill it. Instead, use key access with INSERT ... INTO
TABLE.
If the function module raises conventional exceptions, these can also be caught dynamically.
To catch the exceptions, specify an internal table with type ABAP_FUNC_EXCPBIND_TAB after
the EXCEPTION-TABLE addition, in which the NAME and VALUE columns define the
assignment between the conventional exception and a value for system field sy-subrc. In
this case, the evaluation of sy-subrc needs to be implemented after the dynamic call of the
function module.
Caution:
If errors occur in the tables or in the dynamic call of the function module itself,
catchable runtime errors occur. The exception classes start with
CX_SY_DYN_CALL_. Be sure to catch and handle these errors.
Hint:
Instead of formulating a separate CATCH block for each exception class, you can
catch and handle the superclass CX_SY_DYN_CALL_ERROR instead.
© Copyright. All rights reserved.
295
Unit 5: Dynamic Programming
Dynamic Method Calls
Figure 138: Dynamic Method Call
In method calls, the dynamic passing of parameters and the handling of conventional
exceptions are similar to the procedure for function modules. There are a number of minor
differences.
The differences are as follows:
●
The internal tables must have table type ABAP_PARMBIND_TAB and ABAP_EXCP_TAB
from type group ABAP.
●
Table type ABAP_PARMBIND_TAB describes a hashed table and not a sorted table.
Therefore, the syntax check prevents index accesses.
●
The KIND field can remain initial in method calls. To fill the field anyway, the corresponding
constants are contained in global class CL_ABAP_OBJECTDESCR, not type group ABAP.
Caution:
Dynamic method calls result in easily identifiable runtime errors if the dynamic
values are incorrect. The exception classes for these runtime errors are also
subclasses of class CX_SY_DYN_CALL_ERROR.
296
© Copyright. All rights reserved.
Lesson: Using Dynamic Statements and Dynamic Calls
Dynamic Program Calls
Figure 139: Dynamic Call of an Executable Program (Report)
When you call executable programs dynamically, you can supply the selection screen with
values by passing an internal table with the WITH SELECTION-TABLE addition. Define this
internal table with the dictionary type RSPARAMS as the line type.
The components of the RSPARAMS structure type are as follows:
●
SEL_NAME
Specify the name of the parameter or selection criterion (SELECT-OPTIONS) on the
selection screen. The name must be in uppercase.
●
KIND
The values P and S determine whether it is a parameter or a selection criterion.
●
SIGN, OPTION, LOW, HIGH
For selection criteria (KIND = ’S’), the SIGN, OPTION, LOW, and HIGH values correspond
with the same columns in a select-options internal table. For parameters (KIND = ’P’), fill
only the LOW field.
© Copyright. All rights reserved.
297
Unit 5: Dynamic Programming
298
© Copyright. All rights reserved.
Unit 5
Exercise 13
Implement a Dynamic Method Call
Business Example
You are asked to develop a program which displays the contents of either database table
SPFLI or database table SCUSTOM. You know two methods which can be used to retrieve the
data, and want to use a dynamic method call to ensure that the appropriate method is called
at runtime, depending on which data is required.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy the Template Program
Copy program BC402_DYT_DYN_CALL and name it ZBC402_##_DYN_CALL. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test the program.
3. Analyze the source code. How is the data read from the database? Into which data objects
is it read? How is the data displayed?
Implement a Dynamic Method Call
Replace the two calls of the write_connections and write_customers methods with a
single call after the ENDCASE statement. Use the option of specifying the method name with a
character-type data object. Use the PARAMETER-TABLE addition to pass parameters.
1. Define a character-type data object for the method name (suggested name is
gv_methname). Fill the data object with the respective method names in the WHEN blocks.
2. Define an internal table whose type allows it to be defined after the PARAMETER-TABLE
addition in the dynamic method call (suggested name is gt_parmbind). Also define a
work area for it (suggested name is gs_parmbind).
3. Fill gv_methname with the respective method names in the WHEN blocks.
Fill gt_parmbind with one line to allow the method parameter to be passed. Fill the name
column with the name of the formal parameter for the respective method and point the
reference in the value column to the internal table you want to pass to the method.
© Copyright. All rights reserved.
299
Unit 5: Dynamic Programming
Hint:
You can leave the kind column initial in the method call.
4. Move one of the two method calls from the WHEN block to after the ENDCASE statement
and delete the other one.
Make the remaining method call dynamic. Replace the static method name with data
object gv_methname and replace the static parameter passing with the PARAMETERTABLE addition.
Catch Dynamic Method Call Runtime Errors
1. Read the keyword documentation to find the exceptions that occur during dynamic
method calls. Implement exception handling with TRY... CATCH ... ENDTRY. For
example, respond with error message 060 from message class BC402.
2. Activate and test the program.
300
© Copyright. All rights reserved.
Unit 5
Solution 13
Implement a Dynamic Method Call
Business Example
You are asked to develop a program which displays the contents of either database table
SPFLI or database table SCUSTOM. You know two methods which can be used to retrieve the
data, and want to use a dynamic method call to ensure that the appropriate method is called
at runtime, depending on which data is required.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy the Template Program
Copy program BC402_DYT_DYN_CALL and name it ZBC402_##_DYN_CALL. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DYT_DYN_CALL.
c) Choose Display.
d) Right-click BC402_DYT_DYN_CALLand choose Copy....
e) In the Copy Program BC402_DYT_DYN_CALLdialog box, in the Target program field,
enter ZBC402_##_DYN_CALL and choose Copy.
f) In the Copy Program BC402_DYT__DYN_CALL to ZBC402_##_DYN_CALLdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
© Copyright. All rights reserved.
301
Unit 5: Dynamic Programming
3. Analyze the source code. How is the data read from the database? Into which data objects
is it read? How is the data displayed?
The data is read from the database in static SELECT statements. In the process, one of
two statically defined internal tables is filled. The output is implemented by calling the
corresponding methods.
Implement a Dynamic Method Call
Replace the two calls of the write_connections and write_customers methods with a
single call after the ENDCASE statement. Use the option of specifying the method name with a
character-type data object. Use the PARAMETER-TABLE addition to pass parameters.
1. Define a character-type data object for the method name (suggested name is
gv_methname). Fill the data object with the respective method names in the WHEN blocks.
a) See the source code excerpt from the model solution.
2. Define an internal table whose type allows it to be defined after the PARAMETER-TABLE
addition in the dynamic method call (suggested name is gt_parmbind). Also define a
work area for it (suggested name is gs_parmbind).
a) See the source code excerpt from the model solution.
3. Fill gv_methname with the respective method names in the WHEN blocks.
Fill gt_parmbind with one line to allow the method parameter to be passed. Fill the name
column with the name of the formal parameter for the respective method and point the
reference in the value column to the internal table you want to pass to the method.
Hint:
You can leave the kind column initial in the method call.
a) See the source code excerpt from the model solution.
4. Move one of the two method calls from the WHEN block to after the ENDCASE statement
and delete the other one.
Make the remaining method call dynamic. Replace the static method name with data
object gv_methname and replace the static parameter passing with the PARAMETERTABLE addition.
a) See the source code excerpt from the model solution.
Catch Dynamic Method Call Runtime Errors
1. Read the keyword documentation to find the exceptions that occur during dynamic
method calls. Implement exception handling with TRY... CATCH ... ENDTRY. For
example, respond with error message 060 from message class BC402.
a) See the source code excerpt from the model solution.
2. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
302
© Copyright. All rights reserved.
Lesson: Using Dynamic Statements and Dynamic Calls
Source code excerpt from the model solution:
REPORT
bc402_dys_dyn_call MESSAGE-ID bc402.
TYPE-POOLS: abap.
DATA: gt_cust
gt_conn
TYPE ty_customers,
TYPE ty_connections.
DATA: gv_methname TYPE string,
gt_parmbind TYPE abap_parmbind_tab,
gs_parmbind TYPE abap_parmbind.
SELECTION-SCREEN COMMENT 1(80) text-sel.
PARAMETERS:
pa_xconn TYPE xfeld RADIOBUTTON GROUP tab DEFAULT 'X',
pa_xcust TYPE xfeld RADIOBUTTON GROUP tab.
PARAMETERS:
pa_nol
TYPE i DEFAULT '100'.
START-OF-SELECTION.
* specific part
*---------------------------------------------*
CASE 'X'.
WHEN pa_xconn.
SELECT * FROM spfli INTO TABLE gt_conn
UP TO pa_nol ROWS.
gv_methname = 'WRITE_CONNECTIONS'.
gs_parmbind-name = 'IT_CONN'.
GET REFERENCE OF gt_conn INTO gs_parmbind-value.
INSERT gs_parmbind INTO TABLE gt_parmbind.
WHEN pa_xcust.
SELECT * FROM scustom INTO TABLE gt_cust
UP TO pa_nol ROWS.
gv_methname = 'WRITE_CUSTOMERS'.
gs_parmbind-name = 'IT_CUST'.
GET REFERENCE OF gt_cust INTO gs_parmbind-value.
INSERT gs_parmbind INTO TABLE gt_parmbind.
ENDCASE.
* dynamic part
*-----------------------------------------------*
TRY.
CALL METHOD cl_bc402_utilities=>(gv_methname)
PARAMETER-TABLE
gt_parmbind.
CATCH cx_sy_dyn_call_error.
MESSAGE e060.
ENDTRY.
© Copyright. All rights reserved.
303
Unit 5: Dynamic Programming
Persistent Program Generation
Figure 140: Generating Persistent Executable Programs
The INSERT REPORT statement creates a program that is stored permanently in the
Repository. To use this statement, fill an internal table with the source code that has a
REPORT statement in the first line. Do not forget the period at the end of each ABAP
statement.
The contents of the internal table are saved as an executable program (program type 1). Once
the program is saved, it can be called with the SUBMIT statement. The VIA SELECTIONSCREEN addition causes the selection screen (if any) to be displayed. The AND RETURN
addition means control passes back to the calling program after the program ends.
For more information about generating executable programs, see the ABAP help and look up
keyword INSERT REPORT.
304
© Copyright. All rights reserved.
Lesson: Using Dynamic Statements and Dynamic Calls
Transient Subroutine Pool Generation
Figure 141: Generating Transient Subroutine Pools
The GENERATE SUBROUTINE POOL statement generates a program with type S – a
subroutine pool. This program exists only at runtime of the generating program and contains
only subroutines. Call these subroutines with an external subroutine call (“external
PERFORM”).
For more information about generating transient subroutine pools, see the ABAP help and
look up keyword GENERATE.
© Copyright. All rights reserved.
305
Unit 5: Dynamic Programming
LESSON SUMMARY
You should now be able to:
306
●
Define parts of ABAP statements at runtime
●
Call procedures, methods, and programs dynamically
●
Generate programs at runtime
© Copyright. All rights reserved.
Unit 5
Lesson 3
Using Generic Data Types
LESSON OVERVIEW
This lesson discusses how to use generic data types in ABAP for dynamic programming. It
also discusses the constraints posed on generic data references by the ABAP syntax and how
these constraints affect generic data use.
Business Example
You need to develop a flexible application. Therefore, you want to find out about the generic
data types in ABAP and learn how to type parameters, field symbols, and data references
generically. For this reason, you require the following knowledge:
●
An understanding of generic types and their uses
●
An understanding of how to use generically typed parameters, field symbols, and data
references
●
An understanding of how to use field symbols to access data objects dynamically
●
An understanding of how to use field symbols to access attributes and structure
components dynamically
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain generic data types of ABAP
●
Use generic data types
●
Access data objects dynamically
●
Use generically typed data references
© Copyright. All rights reserved.
307
Unit 5: Dynamic Programming
ABAP Built-In Generic Data Types
Figure 142: Generic ABAP Data Types
The figure Generic ABAP Data Types illustrates the predefined generic data types supported
by ABAP syntax.
In addition to complete data types, ABAP also features a number of generic data types. In
contrast to complete types, you cannot use generic types to define the properties of data
objects. You only use generic types to type formal parameters and field symbols.
Note:
Currently, the two built-in types, ... TYPE REF TO OBJECT and ... TYPE
REF TO DATA are the only types available for typing reference variables
generically.
Generic ABAP Data Types – Internal Tables
Hint:
Most generic types, such as clike, csequence, numeric, simple, and xsequence,
are available as of SAP Web AS 6.10. Generic type decfloat is available as of SAP
NetWeaver 7.0 EhP 2.
308
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
Figure 143: Generic ABAP Data Types – Internal Tables
Each of the generic types is compatible with the set of ABAP types shown in the previous
figures. When you call a procedure, the system checks whether the type of the actual
parameter is compatible with the type of the formal parameter. When you assign a generically
typed field symbol, the syntax check tests whether the type of the data object is compatible
with the generic type of the field symbol.
Note:
The DATA type behaves in the same way as ANY. The differentiation is purely
theoretical at this point. In the future, however, reference variables with type
TYPE REF TO ANY to point to data objects or instances of classes might be
possible.
The ANY TABLE, INDEX TABLE, and SORTED TABLE are special generic data types that are
only compatible with internal tables.
Freely Defined Generic Table Types
Figure 144: Generic Table Types – User-Defined
© Copyright. All rights reserved.
309
Unit 5: Dynamic Programming
In addition to these built-in generic table types, ABAP also contains generic table types that
developers create as generic types. These generic table types are created either in the ABAP
Dictionary or in the program source code, with the TYPES statement.
The figure Generic Table Types — User-Defined shows an example of locally defined generic
table types.
In these generic table types, you define the line type, but the table type and key definition
remain open.
Note:
To create appropriate generic types in the ABAP Dictionary, check the
corresponding options under the Access and Key tabs.
Generically Typed Parameters
Figure 145: Problems When Parameters Are Too General
When you generically type formal parameters of a procedure, such as a subroutine, function
module, or method, the procedure becomes more flexible. Use the syntax check to ensure
that the procedure handles the different types.
The syntax check ensures that the system passes only actual parameters with compatible
types to generically typed formal parameters. However, when generically typed parameters
are addressed in ABAP statements, you often cannot determine whether the type of the
underlying data object or its current content is logical in the respective operand position until
runtime. If conflicts occur, the system raises runtime errors that cannot be caught in most
cases. The figure Problems When Parameters Are Too General shows an example.
310
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
If you assign an internal table or a structure that is not flat and character-type to the
parameter in the example, the WRITE statement raises an uncatchable exception,
OBJECTS_NOT_CHARCONV.
The syntax check helps avoid such runtime errors, particularly in operand positions that only
allow internal tables, such as SELECT ... INTO TABLE ... and LOOP AT TABLE ....
Only generic table types are accepted in these operand positions. Therefore, ensure that an
internal table comes after the formal parameter.
To avoid syntax errors and runtime errors, select generic types that are specific enough to be
used with all compatible types in the desired operand position.
Type Precisely to Avoid Errors
Figure 146: Avoiding Errors by Typing as Precisely as Possible
If you use the generic type SIMPLE in the example shown in the figure Avoiding Errors by
Typing as Precisely as Possible, the WRITE statement does not cause runtime errors. You can
convert all data types that are compatible with SIMPLE to a character string.
The syntax errors are corrected because parameter it_data now accepts only internal
tables because of its type, ANY TABLE.
Hint:
A runtime error can still occur if the method contains an index access to
it_data, specifically, if the actual parameter is a hashed table. Use the generic
type INDEX TABLE to restrict the formal parameter even further.
© Copyright. All rights reserved.
311
Unit 5: Dynamic Programming
Generically Typed Field Symbols
Figure 147: Example – Generic Field Symbol in Dynamic SELECT
Field symbols are pointers that can be assigned to data objects dynamically. When the field
symbol is used in an ABAP statement, you can dynamically define the specific data object that
the field symbol refers to.
If the field symbol is fully typed, then all potential data objects must have the same type,
which restricts the possible use of the field symbol significantly.
Generic typing enables the field symbol to refer to data objects with different types. As a
result, you can address different data objects in the same operand position of an ABAP
statement.
The figure Example — Generic Field Symbol in Dynamic SELECT shows an example of how to
use a field symbol in a dynamic SELECT statement.
The program needs to access one of two database tables, SCARR or SBOOK, depending on
the content of data object gv_table_name. To achieve this, a dynamic SELECT statement is
used. To ensure that the line type of the internal table matches the field list of the database
table, a generically typed field symbol is used as a target that points to internal table gt_scarr
or gt_sbook, as required.
Hint:
The field symbol cannot have type ANY. If the field symbol assigned to the
internal tables has type ANY, it causes a syntax error when used in the SELECT
statement.
312
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
Note:
This example is not completely dynamic, because the data objects are still defined
statically.
Type Casting With Field Symbols
Figure 148: Type Casting With Field Symbols
If the CASTING addition is used when a data object is assigned to a field symbol that has a
different type, the restrictions of having to use the data objects original type are removed.
If the CASTING TYPE addition is used when assigning a data object to a field symbol that has
a different type, the data object can be accessed using the field symbol as if it has that
explicitly specified type.
In the figure Type Casting for Field Symbols, note that the system field SY-DATUM is an
elementary character-type component of length 8.
© Copyright. All rights reserved.
313
Unit 5: Dynamic Programming
314
© Copyright. All rights reserved.
Unit 5
Exercise 14
Use Dynamically Typed Field Symbols in
Dynamic SQL Statements
Business Example
You need to develop a simple program that displays the contents of any database table.
Define the database table in a SELECT statement dynamically, and use a generically typed
field symbol to specify the target of the SELECT statement dynamically.
Note:
In the next step, replace two static SELECT statements with a dynamic
statement.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy the Template Program
Copy program BC402_DYS_DYN_CALL or your own program ZBC402_##_DYN_CALL and
name it ZBC402_##_DYN_SQL, where ## is your group number. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test the program.
3. Analyze the source code. How is the data read from the database and into which data
objects is it transferred?
Program a Dynamic SQL Statement
Replace the two SELECT statements with a single SELECT statement after the ENDCASE
statement. Specify the table name as a character-type data object. In addition, use a
generically typed field symbol as the target (INTO clause) to which you dynamically assign a
suitable data object.
1. Define a character-type data object for the table name (suggested name is gv_tabname).
Fill the data object with the respective table names in the WHEN blocks.
© Copyright. All rights reserved.
315
Unit 5: Dynamic Programming
2. Create a field symbol (suggested name is <fs_table>) whose type allows either data
object gt_conn or gt_cust to be assigned to it.
3. Why is type ANY not suitable?
4. Assign the field symbol to the respective internal tables in the WHEN blocks, the ones you
want to fill in the generic SELECT statement.
5. Move one of the two SELECT statements from the WHEN block to after the ENDCASE
statement and delete the other one. Make the remaining database access dynamic.
Replace the static table name with data object gv_tabname and replace the target
(internal table) with the field symbol.
Catch Dynamic SQL Statement Runtime Errors
1. Read the keyword documentation to find out about the exceptions that occur when using
dynamic SQL statements. Implement exception handling with TRY... CATCH ...
ENDTRY. Either implement a separate CATCH block for each of the exception classes or use
a single CATCH block for the shared superclass. If an error occurs, respond with error
message 061 from message class BC402.
2. Activate and test the program.
316
© Copyright. All rights reserved.
Unit 5
Solution 14
Use Dynamically Typed Field Symbols in
Dynamic SQL Statements
Business Example
You need to develop a simple program that displays the contents of any database table.
Define the database table in a SELECT statement dynamically, and use a generically typed
field symbol to specify the target of the SELECT statement dynamically.
Note:
In the next step, replace two static SELECT statements with a dynamic
statement.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy the Template Program
Copy program BC402_DYS_DYN_CALL or your own program ZBC402_##_DYN_CALL and
name it ZBC402_##_DYN_SQL, where ## is your group number. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_DYN_CALL.
c) Choose Display.
d) Right-click ZBC402_##_DYN_CALLand choose Copy....
e) In the Copy Program ZBC402_##_DYN_CALLdialog box, in the Target program field,
enter ZBC402_##_DYN_SQL and choose Copy.
f) In the Copy Program ZBC402_##__DYN_CALL to ZBC402_##_DYN_SQLdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test the program.
a) Choose the Check button.
© Copyright. All rights reserved.
317
Unit 5: Dynamic Programming
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
3. Analyze the source code. How is the data read from the database and into which data
objects is it transferred?
The data is read from the database in static SELECT statements. In the process, one of
two statically defined internal tables is filled.
Program a Dynamic SQL Statement
Replace the two SELECT statements with a single SELECT statement after the ENDCASE
statement. Specify the table name as a character-type data object. In addition, use a
generically typed field symbol as the target (INTO clause) to which you dynamically assign a
suitable data object.
1. Define a character-type data object for the table name (suggested name is gv_tabname).
Fill the data object with the respective table names in the WHEN blocks.
a) See the source code excerpt from the model solution.
2. Create a field symbol (suggested name is <fs_table>) whose type allows either data
object gt_conn or gt_cust to be assigned to it.
a) See the source code excerpt from the model solution.
3. Why is type ANY not suitable?
The field symbol should be specified after INTO TABLE in the SELECT statement. The
syntax check only allows generic values here, with at least type ANY TABLE.
4. Assign the field symbol to the respective internal tables in the WHEN blocks, the ones you
want to fill in the generic SELECT statement.
a) See the source code excerpt from the model solution.
5. Move one of the two SELECT statements from the WHEN block to after the ENDCASE
statement and delete the other one. Make the remaining database access dynamic.
Replace the static table name with data object gv_tabname and replace the target
(internal table) with the field symbol.
a) See the source code excerpt from the model solution.
Catch Dynamic SQL Statement Runtime Errors
1. Read the keyword documentation to find out about the exceptions that occur when using
dynamic SQL statements. Implement exception handling with TRY... CATCH ...
ENDTRY. Either implement a separate CATCH block for each of the exception classes or use
a single CATCH block for the shared superclass. If an error occurs, respond with error
message 061 from message class BC402.
a) See the source code excerpt from the model solution.
2. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
318
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_dys_dyn_sql MESSAGE-ID bc402.
TYPE-POOLS: abap.
DATA:
gt_cust
gt_conn
TYPE ty_customers,
TYPE ty_connections.
DATA:
gv_methname TYPE string,
gt_parmbind TYPE abap_parmbind_tab,
gs_parmbind TYPE abap_parmbind.
DATA:
gv_tabname
TYPE string.
FIELD-SYMBOLS:
<fs_table> TYPE ANY TABLE.
SELECTION-SCREEN COMMENT 1(80) text-sel.
PARAMETERS:
pa_xconn TYPE xfeld RADIOBUTTON GROUP tab DEFAULT 'X',
pa_xcust TYPE xfeld RADIOBUTTON GROUP tab .
PARAMETERS:
pa_nol
TYPE i DEFAULT '100'.
START-OF-SELECTION.
* specific part
*------------------------------------------*
CASE 'X'.
WHEN pa_xconn.
gv_tabname = 'SPFLI'.
ASSIGN gt_conn TO <fs_table>.
gv_methname = 'WRITE_CONNECTIONS'.
gs_parmbind-name = 'IT_CONN'.
GET REFERENCE OF gt_conn INTO gs_parmbind-value.
INSERT gs_parmbind INTO TABLE gt_parmbind.
WHEN pa_xcust.
gv_tabname = 'SCUSTOM'.
ASSIGN gt_cust TO <fs_table>.
gv_methname = 'WRITE_CUSTOMERS'.
gs_parmbind-name = 'IT_CUST'.
GET REFERENCE OF gt_cust INTO gs_parmbind-value.
INSERT gs_parmbind INTO TABLE gt_parmbind.
ENDCASE.
© Copyright. All rights reserved.
319
Unit 5: Dynamic Programming
* dynamic part
*---------------------------------------------*
TRY.
SELECT * FROM (gv_tabname) INTO TABLE <fs_table>
UP TO pa_nol ROWS.
CATCH cx_sy_dynamic_osql_error.
MESSAGE e061.
ENDTRY.
TRY.
CALL METHOD cl_bc402_utilities=>(gv_methname)
PARAMETER-TABLE
gt_parmbind.
CATCH cx_sy_dyn_call_error.
MESSAGE e060.
ENDTRY.
320
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
Dynamic Access to Data Objects
Figure 149: Dynamic Access to Data Objects
In most ABAP statements, you cannot replace data objects in operand positions directly with
character-type data objects in parentheses. However, this option is available in the ASSIGN
statement for the data object to which you assign the field symbol.
This approach indirectly makes it possible to call the data object dynamically by its name. You
have to assign a generically typed field symbol to the data object using the syntax in the figure
Dynamic Access to Data Objects. Then use that field symbol in the ABAP statement. There
are easier and less error-prone alternatives to specifically access attributes and structure
components.
© Copyright. All rights reserved.
321
Unit 5: Dynamic Programming
Dynamic Access to Instance Attributes and Class Attributes
Figure 150: Dynamic Access to Object Attributes and Class Attributes
In addition to using the full identifier for dynamic access to attributes of classes and objects,
you can also specify only the attribute name with a character-type data object. The object
reference and component selector are specified statically. You can also dynamically specify
the class name for static attributes, if necessary. This syntax is similar to that used for
dynamic method calls.
Hint:
Because the syntax check supports the static part of the statement, these
variants are less error-prone and are therefore preferred.
322
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
Dynamic Access to Structure Components
Figure 151: Dynamic Access to Structure Components
A special variant of the ASSIGN statement provides access to structure components
dynamically. You specify the structure statically or through a separate field symbol in the
ASSIGN COMPONENT ... OF STRUCTURE ... statement. Address the components either
by name or by position (number) within the structure.
Hint:
Because the syntax check supports the static part of the statement, these
variants are less error-prone and are therefore preferred.
Because the system addresses the components of a structure by their positions in sequence,
you can process any structure completely, component by component.
© Copyright. All rights reserved.
323
Unit 5: Dynamic Programming
Full Processing of Any Non-Nested, Flat Structure
Figure 152: Full Processing of Any Non-Nested Flat Structure
Caution:
In the figure Full Processing of Any Non-Nested Flat Structure, an uncatchable
ASSIGN_TYPE_CONFLICT runtime error occurs if the transferred structure
contains a component that is incompatible with the generic SIMPLE type of the
field symbol. Similarly, a runtime error occurs during the WRITE statement if you
type the field symbol with ANY.
324
© Copyright. All rights reserved.
Unit 5
Exercise 15
Access Structure Components Dynamically
Business Example
You need to develop a simple program that displays the contents of any database table. You
therefore want to find out about the options available in dynamic programming.
To implement a generic method that enables you to output the contents of any table in a list
(provided the line type of the internal table has a flat structure), replace the dynamic call of
two specific methods with a static call of a generic method.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Global Class CL_BC402_DYT_GEN_TYPES
Copy global class CL_BC402_DYT_GEN_TYPES and name it ZCL_BC402_##_GEN_TYPES.
Familiarize yourself with the class definition.
1. Copy the global class.
2. Analyze the class definition. Which methods are defined? What is their purpose?
3. Which parameters do these methods have? How are the parameters typed?
Implement Method write_any_struct
Implement method write_any_struct, and output all components of structure gs_struct
individually with a WRITE statement by programming a loop in which you access all the
components in structure gs_struct consecutively.
1. Create a field symbol (suggested name is <fs_comp>) that has a generic type that allows
assignment of any flat components of the structure.
2. Program a DO loop. Use the sy-index loop counter to access all components of
gs_struct consecutively with the field symbol.
3. Check whether the field symbol assignment was successful. If it was, output the
component with a WRITE statement. Otherwise, exit the loop.
© Copyright. All rights reserved.
325
Unit 5: Dynamic Programming
Implement Method write_any_table
Implement method write_any_table. Display the contents of internal table it_table in a list by
programming a loop. Call your previously implemented method, write_any_struct, for each
line.
1. Create a field symbol (suggested name is <fs_line>) that has a generic type that allows
assignment of a line of generic internal table it_table.
2. Program a LOOP over internal table it_table. Assign the lines in the internal table to field
symbol <fs_line> consecutively.
3. Call method write_any_struct for each line.
Copy the Template Program
Copy program BC402_DYS_DYN_SQL or your own program ZBC402_##_DYN_SQL and name
it ZBC402_##_GEN_TYPES, where ## is your group number. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test the program. Analyze the source code.
Replace a Dynamic Method Call with a Generic Method
Replace the dynamic method call at the end of the program with a call of your new method,
write_any_table. Remove all parts of the source code you no longer need, or comment them
out.
1. Delete the dynamic method call or comment it out. In its place, implement a call of method
write_any_table. Pass the method the generic field symbol that points to the internal table
with the data.
2. Delete the definitions of the data objects that are needed for the dynamic method call or
comment them out.
3. Activate and test the program.
326
© Copyright. All rights reserved.
Unit 5
Solution 15
Access Structure Components Dynamically
Business Example
You need to develop a simple program that displays the contents of any database table. You
therefore want to find out about the options available in dynamic programming.
To implement a generic method that enables you to output the contents of any table in a list
(provided the line type of the internal table has a flat structure), replace the dynamic call of
two specific methods with a static call of a generic method.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Global Class CL_BC402_DYT_GEN_TYPES
Copy global class CL_BC402_DYT_GEN_TYPES and name it ZCL_BC402_##_GEN_TYPES.
Familiarize yourself with the class definition.
1. Copy the global class.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Class/Interface and
specify the name of the class CL_BC402_DYT_GEN_TYPES.
c) Choose Display.
d) Right-click CL_BC402_DYT_GEN_TYPESand choose Copy....
e) In the Copy CL_BC402_DYT_GEN_TYPESdialog box, in the Copy To field, enter
ZCL_BC402_##_GEN_TYPES and choose Copy.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Analyze the class definition. Which methods are defined? What is their purpose?
write_any_struct and write_any_table for list output of any flat structure or any internal
table with flat line type.
© Copyright. All rights reserved.
327
Unit 5: Dynamic Programming
3. Which parameters do these methods have? How are the parameters typed?
The parameter of method WRITE_ANY_STRUCT is called IS_STRUCT and has TYPE ANY,
and the parameter of method WRITE_ANY_TABLE is called IT_TABLE, and has TYPE ANY
TABLE.
Implement Method write_any_struct
Implement method write_any_struct, and output all components of structure gs_struct
individually with a WRITE statement by programming a loop in which you access all the
components in structure gs_struct consecutively.
1. Create a field symbol (suggested name is <fs_comp>) that has a generic type that allows
assignment of any flat components of the structure.
a) In the Class Builder, double-click WRITE_ANY_STRUCTand choose Display<->Change.
b) See the source code excerpt from the model solution.
2. Program a DO loop. Use the sy-index loop counter to access all components of
gs_struct consecutively with the field symbol.
a) See the source code excerpt from the model solution.
3. Check whether the field symbol assignment was successful. If it was, output the
component with a WRITE statement. Otherwise, exit the loop.
a) See the source code excerpt from the model solution.
Implement Method write_any_table
Implement method write_any_table. Display the contents of internal table it_table in a list by
programming a loop. Call your previously implemented method, write_any_struct, for each
line.
1. Create a field symbol (suggested name is <fs_line>) that has a generic type that allows
assignment of a line of generic internal table it_table.
a) Choose the Back button.
b) To write the code, double-click WRITE_ANY_TABLE.
c) See the source code excerpt from the model solution.
2. Program a LOOP over internal table it_table. Assign the lines in the internal table to field
symbol <fs_line> consecutively.
a) See the source code excerpt from the model solution.
3. Call method write_any_struct for each line.
a) See the source code excerpt from the model solution.
Copy the Template Program
Copy program BC402_DYS_DYN_SQL or your own program ZBC402_##_DYN_SQL and name
it ZBC402_##_GEN_TYPES, where ## is your group number. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
a) In SE80, in the unnamed dropdown menu on the left of the screen, choose Program
and specify the name of the program ZBC402_##_DYN_SQL.
328
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
b) Choose Display.
c) Right-click ZBC402_##_DYN_SQLand choose Copy....
d) In the Copy Program ZBC402_##_DYN_SQLdialog box, in the Target program field,
enter ZBC402_##_GEN_TYPES and choose Copy.
e) In the Copy Program ZBC402_##_DYN_SQL to ZBC402_##_GEN_TYPESdialog box,
select all checkboxes and choose Copy.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test the program. Analyze the source code.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Replace a Dynamic Method Call with a Generic Method
Replace the dynamic method call at the end of the program with a call of your new method,
write_any_table. Remove all parts of the source code you no longer need, or comment them
out.
1. Delete the dynamic method call or comment it out. In its place, implement a call of method
write_any_table. Pass the method the generic field symbol that points to the internal table
with the data.
a) See the source code excerpt from the model solution.
2. Delete the definitions of the data objects that are needed for the dynamic method call or
comment them out.
a) See the source code excerpt from the model solution.
3. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
Method write_any_struct (Class CL_BC402_DYS_GEN_TYPE)
method WRITE_ANY_STRUCT.
FIELD-SYMBOLS <fs_comp> TYPE simple.
NEW-LINE.
DO.
ASSIGN COMPONENT sy-index OF STRUCTURE is_struct TO <fs_comp>.
IF sy-subrc = 0.
WRITE <fs_comp>.
ELSE.
EXIT.
ENDIF.
ENDDO.
© Copyright. All rights reserved.
329
Unit 5: Dynamic Programming
endmethod.
Method write_any_table (Class CL_BC402_DYS_GEN_TYPE)
method WRITE_ANY_TABLE.
FIELD-SYMBOLS: <fs_line> TYPE ANY.
LOOP AT it_table ASSIGNING <fs_line>.
write_any_struct( <fs_line> ).
ENDLOOP.
endmethod.
Executable Program BC402_DYS_GEN_TYPES
REPORT
bc402_dys_gen_types MESSAGE-ID bc402.
*TYPE-POOLS: abap.
DATA:
gt_cust
gt_conn
TYPE ty_customers,
TYPE ty_connections.
*DATA:
* gv_methname TYPE string,
* gt_parmbind TYPE abap_parmbind_tab,
* gs_parmbind TYPE abap_parmbind.
DATA:
gv_tabname
TYPE string.
FIELD-SYMBOLS:
<fs_table> TYPE ANY TABLE.
SELECTION-SCREEN COMMENT 1(80) text-sel.
PARAMETERS:
pa_xconn TYPE xfeld RADIOBUTTON GROUP tab DEFAULT 'X',
pa_xcust TYPE xfeld RADIOBUTTON GROUP tab .
PARAMETERS:
pa_nol
TYPE i DEFAULT '100'.
START-OF-SELECTION.
* specific part
*----------------------------------------------------*
CASE 'X'.
WHEN pa_xconn.
gv_tabname = 'SPFLI'.
ASSIGN gt_conn TO <fs_table>.
WHEN pa_xcust.
gv_tabname = 'SCUSTOM'.
ASSIGN gt_cust TO <fs_table>.
ENDCASE.
330
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
* dynamic part
*------------------------------------------------------*
TRY.
SELECT * FROM (gv_tabname) INTO TABLE <fs_table>
UP TO pa_nol ROWS.
CATCH cx_sy_dynamic_osql_error.
MESSAGE e061.
ENDTRY.
*
*
*
*
*
*
*
*
TRY.
CALL METHOD cl_bc402_utilities=>(gv_methname)
PARAMETER-TABLE
gt_parmbind.
CATCH cx_sy_dyn_call_error.
MESSAGE e060.
ENDTRY.
cl_bc402_dys_gen_types=>write_any_table( <fs_table> ).
© Copyright. All rights reserved.
331
Unit 5: Dynamic Programming
Generically Typed Data References
You can type reference variables generically. However, in contrast to field symbols, only the
generic types DATA (for data references) and OBJECT (for object references) are available for
reference variables.
The use of generically typed reference variables is restricted in ABAP. With the exception of
the ASSIGN statement, generically typed reference variables cannot be dereferenced directly
in operand positions. The statement WRITE ref->* causes a syntax error, for example, if the
data reference has type TYPE REF TO DATA.
Due to these restrictions, only use generic data references where generic field symbols do not
work.
Use Cases for Generically Typed Data References
Common Use Cases for References with Type TYPE REF TO DATA
●
In internal tables (for example, the parameter table for dynamic method and function
module calls)
●
During the dynamic generation of data objects using the CREATE DATA statement
Cast Assignment for Data References
Figure 153: Cast Assignment for Data References
To address the content of referenced data objects, one option is to use a fully-typed data
reference. The contents of the generic data reference are copied to the fully-typed data
reference. The complete data reference can then be dereferenced in any operand item.
332
© Copyright. All rights reserved.
Lesson: Using Generic Data Types
However, for this technique to work, the second reference variable needs to have the same
type as the referenced data object.
When you assign values between two reference variables with different types, you perform a
cast assignment. It is similar to cast assignment between object references in object-oriented
programming.
As with object references, an upcast occurs when the target variable has a more general
definition, and a downcast occurs when the target variable has a more specific type than the
source variable. Accordingly, assignment from a generic data reference to a fully typed
reference is a downcast.
While upcasts to type TYPE REF TO DATA always work, the downcast must have the ?= cast
operator to pass the syntax check. The system checks compatibility at runtime in this case.
Caution:
If the type of the new reference variable does not match the exact type of the
referenced data object, a runtime error occurs. Class-based exception
CX_SY_MOVE_CAST_ERROR is the exception that occurs.
Dereferenced Generic Data References
Figure 154: Dereferencing Generically Typed Data References
The only ABAP statement in which you can dereference a generically typed reference variable
is the ASSIGN statement.
The ASSIGN statement assigns a (generic) field symbol to the data object to which the
generic reference variable points. You then address and further process the contents of the
referenced object using this field symbol.
© Copyright. All rights reserved.
333
Unit 5: Dynamic Programming
LESSON SUMMARY
You should now be able to:
334
●
Explain generic data types of ABAP
●
Use generic data types
●
Access data objects dynamically
●
Use generically typed data references
© Copyright. All rights reserved.
Unit 5
Lesson 4
Describing Data Types, Data Objects, and
Objects at Runtime
LESSON OVERVIEW
This lesson discusses Runtime Type Identification (RTTI), a technique that you use to query
information about data types and object types at runtime. This technique is essential when
using the generically typed parameters, field symbols, and references in dynamic programs.
Business Example
You need to develop a flexible application using generically typed parameters, field symbols,
and references. Therefore, you want to learn about the options provided by RTTI for querying
information about the actual type of the underlying object at runtime. For this reason, you
require the following knowledge:
●
An understanding of how to query the properties of data objects and data types at runtime
●
An understanding of how to query the properties of classes and instances at runtime
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain Runtime Type Identification (RTTI)
●
Describe data types and data objects at runtime
●
Describe object types and objects at runtime
© Copyright. All rights reserved.
335
Unit 5: Dynamic Programming
RTTI Class Hierarchy
Figure 155: Class Hierarchy of RTTI Description Classes
As of SAP Web AS 6.10, ABAP developers can use a class-based concept, RTTI, to determine
type properties, such as data types and object types, at runtime.
Hint:
Before RTTI, ABAP contained only the DESCRIBE FIELD and DESCRIBE TABLE
statements. However, these statements are limited to properties of data objects,
and do not determine as many properties as RTTI.
RTTI consists of a hierarchy of ten global classes that developers use.
The description of a type at runtime is realized as an instance of one of these classes. The
properties of the type are saved in the instance attributes and can be queried directly or using
appropriate methods. At runtime, only one description object exists for each type.
All classes inherit properties from a shared superclass, either directly or indirectly, and their
names all follow the pattern CL_ABAP_xxxDESCR, where xxx stands for the category of the
type used to describe the respective class.
Different classes are needed because the attributes and methods of each class relate to a
specific category of types. For example, you use class CL_ABAP_TABLEDESCR to describe
table types. Therefore, the class contains attributes for the table category and the structure
of the table key, among other information. These attributes are specific to class
CL_ABAP_TABLEDESCR. No other RTTI classes contain them.
RTTI Classes – Purpose
Only six of the ten RTTI classes can be instantiated and used to describe specific types.
336
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
Table 11: RTTI Classes that can be Instantiated
The following table lists the RTTI classes that can be instantiated:
RTTI Class
Purpose
CL_ABAP_ELEMDESCR
To describe elementary data types
CL_ABAP_REFDESCR
To describe reference types (= types of reference variables)
CL_ABAP_STRUCTDESCR
To describe structure types
CL_ABAP_TABLEDESCR
To describe table types
CL_ABAP_CLASSDESCR
To describe classes (= object types)
CL_ABAP_INTFDESCR
To describe interfaces
All other RTTI classes are abstract, which means that you cannot instantiate them. They are
used to centrally define the attributes and methods that are used in several of the other
classes. For example, the METHODS attribute, which contains a list of the methods, is not
defined in class CL_ABAP_CLASSDESCR, but instead in class CL_ABAP_OBJECTDESCR,
because it is also needed in the same form in class CL_ABAP_INTFDESCR.
RTTI Class Instantiation
Figure 156: RTTI – Methods and Attributes of the Root Class
It is not possible to instantiate the RTTI description classes directly with the CREATE OBJECT
statement. To retrieve a reference to a description object, call static method
DESCRIBE_BY_xxx of class CL_ABAP_TYPEDESCR. The description objects are generated
and the data is filled and returned using a return parameter with generic type REF TO
CL_ABAP_TYPEDESCR.
© Copyright. All rights reserved.
337
Unit 5: Dynamic Programming
Describe a Type Based on Its Name
Figure 157: Describing a Type Based on Its Name
After the call, you need to cast to a reference variable of a suitable subclass to access specific
attributes and methods for the respective type. If you do not know which RTTI class was
instantiated, evaluate the public KIND instance attribute whose contents match the value of
one of the six constants from class CL_ABAP_TYPEDESCR. Each of these six constants
corresponds to one of the six RTTI classes that the developer can instantiate.
338
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
Casting a Suitable Reference for a Type Description Object
Figure 158: Casting a Suitable Reference for a Type Description Object
Hint:
If you know which description class is instantiated, then the downcast can also
take place directly in the call of the DESCRIBE_BY_xxx functional method, for
example, lo_class ?= cl_abap_typedescr=>describe_by_...
In this case, it is a good idea to catch runtime error CX_SY_MOVE_CAST_ERROR.
Methods for Description Objects
The following methods differ with regard to the information they are given in their calls:
●
DESCRIBE_BY_NAME
This method returns a description object with which the name of the type is known. It can
analyze both data types and object types (classes and interfaces). It is unimportant
whether the type was defined globally in the Dictionary or Class Builder, or locally in the
program.
You must enter the type name in upper case. If the method does not find the type with the
specified name, it raises a classic exception TYPE_NOT_FOUND.
●
DESCRIBE_BY_DATA
© Copyright. All rights reserved.
339
Unit 5: Dynamic Programming
This method returns the description object for the type of a data object. It only returns
descriptions of data types, but it does not matter whether the data object is defined with
an explicit type or a bound type.
If the specified data object is a parameter or field symbol with a generic type, the method
does not return the description of the generic type. Instead, it returns the type of the
currently assigned actual parameter or data object.
●
DESCRIBE_BY_DATA_REF
This method returns the description object for the type of a data object that a data
reference points to. It only returns descriptions of data types. If the data reference is typed
generically (TYPE REF TO DATA), you can use this method to determine the dynamic type
of the referenced data object.
Caution:
If the reference does not have a valid value at call time, the method raises
classic exception REFERENCE_IS_INITIAL.
●
DESCRIBE_BY_OBJECT_REF
This method returns the description object for the type of an instance that an object
reference points to. It only returns descriptions of classes. Use this method to determine
the dynamic type of the referenced instance after an upcast to a superclass or
implemented interface.
Caution:
If the reference does not have a valid value at call time, the method raises
classic exception REFERENCE_IS_INITIAL.
340
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
Describe Types Based on Data Objects and References
Figure 159: Describing Types Based on Data Objects and References
The figure Describing Types Based on Data Objects and References shows an example of how
to use these DESCRIBE_BY_xxx static methods.
In addition to the static methods listed, there is another option available for accessing
description objects. Special methods are available to navigate from one description object to
other description objects. For example, you want to navigate from the description of a table
type to the description of the corresponding line type, or you want to navigate from a
structure type to the description objects for the component types.
© Copyright. All rights reserved.
341
Unit 5: Dynamic Programming
Elementary Data Type Analysis
Figure 160: Analysis of an Elementary Data Type
The example in the figure Analysis of an Elementary Data Type, demonstrates how to use
RTTI to determine the properties of different data types, in this case, an elementary data type.
The data type determines which subclass is used.
An instance of class CL_ABAP_ELEMDESCR describes all the properties of an elementary
data type. The corresponding public attributes contain the technical properties of the
underlying ABAP type, the length, and the number of decimal places. To evaluate the
TYPE_KIND attribute, compare its contents with the corresponding constants from class
CL_ABAP_TYPEDESCR, in the same way as for the KIND attribute.
Note:
The three attributes are described in the root class of RTTI, which means they are
inherited by all description classes. However, in the other classes, these attributes
are less significant.
The semantic properties, that is, the additional information from the ABAP Dictionary, must
be determined explicitly using public methods. The figure shows a call of method
GET_DDIC_FIELD. You can use an optional parameter to determine language-dependent
information, such as field labels, in a language other than the current logon language.
342
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
Caution:
If the current type is not a dictionary type, the method raises a classic exception.
To avoid this, first use method IS_DDIC_TYPE to check whether dictionary
information is available (see the example given in the figure).
Reference Type Analysis
Figure 161: Analysis of the Type of a Reference Variable
When you analyze a reference type (= type of a reference variable), the inherited TYPE_KIND
attribute allows you to differentiate between object references and data references. However,
to determine the details of the static type of the reference variable, use the
GET_REFERENCED_TYPE navigation method. This method returns a reference to another
description object. This description object can be an instance of class
CL_ABAP_STRUCTDESCR if the reference variable was created with a structure type.
However, if the reference variable was created with reference to a class or an interface, then
GET_REFERENCED_TYPE returns instances of the CL_ABAP_CLASSDESCR or
CL_ABAP_INTFDESCR class, respectively.
© Copyright. All rights reserved.
343
Unit 5: Dynamic Programming
Structure Type Analysis
Figure 162: Analysis of a Structure Type
The CL_ABAP_STRUCTDESCR class also has a number of public attributes with basic
information, such as the total length in bytes, the existence of includes, the type of structure
(nested or not), and so on. The COMPONENTS attribute is an internal table that contains the
names of all components and their elementary technical properties. You can use the
GET_DDIC_FIELD_LIST method to determine the semantic information (if any) for the
components. It is similar to the GET_DDIC_FIELD method, but returns an internal table
instead of a structure.
344
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
Navigation from Structure Type to Component Types
Figure 163: Navigation from Structure Type to Component Types
To gain full access to all properties of the component types, navigate to the respective
description objects. The GET_COMPONENT_TYPE navigation method returns the description
object for the type of a specific component, while the GET_COMPONENTS navigation method
returns the description objects for all components.
Hint:
Because component types are also reference types, structure types, or table
types, define the return values with type REF TO CL_ABAP_DATADESCR. A
downcast to a subclass–typed reference variable may be necessary in reference
variables, for example, to type REF TO CL_ABAP_ELEMDESCR.
© Copyright. All rights reserved.
345
Unit 5: Dynamic Programming
Table Type Analysis
Figure 164: Analysis of a Table Type
The public attributes of class CL_ABAP_TABLEDESCR include the table type (for example,
standard, sorted, hashed, index, or any) uniqueness of the key, and a list of names of the key
components. To determine the details for a line type, navigate to a description object for that
line type using the GET_TABLE_LINE_TYPE navigation method.
Hint:
The line type of a table type can have any data type. Accordingly, the return
parameter is typed with REF TO CL_ABAP_DATADESCR, so you might have to
perform a downcast to a suitable type if necessary.
346
© Copyright. All rights reserved.
Unit 5
Exercise 16
Provide Column Headers Using RTTI
Business Example
You need to develop a simple program that displays the contents of any database table. To
develop the program, you need to find out about the options available in dynamic
programming. You have already developed a method to output any internal table with a flat
line type to a list. You need to use the options of RTTI to develop a method that generates
dynamic column headers for the program.
Use RTTI to analyze a structure type and to determine semantic information for that structure
type from the ABAP Dictionary. Use the semantic information for the structure type to
generate column headers dynamically.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Class
Copy template CL_BC402_DYT_RTTI_HEADERS and name it
ZCL_BC402_##_RTTI_HEADERS. Familiarize yourself with the class definition.
1. Copy the global class.
2. Analyze the class definition. Determine which methods are defined and what their
purposes are?
3. Which parameters and exceptions do these methods have? How are the parameters
typed? Which error situations correspond to the exceptions?
Implement Method write_headers
Implement method write_headers. Use RTTI options to analyze the Dictionary table whose
name is passed to the import parameter gv_tabname.
1. Call a suitable static method of class CL_ABAP_TYPEDESCR to analyze the data type
based on its name.
© Copyright. All rights reserved.
347
Unit 5: Dynamic Programming
2. Create a local reference variable (suggested name is lo_type) and type it to match the
return parameter of the method. Specify this reference variable as an actual parameter in
the method call.
3. Handle any possible exceptions and raise exception TYPE_NOT_FOUND from method
write_headers in response.
4. Use the public KIND attribute to determine whether the generated RTTI instance actually
describes a structure type. If the data type is not a structure type, exit method
write_headers with exception NO_STRUCTURE.
5. Create a local reference variable (suggested name is lo_struct) of TYPE REF TO
CL_ABAP_STRUCTDESCR. Program a down cast to point this reference to the type
description object.
Hint:
There is no need to catch possible runtime errors here because the query of
the KIND attribute already ensures compatibility.
Output the Report Header for all Components
Determine a list with dictionary information for all components of the structure type. Output
the report header for all components in sequence. Ensure that the output does not exceed the
display length of the corresponding field.
1. Create an internal table with type ddfields (suggested name: lt_fields).
2. Call a suitable method of class CL_ABAP_STRUCTDESCR to generate a list with dictionary
information for the structure components. To do so, supply the internal table it_fields as
the actual parameter for the return value. If the method call terminates with exceptions,
exit the write_headers method with a suitable exception.
3. To program a loop over the internal table, create a field symbol (suggested name is
<fs_flist>) that is typed with the line type of internal table lt_fields.
4. Output the report header (field reptext) in each loop pass. Use the output length (field
outputlen) for length access to ensure the headers are exactly as long as they will be
output later.
Copy Template Program
Copy program BC402_DYS_GEN_TYPES or your own program, ZBC402_##_GEN_TYPES and
name it ZBC402_##_RTTI_HEADERS. Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test the program. Analyze the source code.
Call Method write_headers
Insert a call of method write_headers before the data output. Pass the name of the line type of
the internal table with the data to your method.
1. Implement a call of method write_headers before the call of method write_any_table. Pass
the data object that contains the name of the database table (and therefore the name of
the line type of the internal table).
2. React to exceptions with suitable error messages from message class BC402.
348
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
3. Activate and test the program.
© Copyright. All rights reserved.
349
Unit 5
Solution 16
Provide Column Headers Using RTTI
Business Example
You need to develop a simple program that displays the contents of any database table. To
develop the program, you need to find out about the options available in dynamic
programming. You have already developed a method to output any internal table with a flat
line type to a list. You need to use the options of RTTI to develop a method that generates
dynamic column headers for the program.
Use RTTI to analyze a structure type and to determine semantic information for that structure
type from the ABAP Dictionary. Use the semantic information for the structure type to
generate column headers dynamically.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Class
Copy template CL_BC402_DYT_RTTI_HEADERS and name it
ZCL_BC402_##_RTTI_HEADERS. Familiarize yourself with the class definition.
1. Copy the global class.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Class/Interface and
specify the name of the class CL_BC402_DYT_RTTI_HEADERS.
c) Choose Display.
d) Right-click CL_BC402_DYT_RTTI_HEADERSand choose Copy....
e) In the Copy CL_BC402_DYT_RTTI_HEADERSdialog box, in the Copy to field, enter
ZCL_BC402_##_RTTI_HEADERS and choose Copy.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Analyze the class definition. Determine which methods are defined and what their
purposes are?
write_headers to output a list of column headers based on a structure type from the ABAP
Dictionary.
350
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
3. Which parameters and exceptions do these methods have? How are the parameters
typed? Which error situations correspond to the exceptions?
Parameter iv_tabname with generic type csequence and exceptions. Error situations that
correspond to the exceptions are as follows: TYPE_NOT_FOUND: the supplied type is
unknown, NO_STRUCTURE: the object is not a structure type, NO_DDIC_TYPE: the object
is not a type in the ABAP Dictionary.
Implement Method write_headers
Implement method write_headers. Use RTTI options to analyze the Dictionary table whose
name is passed to the import parameter gv_tabname.
1. Call a suitable static method of class CL_ABAP_TYPEDESCR to analyze the data type
based on its name.
a) In the Methods tab, double-click WRITE_HEADERS and choose Display<->Change.
b) See the source code excerpt from the model solution.
2. Create a local reference variable (suggested name is lo_type) and type it to match the
return parameter of the method. Specify this reference variable as an actual parameter in
the method call.
a) See the source code excerpt from the model solution.
3. Handle any possible exceptions and raise exception TYPE_NOT_FOUND from method
write_headers in response.
a) See the source code excerpt from the model solution.
4. Use the public KIND attribute to determine whether the generated RTTI instance actually
describes a structure type. If the data type is not a structure type, exit method
write_headers with exception NO_STRUCTURE.
a) See the source code excerpt from the model solution.
5. Create a local reference variable (suggested name is lo_struct) of TYPE REF TO
CL_ABAP_STRUCTDESCR. Program a down cast to point this reference to the type
description object.
Hint:
There is no need to catch possible runtime errors here because the query of
the KIND attribute already ensures compatibility.
a) See the source code excerpt from the model solution.
Output the Report Header for all Components
Determine a list with dictionary information for all components of the structure type. Output
the report header for all components in sequence. Ensure that the output does not exceed the
display length of the corresponding field.
1. Create an internal table with type ddfields (suggested name: lt_fields).
a) See the source code excerpt from the model solution.
2. Call a suitable method of class CL_ABAP_STRUCTDESCR to generate a list with dictionary
information for the structure components. To do so, supply the internal table it_fields as
© Copyright. All rights reserved.
351
Unit 5: Dynamic Programming
the actual parameter for the return value. If the method call terminates with exceptions,
exit the write_headers method with a suitable exception.
a) See the source code excerpt from the model solution.
3. To program a loop over the internal table, create a field symbol (suggested name is
<fs_flist>) that is typed with the line type of internal table lt_fields.
a) See the source code excerpt from the model solution.
4. Output the report header (field reptext) in each loop pass. Use the output length (field
outputlen) for length access to ensure the headers are exactly as long as they will be
output later.
a) See the source code excerpt from the model solution.
Copy Template Program
Copy program BC402_DYS_GEN_TYPES or your own program, ZBC402_##_GEN_TYPES and
name it ZBC402_##_RTTI_HEADERS. Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) In SE80, in the unnamed dropdown menu on the left of the screen, choose Program
and specify the name of the program ZBC402_##_GEN_TYPES.
b) Choose Display.
c) Right-click ZBC402_##_GEN_TYPESand choose Copy....
d) In the Copy Program ZBC402_##_GEN_TYPESdialog box, in the Target program field,
enter ZBC402_##_RTTI_HEADERS and choose Copy.
e) In the Copy Program ZBC402_##_GEN_TYPES to ZBC402_##_RTTI_HEADERSdialog
box, select all checkboxes and choose Copy.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test the program. Analyze the source code.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Call Method write_headers
Insert a call of method write_headers before the data output. Pass the name of the line type of
the internal table with the data to your method.
1. Implement a call of method write_headers before the call of method write_any_table. Pass
the data object that contains the name of the database table (and therefore the name of
the line type of the internal table).
a) See the source code excerpt from the model solution.
2. React to exceptions with suitable error messages from message class BC402.
a) See the source code excerpt from the model solution.
3. Activate and test the program.
a) Choose the Check button.
352
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
Method write_headers (Class_CL_BC402_DYS_RTTI_HEADERS)
METHOD write_headers.
DATA:
lo_type
TYPE REF TO cl_abap_typedescr,
lo_struct TYPE REF TO cl_abap_structdescr,
lt_flist TYPE ddfields.
FIELD-SYMBOLS:
<fs_flist> LIKE LINE OF lt_flist.
CALL METHOD cl_abap_typedescr=>describe_by_name
EXPORTING
p_name
= iv_tabname
RECEIVING
p_descr_ref
= lo_type
EXCEPTIONS
type_not_found = 1.
IF sy-subrc <> 0.
RAISE type_not_found.
ENDIF.
IF lo_type->kind <> cl_abap_typedescr=>kind_struct.
RAISE no_structure.
ENDIF.
lo_struct ?= lo_type.
CALL METHOD lo_struct->get_ddic_field_list
RECEIVING
p_field_list
= lt_flist
EXCEPTIONS
not_found
= 1
no_ddic_type
= 2.
CASE sy-subrc.
WHEN 1.
RAISE type_not_found.
WHEN 2.
RAISE no_ddic_type.
ENDCASE.
NEW-LINE.
LOOP AT lt_flist ASSIGNING <fs_flist> .
WRITE <fs_flist>-reptext(<fs_flist>-outputlen) COLOR COL_HEADING.
ENDLOOP.
ULINE.
ENDMETHOD.
© Copyright. All rights reserved.
353
Unit 5: Dynamic Programming
Executable Program BC402_DYS_RTTI_HEADERS
REPORT
bc402_dys_rtti_headers MESSAGE-ID bc402.
TYPE-POOLS: abap.
DATA:
gt_cust
gt_conn
DATA:
gv_tabname
TYPE ty_customers,
TYPE ty_connections.
TYPE string.
FIELD-SYMBOLS:
<fs_table> TYPE ANY TABLE.
SELECTION-SCREEN COMMENT 1(80) text-sel.
PARAMETERS:
pa_xconn TYPE xfeld RADIOBUTTON GROUP tab DEFAULT 'X',
pa_xcust TYPE xfeld RADIOBUTTON GROUP tab .
PARAMETERS:
pa_nol
TYPE i DEFAULT '100'.
START-OF-SELECTION.
* specific part
*----------------------------------------------------*
CASE 'X'.
WHEN pa_xconn.
gv_tabname = 'SPFLI'.
ASSIGN gt_conn TO <fs_table>.
WHEN pa_xcust.
gv_tabname = 'SCUSTOM'.
ASSIGN gt_cust TO <fs_table>.
ENDCASE.
* dynamic part
*------------------------------------------------------*
TRY.
SELECT * FROM (gv_tabname) INTO TABLE <fs_table>
UP TO pa_nol ROWS.
CATCH cx_sy_dynamic_osql_error.
MESSAGE e061.
ENDTRY.
CALL METHOD cl_bc402_dys_rtti_headers=>write_headers
EXPORTING
iv_tabname
= gv_tabname
EXCEPTIONS
type_not_found = 1
no_structure
= 2
no_ddic_type
= 3.
CASE sy-subrc.
WHEN 1.
354
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
MESSAGE e050 WITH gv_tabname.
WHEN 2.
MESSAGE e051 WITH gv_tabname.
WHEN 3.
MESSAGE e052 WITH gv_tabname.
ENDCASE.
cl_bc402_dys_gen_types=>write_any_table( <fs_table> ).
© Copyright. All rights reserved.
355
Unit 5: Dynamic Programming
Object Type Analysis
Figure 165: Analysis of an Object Type
RTTI permits you to analyze the attributes of objects by working with classes
CL_ABAP_CLASSDESCR and CL_ABAP_INTFDESCR.
Most of the attributes and methods for these two classes are defined in the (abstract) shared
superclass CL_ABAP_OBJECTDESCR because they are required to analyze both classes and
interfaces.
Note:
A class is analyzed in the example shown in the figure Analysis of an Object Type.
Most of the information also applies to the analysis of interfaces.
Class CL_ABAP_CLASSDESCR contains public attributes that list the attributes, methods,
events, interfaces, and other objects of the described class. These attributes are typed as
internal tables. Some of these attributes, such as METHODS, are defined as nested internal
tables in which each line itself contains one or more internal tables. For example, these nested
internal tables contain lists with parameters and exceptions for the respective method.
In addition to these inherited attributes, class CL_ABAP_CLASSDESCR also provides specific
attributes, such as the CLASS_KIND attribute, which you use to determine whether the class
was flagged as abstract, final, and so on.
356
© Copyright. All rights reserved.
Lesson: Describing Data Types, Data Objects, and Objects at Runtime
Note:
Class CL_ABAP_INTFDESCR contains an INTF_KIND attribute instead, which you
use to determine whether an interface is comprised of multiple interfaces.
The figure Analysis of an Object Type demonstrates how to use RTTI to determine all the
parameters of the constructor for class CL_RENTAL.
After the program generates the description object and performs the downcast, it reads the
description of the constructor method from the list of methods (statement with READ
TABLE). The program then evaluates the list of parameters for the constructor method in a
loop (LOOP over the inner internal table).
The description classes for object types also provide navigation methods for determining the
details of a used type. For example, the GET_ATTRIBUTE_TYPE method returns the
description object for the type of a specific attribute, while
GET_METHOD_PARAMETER_TYPE analyzes the type of a specific method parameter, and so
on.
The GET_SUPER_CLASS_TYPE method is specific to classes. It returns the description object
for the direct superclass, if any.
© Copyright. All rights reserved.
357
Unit 5: Dynamic Programming
LESSON SUMMARY
You should now be able to:
358
●
Explain Runtime Type Identification (RTTI)
●
Describe data types and data objects at runtime
●
Describe object types and objects at runtime
© Copyright. All rights reserved.
Unit 5
Lesson 5
Creating Data Types, Data Objects, and
Objects at Runtime
LESSON OVERVIEW
In this lesson, you will learn how to generate data objects (as instances of data types) at
runtime, which is similar to creating instances of classes in object-oriented programming. In
contrast to data objects that are created statically with the DATA statement, you do not have
to directly set the type of dynamically generated data objects. Instead, the type can be
determined dynamically at runtime. You will also learn about Runtime Type Creation (RTTC),
a technique that lets you define the data type at runtime.
Business Example
You need to develop a flexible application. In addition to accessing existing data objects
dynamically and analyzing the underlying data types, you also want to learn about the
techniques available to generate objects, data objects, and data types at runtime according to
the requirements of the program. For this reason, you require the following knowledge:
●
An understanding of how to generate objects or instances at runtime
●
An understanding of how to generate data objects at runtime
●
An understanding of how to generate data types at runtime
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Create objects at runtime
●
Create data objects at runtime
●
Create data types at runtime
© Copyright. All rights reserved.
359
Unit 5: Dynamic Programming
Dynamic Object Creation
Figure 166: Options for Generating Objects at Runtime
The CREATE OBJECT statement generates objects or specifically, instances of classes at
runtime. Usually, the type of object, (that is, the class to be instantiated) is defined implicitly
through the static type of the reference variable used.
Alternatively, you can use the TYPE addition to specify the class to be instantiated in the
CREATE OBJECT statement.
The following rules apply when using the TYPE addition of the CREATE OBJECT statement:
●
A class, not an interface, must appear after the TYPE addition.
●
You must be able to instantiate the class, which means that it cannot be flagged as
abstract.
●
The static type of the reference variable must be compatible with the class.
The last rule applies because the system carries out an implicit upcast if necessary when you
specify the type explicitly.
The reference variable is compatible with the created object if it meets one of the following
conditions:
360
●
The reference variable is typed with the class to be instantiated.
●
The reference variable is typed with a superclass of the class to be instantiated.
●
The reference variable is typed with an interface that is implemented by the class to be
instantiated.
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
●
The reference variable is typed with the generic TYPE REF TO OBJECT.
The syntax for specifying an explicit type can include a data object in parentheses after TYPE.
This syntax enables dynamic selection of the class to be instantiated.
Hint:
If classes are available for selections that are not linked through a shared
superclass or the same implementing interface, type the reference variable
completely generically with TYPE REF TO OBJECT.
Dynamic Parameter Passing
Figure 167: Dynamic Passing of Parameters
If all potential classes have the same constructor signature, the parameters can be supplied
with data statically. However, it is likely that the parameters and exceptions of the
constructors will differ. In this case, you need to use dynamic parameter transfer.
As with dynamic method calls, perform dynamic parameter transfer using internal tables
after the PARAMETER-TABLE and EXCEPTION-TABLE additions. These internal tables need to
be typed and filled just like with dynamic method calls.
© Copyright. All rights reserved.
361
Unit 5: Dynamic Programming
Dynamic Data Object Creation
Figure 168: Options for Creating Data Objects at Runtime
You can also create data objects at runtime. The corresponding statement, CREATE DATA, is
used in a similar way to the CREATE OBJECT statement.
The CREATE DATA statement creates a data object dynamically, assigns memory to it, and
points the data reference variable to that data object in memory.
The data object is not given a name, so it is often called an anonymous data object. To
address the data object, dereference the reference variable at runtime.
Hint:
In contrast to the static DATA declaration, the system does not reserve the
memory for the data objects until runtime, and it does not reserve the memory
when the respective program is loaded. Like with class instances, the garbage
collector releases the memory again as soon as the program deletes the last
reference to the data object.
As withCREATE OBJECT, you can define the type of the data object implicitly by using the
type of the reference variable, or explicitly by using the TYPE addition. If you use explicit
typing, you can use a number of variants that you might be familiar with from DATA
declarations. These variants include the use of built-in types, the implicit construction of table
types, and the reference to an existing data object with LIKE.
To define the data type for the generated data objects dynamically, use character-type data
objects in parentheses.
362
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Note:
Alternatively, use the TYPE HANDLE addition to refer to an RTTI-type description
object.
Access to Dynamically Created Data Objects
Figure 169: Access to Dynamically Created Data Objects
If the data type is to be determined dynamically, the reference variable must be typed
generically with TYPE REF TO DATA. This is the only generic type that can be used for data
references at present.
Reasons for Assigning Field Symbols to the Referenced Data Object
●
You can only dereference the generic data reference in the ASSIGN statement.
●
You can use generically typed field symbols almost anywhere.
Hint:
If the new data object is an internal table and you want to use it in the
corresponding operand positions, the field symbol must contain at least type
ANY TABLE.
© Copyright. All rights reserved.
363
Unit 5: Dynamic Programming
Dynamically Generated Internal Table and Dynamic SELECT
Figure 170: Example – Dynamically Generated Internal Table and Dynamic SELECT
The figure Example – Dynamically Generated Internal Table and Dynamic SELECT shows an
example of a dynamic database access in which the suitable data object is generated at
runtime.
364
© Copyright. All rights reserved.
Unit 5
Exercise 17
Create Data Objects at Runtime
Business Example
You need to develop a simple program that displays the contents of any database table by
using the options available in dynamic programming.
Note:
The program you created in the exercise Provide Column Headers Using RTTI
can already output the content of any internal table in a list. The database access
(the SELECT statement) has a dynamic design. At this point, there is one more
condition that hinders you from reading any table: The data objects that you fill in
the SELECT statement must have static definitions.
In this exercise, you generate data objects dynamically at runtime. This enables
your program to read and display the content of any database table.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy program BC402_DYS_RTTI_HEADERS or your own program,
ZBC402_##_RTTI_HEADERS and name it ZBC402_##_CREATE_DATA. Familiarize yourself
with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test the program.
3. Analyze the source code. Which data objects are filled during the database access? Which
types do they have? Were they created statically or dynamically?
Create an Internal Table at Runtime
Replace the two statically defined internal tables with a data object that you generate after the
CASE structure (standard table with non-unique standard key). Define the type of the data
object dynamically to ensure that the line type precisely matches the structure of the
database table you want to read.
1. Define a generically typed data reference (suggested name is gr_data).
© Copyright. All rights reserved.
365
Unit 5: Dynamic Programming
2. Use the gr_data data reference to generate an internal table immediately after the
ENDCASE statement. Access the contents of data object gv_tabname to define the line
type of the table dynamically.
3. Move one of the ASSIGN statements outside the WHEN blocks after the data object is
generated, and delete the other ASSIGN statement. Replace the statically defined internal
table with the dynamically generated table.
Hint:
Dereference the generic data reference.
4. Why can you not continue to use gr_data directly?
5. Delete the definitions of the two static internal tables or comment them out.
6. Activate and test your program.
Allow Any Database Table to be Selected by the User
The static part of the program now contains only the filling of data object gv_tabname with an
appropriate literal for the name of the database table. Replace both checkboxes on the
selection screen with a parameter for the name of any database table.
1. Delete the selection screen parameter definitions for the two checkboxes, or comment
them out.
2. Create a new parameter (suggested name is pa_tab).
Hint:
If you use the global type dd02l-tabname, a value (F4) help function is
provided for the users.
3. Delete the CASE structure or comment it out. In the same position, program a value
assignment from pa_tab to gv_tabname.
4. Activate and test your program.
366
© Copyright. All rights reserved.
Unit 5
Solution 17
Create Data Objects at Runtime
Business Example
You need to develop a simple program that displays the contents of any database table by
using the options available in dynamic programming.
Note:
The program you created in the exercise Provide Column Headers Using RTTI
can already output the content of any internal table in a list. The database access
(the SELECT statement) has a dynamic design. At this point, there is one more
condition that hinders you from reading any table: The data objects that you fill in
the SELECT statement must have static definitions.
In this exercise, you generate data objects dynamically at runtime. This enables
your program to read and display the content of any database table.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy program BC402_DYS_RTTI_HEADERS or your own program,
ZBC402_##_RTTI_HEADERS and name it ZBC402_##_CREATE_DATA. Familiarize yourself
with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_RTTI_HEADERS.
c) Choose Display.
d) Right-click ZBC402_##_RTTI_HEADERSand choose Copy....
e) In the Copy Program ZBC402_##_RTTI_HEADERSdialog box, in the Target program
field, enter ZBC402_##_CREATE_DATA and choose Copy.
f) In the Copy Program ZBC402_##_RTTI_HEADERS to ZBC402_##_CREATE_DATA
dialog box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
© Copyright. All rights reserved.
367
Unit 5: Dynamic Programming
2. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
3. Analyze the source code. Which data objects are filled during the database access? Which
types do they have? Were they created statically or dynamically?
One of two internal tables, gt_conn or gt_cust, is filled depending on the user entry. While
the data object assigned to field symbol <fs_table> (which is therefore addressed in the
SELECT statement) is determined dynamically, the data objects themselves have static
definitions (DATA statement).
Create an Internal Table at Runtime
Replace the two statically defined internal tables with a data object that you generate after the
CASE structure (standard table with non-unique standard key). Define the type of the data
object dynamically to ensure that the line type precisely matches the structure of the
database table you want to read.
1. Define a generically typed data reference (suggested name is gr_data).
a) See the source code excerpt from the model solution.
2. Use the gr_data data reference to generate an internal table immediately after the
ENDCASE statement. Access the contents of data object gv_tabname to define the line
type of the table dynamically.
a) See the source code excerpt from the model solution.
3. Move one of the ASSIGN statements outside the WHEN blocks after the data object is
generated, and delete the other ASSIGN statement. Replace the statically defined internal
table with the dynamically generated table.
Hint:
Dereference the generic data reference.
a) See the source code excerpt from the model solution.
4. Why can you not continue to use gr_data directly?
Because gr_data has a generic type and ABAP only allows dereferenced access to
generically typed data references in ASSIGN statements.
5. Delete the definitions of the two static internal tables or comment them out.
a) See the source code excerpt from the model solution.
6. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
368
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Allow Any Database Table to be Selected by the User
The static part of the program now contains only the filling of data object gv_tabname with an
appropriate literal for the name of the database table. Replace both checkboxes on the
selection screen with a parameter for the name of any database table.
1. Delete the selection screen parameter definitions for the two checkboxes, or comment
them out.
a) See the source code excerpt from the model solution.
2. Create a new parameter (suggested name is pa_tab).
Hint:
If you use the global type dd02l-tabname, a value (F4) help function is
provided for the users.
a) See the source code excerpt from the model solution.
3. Delete the CASE structure or comment it out. In the same position, program a value
assignment from pa_tab to gv_tabname.
a) See the source code excerpt from the model solution.
4. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
*&--------------------------------------*
*& Report BC402_DYS_CREATE_DATA
*&
*&--------------------------------------*
*&
*&
*&--------------------------------------*
REPORT bc402_dys_create_data MESSAGE-ID bc402.
*DATA:
* gt_cust
TYPE ty_customers,
* gt_conn
TYPE ty_connections.
DATA:
gr_data TYPE REF TO data.
DATA:
gv_tabname TYPE string.
FIELD-SYMBOLS:
<fs_table> TYPE ANY TABLE.
SELECTION-SCREEN COMMENT 1(80) text-sel.
*PARAMETERS:
*
pa_xconn TYPE xfeld RADIOBUTTON GROUP tab DEFAULT 'X',
*
pa_xcust TYPE xfeld RADIOBUTTON GROUP tab .
PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT 'SPFLI'.
PARAMETERS:
© Copyright. All rights reserved.
369
Unit 5: Dynamic Programming
pa_nol
TYPE i DEFAULT '100'.
START-OF-SELECTION.
* specific part
*---------------------------------*
* CASE 'X'.
*
WHEN pa_xconn.
*
*
gv_tabname = 'SPFLI'.
*
ASSIGN gt_conn TO <fs_table> .
*
*
WHEN pa_xcust.
*
*
gv_tabname = 'SCUSTOM'.
*
ASSIGN gt_cust TO <fs_table> .
*
* ENDCASE.
* dynamic part
*---------------------------------*
gv_tabname = pa_tab.
CREATE DATA gr_data TYPE TABLE OF (gv_tabname).
ASSIGN gr_data->* TO <fs_table> .
TRY.
SELECT * FROM (gv_tabname) INTO TABLE <fs_table>
UP TO pa_nol ROWS.
CATCH cx_sy_dynamic_osql_error.
MESSAGE e061.
ENDTRY.
CALL METHOD cl_bc402_dys_rtti_headers=>write_headers
EXPORTING
iv_tabname
= gv_tabname
EXCEPTIONS
type_not_found = 1
no_structure
= 2
no_ddic_type
= 3.
CASE sy-subrc.
WHEN 1.
MESSAGE e050 WITH gv_tabname.
WHEN 2.
MESSAGE e051 WITH gv_tabname.
WHEN 3.
MESSAGE e052 WITH gv_tabname.
ENDCASE.
cl_bc402_dys_gen_types=>write_any_table( <fs_table> ).
370
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Runtime Type Creation (RTTC)
Figure 171: Dynamic Type Creation Methods of Runtime Type Services
RTTI enables you to describe data types and object types with instances of RTTI classes or
type description objects. The RTTI concept was enhanced in SAP Web AS 6.40. In addition to
describing existing types, you can use it to generate new types. This enhanced function set is
called runtime type creation (RTTC).
RTTC consists of a number of additional static methods in the RTTI description classes.
Hint:
Note that type generation is restricted to data types. You cannot generate
classes or interfaces dynamically.
In the figure Dynamic Type Creation Methods of Runtime Type Services, the
CL_ABAP_REFDESCR, CL_ABAP_STRUCTDESCR, and CL_ABAP_TABLEDESCR classes are
enhanced with a CREATE method, while the CL_ABAP_ELEMDESCR class receives an
appropriate GET method for each built-in elementary ABAP type such as, GET_I, GET_F,
GET_C, GET_STRING.
These methods return pointers to an instance of the respective class. In contrast to the
DESCRIBE methods of the root class, the attribute values of this instance do not come from
analyzing a data object, a reference, or a named type. Instead, they are passed on to the
RTTC method explicitly.
The method signatures have been designed accordingly. While the GET_I method does not
need any other input (type i is complete), method GET_P has two import parameters defined:
one for length and the other for the number of decimal places.
© Copyright. All rights reserved.
371
Unit 5: Dynamic Programming
The CREATE method for reference types expects the pointer to the description object for the
referenced type, while the CREATE method for structure types expects a list with names and
types of the components. When table types are generated, a reference to an RTTI object that
describes the line type is expected (among other things).
Dynamic Table Type Creation
Figure 172: RTTC – Creating a Table Type
The figure RTTC – Creating a Table Type shows how to generate a table type dynamically with
RTTC.
You are required to specify only the P_LINE_TYPE parameter for the CREATE method. The
parameter is of type REF TO CL_ABAP_DATADESCR and needs to be supplied with a
reference to any description object for a data type. In the example shown in the figure RTTC –
Creating a Table Type, SPFLI is used as the line type. The DESCRIBE_BY_NAME method
returns the matching description object.
The optional parameters are used to define the table type and key. If you do not specify them,
a standard table with a non-unique standard key is used by default.
372
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Use of RTTC Types
Figure 173: Generating an Internal Table with a Dynamically Created Type
To dynamically create a data object with this specific type, use the dynamically generated
type in the CREATE DATA statement.
Use the HANDLE addition with the CREATE DATA statement to generate a data object whose
type matches the specified type description object. Specify the HANDLE as a reference
variable with static type CL_ABAP_DATADESCR or one of its subclasses. The type object may
have been created based on existing data types, using RTTI methods or by dynamically
defining a new data type.
© Copyright. All rights reserved.
373
Unit 5: Dynamic Programming
374
© Copyright. All rights reserved.
Unit 5
Exercise 18
Create Data Types at Runtime with RTTC
Business Example
You have developed a simple program that displays the contents of any database table. The
program now needs to allow users to select the specific columns they want to read and
display.
You should use function module BC402_SELECT_COMPONENTS, which displays all the
components of a global structure type and enables users to select components. You then
need to use RTTC to generate a table type dynamically, with a line type containing only the
user-selected components.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Analyze Function Module BC402_SELECT_COMPONENTS
Display function module BC402_SELECT_COMPONENTS. Analyze the interface and test the
functional scope of the function module.
1. Display the function module.
2. Analyze the interface. Which parameters are there and what are their types?
3. Which exceptions can the function module raise, and what purpose do they serve?
4. Test the function module using table SPFLI.
Call Function Module BC402_SELECT_COMPONENTS
Copy program BC402_DYS_CREATE_DATA or your own program
ZBC402_##_CREATE_DATA and name it ZBC402_##_RTTC. Familiarize yourself with the
program and how it works. Implement a call of the function module before the dynamic
generation of the data object. Pass the table name that the user entered on the selection
screen to the import parameter.
1. Copy the program and all its subcomponents.
2. Call the function module before the CREATE DATA statement. Create a suitably typed data
object to import the data from the function module parameter ET_COMP_NAMES. Pass
© Copyright. All rights reserved.
375
Unit 5: Dynamic Programming
the contents of gv_tabname to the import parameter. React to exceptions with suitable
error messages from message class BC402.
Copy the Template Class
Copy the template class CL_BC402_DYT_RTTC and name it ZCL_BC402_##_RTTC.
Familiarize yourself with the signature of method create_table_type.
1. Copy the global class.
2. Analyze the create_table_type method signature. Which parameters are defined? How are
they typed?
Implement the create_table_type Method
Use RTTI techniques to analyze the data type of the database table name contained in the
import parameter. Use a suitable navigation method to create a list with the names and RTTI
type description objects for all components in the structure.
1. Call a suitable method of class CL_ABAP_TYPEDESCR to generate a type description
object for the data type. Create a reference variable with a suitable type for the return
value (suggested name: lo_struct).
Hint:
For simplicity, assume that the data type is a structure type in the ABAP
Dictionary and perform a direct down cast to the corresponding reference
variable.
2. Call the get_components method for the RTTI instance. Create a data object with a
suitable type for the return value (suggested name is lt_comps).
Create a Table Type Description Object with Only the Required Components
Change the list of components so that it only contains the components listed in import
parameter it_comp_names. Based on this list of components, create a new structure type,
and then a new table type.
1. Implement a loop over the lt_comps component list.
2. Check whether the component name in each line is contained in import parameter
it_comp_names.
Hint:
Use a statement such as FIND ... IN TABLE or READ TABLE ...
TRANSPORTING NO FIELDS.
3. Remove the current line from lt_comps if the corresponding table name is not contained in
import parameter it_comp_names.
376
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Hint:
Use the abbreviated syntax for index access in loops here.
4. To generate an RTTI type description object for a new structure type, call the CREATE
method of class CL_ABAP_STRUCTDESCR. Pass the reduced component list to the
method. Create a data object with a suitable type for the return parameter (suggested
name: lo_struct_new).
5. To generate an RTTI type description object for a new table type, call the CREATE method
of class CL_ABAP_TABLEDESCR. Pass the reference to the RTTI object for the new
structure type. Leave all the optional parameters set to their default values. Transfer the
result of the method call directly to return parameter ro_table_def of method
create_table_type.
Call an Internal Table at Runtime with Only the Required Components
Go back to your executable program ZBC402_##_RTTC. Call method create_table_type to
generate a table type according to the requirements of the user. Use the new data type when
you generate the data object dynamically. Change the SELECT statement so that it reads only
those fields from the database that are contained in the line type of the internal table.
Hint:
Method write_headers still outputs the headers for all the columns in the table.
Either work without the headers completely or use method
write_headers_by_data from class CL_BC402_DYS_RTTI_HEADERS. This
method analyzes the actual line type of an internal table and outputs the column
headers for it.
1. Call method create_table_type in the program directly after the call of function
module BC402_SELECT_COMPONENTS. Pass the name of the database table and the list
of components that the user selected to the method create_table_type.
2. Change the type in the CREATE DATA statement. Use the TYPE HANDLE addition to use
the newly generated table type.
3. Change the SELECT statement. Use the list of component names as a dynamic field list.
Hint:
Alternatively, use the INTO CORRESPONDING FIELDS OF TABLE addition.
4. Activate and test your program.
© Copyright. All rights reserved.
377
Unit 5
Solution 18
Create Data Types at Runtime with RTTC
Business Example
You have developed a simple program that displays the contents of any database table. The
program now needs to allow users to select the specific columns they want to read and
display.
You should use function module BC402_SELECT_COMPONENTS, which displays all the
components of a global structure type and enables users to select components. You then
need to use RTTC to generate a table type dynamically, with a line type containing only the
user-selected components.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Analyze Function Module BC402_SELECT_COMPONENTS
Display function module BC402_SELECT_COMPONENTS. Analyze the interface and test the
functional scope of the function module.
1. Display the function module.
a) To start the Object Navigator, enter transaction code se80.
b) Choose the Other Object... button.
c) In the Object Selection dialog box, select the Enhanced Optionsradio button.
d) Choose the Function Group tab and select the Function Module radio button.
e) In the Function Module field, enter BC402_SELECT_COMPONENTS and choose Continue.
2. Analyze the interface. Which parameters are there and what are their types?
There is one import parameter, iv_tabname, with type csequence and one export
parameter, et_comp_names, with type string_table (standard table with string line type).
3. Which exceptions can the function module raise, and what purpose do they serve?
The exceptions raised by the function module and the purposes served by those
exceptions are as follows: TYPE_NOT_FOUND: the passed type is unknown,
NO_STRUCTURE: the passed type is not a structure, NO_DDIC_TYPE: the passed type is
not a DDIC type.
4. Test the function module using table SPFLI.
378
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
a) Choose the Test/Execute button.
b) In the Value field next to the parameter IV_TABNAME, enter SPFLI.
c) Choose Execute.
d) To select a few rows, select the button to the left of the first row, and, on your
keyboard, press the Ctrl key. Then, select the buttons next to the other rows you want
to select.
e) Choose the Transfer Selectionbutton.
The function module has now finished and the export parameter ET_COMP_NAMES is
displayed.
f) To view the data for the parameter, choose the Details View/Edit button.
Call Function Module BC402_SELECT_COMPONENTS
Copy program BC402_DYS_CREATE_DATA or your own program
ZBC402_##_CREATE_DATA and name it ZBC402_##_RTTC. Familiarize yourself with the
program and how it works. Implement a call of the function module before the dynamic
generation of the data object. Pass the table name that the user entered on the selection
screen to the import parameter.
1. Copy the program and all its subcomponents.
a) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_CREATE_DATA.
b) Choose Display.
c) Right-click ZBC402_##_CREATE_DATAand choose Copy....
d) In the Copy Program ZBC402_##_CREATE_DATAdialog box, in the Target program
field, enter ZBC402_##_RTTC and choose Copy.
e) In the Copy Program ZBC402_##_CREATE_DATA to ZBC402_##_RTTCdialog box,
select all checkboxes and choose Copy.
f) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Call the function module before the CREATE DATA statement. Create a suitably typed data
object to import the data from the function module parameter ET_COMP_NAMES. Pass
the contents of gv_tabname to the import parameter. React to exceptions with suitable
error messages from message class BC402.
a) See the source code excerpt from the model solution.
Copy the Template Class
Copy the template class CL_BC402_DYT_RTTC and name it ZCL_BC402_##_RTTC.
Familiarize yourself with the signature of method create_table_type.
1. Copy the global class.
a) In the unnamed dropdown menu on the left of the screen, choose Class/Interface and
specify the name of the class CL_BC402_DYT_RTTC.
b) Choose Display.
c) Right-click CL_BC402_DYT_RTTCand choose Copy....
© Copyright. All rights reserved.
379
Unit 5: Dynamic Programming
d) In the Copy CL_BC402_DYT_RTTCdialog box, in the Copy to field, enter
ZCL_BC402_##_RTTC and choose Copy.
e) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
f) In the Methods tab, choose the Parameter button.
2. Analyze the create_table_type method signature. Which parameters are defined? How are
they typed?
Import parameter iv_tabname with generic type csequence, import parameter
it_comp_names with type string_table, and return parameter ro_tabledescr, a reference to
class cl_abap_tabledescr.
Implement the create_table_type Method
Use RTTI techniques to analyze the data type of the database table name contained in the
import parameter. Use a suitable navigation method to create a list with the names and RTTI
type description objects for all components in the structure.
1. Call a suitable method of class CL_ABAP_TYPEDESCR to generate a type description
object for the data type. Create a reference variable with a suitable type for the return
value (suggested name: lo_struct).
Hint:
For simplicity, assume that the data type is a structure type in the ABAP
Dictionary and perform a direct down cast to the corresponding reference
variable.
a) Chose the Back to Methods button.
b) In the Methods tab, double-click CREATE_TABLE_TYPEand choose the Display<>Change button.
c) See the source code excerpt from the model solution.
2. Call the get_components method for the RTTI instance. Create a data object with a
suitable type for the return value (suggested name is lt_comps).
a) See the source code excerpt from the model solution.
Create a Table Type Description Object with Only the Required Components
Change the list of components so that it only contains the components listed in import
parameter it_comp_names. Based on this list of components, create a new structure type,
and then a new table type.
1. Implement a loop over the lt_comps component list.
a) See the source code excerpt from the model solution.
2. Check whether the component name in each line is contained in import parameter
it_comp_names.
380
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
Hint:
Use a statement such as FIND ... IN TABLE or READ TABLE ...
TRANSPORTING NO FIELDS.
a) See the source code excerpt from the model solution.
3. Remove the current line from lt_comps if the corresponding table name is not contained in
import parameter it_comp_names.
Hint:
Use the abbreviated syntax for index access in loops here.
a) See the source code excerpt from the model solution.
4. To generate an RTTI type description object for a new structure type, call the CREATE
method of class CL_ABAP_STRUCTDESCR. Pass the reduced component list to the
method. Create a data object with a suitable type for the return parameter (suggested
name: lo_struct_new).
a) See the source code excerpt from the model solution.
5. To generate an RTTI type description object for a new table type, call the CREATE method
of class CL_ABAP_TABLEDESCR. Pass the reference to the RTTI object for the new
structure type. Leave all the optional parameters set to their default values. Transfer the
result of the method call directly to return parameter ro_table_def of method
create_table_type.
a) See the source code excerpt from the model solution.
Call an Internal Table at Runtime with Only the Required Components
Go back to your executable program ZBC402_##_RTTC. Call method create_table_type to
generate a table type according to the requirements of the user. Use the new data type when
you generate the data object dynamically. Change the SELECT statement so that it reads only
those fields from the database that are contained in the line type of the internal table.
Hint:
Method write_headers still outputs the headers for all the columns in the table.
Either work without the headers completely or use method
write_headers_by_data from class CL_BC402_DYS_RTTI_HEADERS. This
method analyzes the actual line type of an internal table and outputs the column
headers for it.
1. Call method create_table_type in the program directly after the call of function
module BC402_SELECT_COMPONENTS. Pass the name of the database table and the list
of components that the user selected to the method create_table_type.
a) In transaction SE80, in the unnamed dropdown list on the left of the screen, choose
Program.
b) In the field underneath Program, enter the name ZBC402_##_RTTC, and choose
Display.
© Copyright. All rights reserved.
381
Unit 5: Dynamic Programming
c) In the Object list, double-click the program name.
d) See the source code excerpt from the model solution.
2. Change the type in the CREATE DATA statement. Use the TYPE HANDLE addition to use
the newly generated table type.
a) See the source code excerpt from the model solution.
3. Change the SELECT statement. Use the list of component names as a dynamic field list.
Hint:
Alternatively, use the INTO CORRESPONDING FIELDS OF TABLE addition.
4. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
Method create_table_type (Class CL_BC402_DYS_RTTC)
METHOD create_table_type.
DATA:
lo_struct
TYPE REF TO cl_abap_structdescr,
lo_struct_new TYPE REF TO cl_abap_structdescr.
DATA:
lt_comps TYPE cl_abap_structdescr=>component_table.
FIELD-SYMBOLS:
<fs_comp> LIKE LINE OF lt_comps.
* get description of transparent table (=structure type)
lo_struct ?=
cl_abap_typedescr=>describe_by_name( iv_tabname ).
* get list of components (including component types)
lt_comps = lo_struct->get_components( ).
LOOP AT lt_comps ASSIGNING <fs_comp> .
FIND <fs_comp>-name IN TABLE it_comp_names.
IF sy-subrc <> 0.
DELETE lt_comps.
ENDIF.
ENDLOOP.
* alternatve solution with read table
* remove all components but the requested ones
* LOOP AT lt_comps ASSIGNING <fs_comp> .
*
READ TABLE it_comp_names
*
TRANSPORTING NO FIELDS
*
WITH TABLE KEY table_line = <fs_comp> -name.
*
IF sy-subrc <> 0.
382
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
*
*
*
*
DELETE lt_comps .
ENDIF.
ENDLOOP.
* create new structure type with the remaining components
lo_struct_new = cl_abap_structdescr=>create(
p_components = lt_comps ).
* create table type with this new structure type as line type
ro_tabledescr = cl_abap_tabledescr=>create(
p_line_type = lo_struct_new ).
ENDMETHOD.
Executable Program BC402_DYS_RTTC
REPORT
bc402_dys_rttc MESSAGE-ID bc402.
DATA:
gr_table
TYPE REF TO data.
DATA:
gv_tabname TYPE string.
DATA:
gt_comp_names TYPE string_table,
go_table
TYPE REF TO cl_abap_tabledescr.
FIELD-SYMBOLS:
<fs_table> TYPE ANY TABLE.
SELECTION-SCREEN COMMENT 1(80) text-sel.
PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT 'SPFLI'.
PARAMETERS:
pa_nol
TYPE i DEFAULT '100'.
START-OF-SELECTION.
gv_tabname = pa_tab.
CALL FUNCTION 'BC402_SELECT_COMPONENTS'
EXPORTING
iv_tabname
= gv_tabname
IMPORTING
et_comp_names = gt_comp_names
EXCEPTIONS
type_not_found = 1
no_structure
= 2
no_ddic_type
= 3.
CASE sy-subrc.
WHEN 1.
MESSAGE e050 WITH gv_tabname.
WHEN 2.
MESSAGE e051 WITH gv_tabname.
WHEN 3.
MESSAGE e052 WITH gv_tabname.
ENDCASE.
go_table = cl_bc402_dys_rttc=>create_table_type(
iv_tabname
= gv_tabname
© Copyright. All rights reserved.
383
Unit 5: Dynamic Programming
it_comp_names = gt_comp_names ).
CREATE DATA gr_table TYPE HANDLE go_table.
ASSIGN gr_table->* TO <fs_table>.
TRY.
SELECT (gt_comp_names) FROM (gv_tabname)
INTO TABLE <fs_table>
UP TO pa_nol ROWS.
CATCH cx_sy_dynamic_osql_error.
MESSAGE e061.
ENDTRY.
CALL METHOD
cl_bc402_dys_rtti_headers=>write_headers_by_data
EXPORTING
it_table
= <fs_table>
EXCEPTIONS
no_structure
= 1
no_ddic_type
= 2
component_not_elem = 3.
CASE sy-subrc.
WHEN 1.
MESSAGE e050 WITH gv_tabname.
WHEN 2.
MESSAGE e051 WITH gv_tabname.
WHEN 3.
MESSAGE e053 WITH gv_tabname.
ENDCASE.
cl_bc402_dys_gen_types=>write_any_table( <fs_table> ).
384
© Copyright. All rights reserved.
Lesson: Creating Data Types, Data Objects, and Objects at Runtime
LESSON SUMMARY
You should now be able to:
●
Create objects at runtime
●
Create data objects at runtime
●
Create data types at runtime
© Copyright. All rights reserved.
385
Unit 5: Dynamic Programming
386
© Copyright. All rights reserved.
Unit 5
Learning Assessment
1. Which of the following clauses of a SELECT statement can be supplied dynamically using a
data object?
Choose the correct answers.
X
A FROM clause
X
B WHERE clause
X
C INTO clause
X
D The field list
2. ABAP enables you to call function modules dynamically. To dynamically assign the actual
parameters to the formal parameters in function module calls, we can use the
PARAMETER-TABLE statement.
Determine whether this statement is true or false.
X
True
X
False
3. Which of the following statements creates a program that is saved permanently in the
repository?
Choose the correct answer.
X
A INSERT REPORT
X
B SUBMIT
X
C GENERATE SUBROUTINE POOL
X
D CREATE DATA
© Copyright. All rights reserved.
387
Unit 5: Learning Assessment
4. Which of the following kinds of internal table is the generic type INDEX TABLE compatible
with?
Choose the correct answers.
X
A Standard
X
B Sorted
X
C Hashed
5. Field symbols are pointers that you can assign to data objects dynamically at runtime.
Determine whether this statement is true or false.
X
True
X
False
6. If a field symbol is assigned to a data object, all accesses you make to the field symbol are
made directly to that data object.
Determine whether this statement is true or false.
X
True
X
False
7. What is the variant of the ASSIGN statement that provides access to structure
components dynamically?
Choose the correct answer.
X
A ASSIGN COMPONENT ... TO STRUCTURE ...
X
B ASSIGN COMPONENT ... OF STRUCTURE ...
X
C ASSIGN COMPONENT ... WITH STRUCTURE ...
X
D ASSIGN COMPONENT ... IN STRUCTURE ...
8. When you assign values between two reference variables with different types, you perform
what is called a cast assignment.
Determine whether this statement is true or false.
388
X
True
X
False
© Copyright. All rights reserved.
Unit 5: Learning Assessment
9. Which of the following classes can be instantiated and used to describe specific types?
Choose the correct answers.
X
A CL_ABAP_ELEMDESCR
X
B CL_ABAP_INTFDESCR
X
C CL_ABAP_STRUCTDESCR
X
D CL_ABAP_RTTI
10. The description classes for object types provide navigation methods for determining the
details of a used type.
Determine whether this statement is true or false.
X
True
X
False
11. Class CL_ABAP_CLASSDESCR contains public attributes that are typed as internal tables.
Determine whether this statement is true or false.
X
True
X
False
12. To generate objects at runtime, the static type of the reference variable must be
compatible with the class.
Determine whether this statement is true or false.
X
True
X
False
13. The ___________ statement creates a data object dynamically at runtime.
Choose the correct answer.
X
A CREATE OBJECT
X
B CREATE DATA
X
C ASSIGN
X
D GET REFERENCE OF
© Copyright. All rights reserved.
389
Unit 5: Learning Assessment
14. With the HANDLE addition, the CREATE DATA statement creates a data object whose
data type is described by an RTTI type object.
Determine whether this statement is true or false.
390
X
True
X
False
© Copyright. All rights reserved.
Unit 5
Learning Assessment - Answers
1. Which of the following clauses of a SELECT statement can be supplied dynamically using a
data object?
Choose the correct answers.
X
A FROM clause
X
B WHERE clause
X
C INTO clause
X
D The field list
2. ABAP enables you to call function modules dynamically. To dynamically assign the actual
parameters to the formal parameters in function module calls, we can use the
PARAMETER-TABLE statement.
Determine whether this statement is true or false.
X
True
X
False
3. Which of the following statements creates a program that is saved permanently in the
repository?
Choose the correct answer.
X
A INSERT REPORT
X
B SUBMIT
X
C GENERATE SUBROUTINE POOL
X
D CREATE DATA
© Copyright. All rights reserved.
391
Unit 5: Learning Assessment - Answers
4. Which of the following kinds of internal table is the generic type INDEX TABLE compatible
with?
Choose the correct answers.
X
A Standard
X
B Sorted
X
C Hashed
5. Field symbols are pointers that you can assign to data objects dynamically at runtime.
Determine whether this statement is true or false.
X
True
X
False
6. If a field symbol is assigned to a data object, all accesses you make to the field symbol are
made directly to that data object.
Determine whether this statement is true or false.
X
True
X
False
7. What is the variant of the ASSIGN statement that provides access to structure
components dynamically?
Choose the correct answer.
X
A ASSIGN COMPONENT ... TO STRUCTURE ...
X
B ASSIGN COMPONENT ... OF STRUCTURE ...
X
C ASSIGN COMPONENT ... WITH STRUCTURE ...
X
D ASSIGN COMPONENT ... IN STRUCTURE ...
8. When you assign values between two reference variables with different types, you perform
what is called a cast assignment.
Determine whether this statement is true or false.
392
X
True
X
False
© Copyright. All rights reserved.
Unit 5: Learning Assessment - Answers
9. Which of the following classes can be instantiated and used to describe specific types?
Choose the correct answers.
X
A CL_ABAP_ELEMDESCR
X
B CL_ABAP_INTFDESCR
X
C CL_ABAP_STRUCTDESCR
X
D CL_ABAP_RTTI
10. The description classes for object types provide navigation methods for determining the
details of a used type.
Determine whether this statement is true or false.
X
True
X
False
11. Class CL_ABAP_CLASSDESCR contains public attributes that are typed as internal tables.
Determine whether this statement is true or false.
X
True
X
False
12. To generate objects at runtime, the static type of the reference variable must be
compatible with the class.
Determine whether this statement is true or false.
X
True
X
False
13. The ___________ statement creates a data object dynamically at runtime.
Choose the correct answer.
X
A CREATE OBJECT
X
B CREATE DATA
X
C ASSIGN
X
D GET REFERENCE OF
© Copyright. All rights reserved.
393
Unit 5: Learning Assessment - Answers
14. With the HANDLE addition, the CREATE DATA statement creates a data object whose
data type is described by an RTTI type object.
Determine whether this statement is true or false.
394
X
True
X
False
© Copyright. All rights reserved.
UNIT 6
ABAP Open SQL
Lesson 1
Describing the Technical Background of Database Accesses with Open SQL
397
Lesson 2
Implementing Complex WHERE Conditions and Special INTO Clauses
412
Lesson 3
Processing and Aggregating Datasets on the Database
Exercise 19: Request Ordered and Condensed Datasets from the Database
Exercise 20: Perform Calculations on the Database
421
425
439
Lesson 4
Selecting Data from Multiple Database Tables
Exercise 21: Implement a Join of Multiple Database Tables
445
451
Lesson 5
Explaining Additional Techniques for Reading from Multiple Database Tables
Exercise 22: Implement Full Buffering and Buffering on Demand
Exercise 23: Read Additional Data with the FOR ALL ENTRIES Addition
458
465
475
Lesson 6
Accessing Large Objects (LOBs) on the Database
482
Lesson 7
Using New Open SQL
Exercise 24: Use New Open SQL Syntax and Features
490
497
UNIT OBJECTIVES
●
Explain the architecture of database accesses
●
Explain database indices
© Copyright. All rights reserved.
395
Unit 6: ABAP Open SQL
396
●
Explain SAP table buffering
●
Filter datasets selected from the database using the WHERE clause
●
Use different types of data objects as the target for SELECT statements
●
Read large volumes of data from the database
●
Request ordered or condensed datasets from the database
●
Perform calculations on the database
●
Identify the disadvantages of nested selects
●
Use ABAP joins and database views
●
Explain special techniques for reading from multiple database tables
●
Use explicit buffering techniques
●
Explain streams and locators
●
Use the new Open SQL syntax
© Copyright. All rights reserved.
Unit 6
Lesson 1
Describing the Technical Background of
Database Accesses with Open SQL
LESSON OVERVIEW
This lesson provides an overview of the system architecture and process flows involved in
database accesses with Open SQL. You will learn about secondary indexes and the optimizer
function in the database, as well as their importance in efficient data access. The lesson also
explains what the database interface does and how SAP table buffering is used to reduce the
load on the database and speed up access to frequently required data.
Business Example
You want to implement database accesses with Open SQL in your applications. These
database accesses must be sophisticated and efficient. Therefore, you want to learn about
the details of the system architecture and the process flows involved in database accesses.
For this reason, you require the following knowledge:
●
An understanding of the relevant system components related to Open SQL
●
An understanding of the process flows involved in a database access using Open SQL
●
An understanding of the terms database interface, SAP table buffer, database buffer,
cursor cache, database index, and optimize
●
An understanding of the importance of the SAP database interface
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain the architecture of database accesses
●
Explain database indices
●
Explain SAP table buffering
© Copyright. All rights reserved.
397
Unit 6: ABAP Open SQL
Overview of Database Accesses
Figure 174: Architecture of the SAP NetWeaver Application Server (ABAP)
The SAP system is implemented as a multitier client/server architecture (presentation layer,
application layer, and database layer). Data transport between the application layer and the
database is the responsibility of the SAP database interface (DBSS). The SAP database
interface accepts the SQL statements that the ABAP applications send in dialog work
processes (Dia-WP), retrieves the requested data, and makes it available to the application
program. The application program can contain statements in either ABAP Open SQL or native
SQL (SQL of the underlying database). Accordingly, the DBSS is divided into an ABAP Open
SQL interface and a native SQL interface.
Tasks of the ABAP Open SQL interface are as follows:
●
Translating ABAP Open SQL to native SQL
●
Client handling, including the client in the WHERE condition
●
Managing the SAP table buffer
When managing the SAP table buffer, the system buffers frequently required data
automatically in the working memory of the application server so that it does not have to be
read from the database each time.
The database contains several database work processes (DB-Wp or “shadow processes”)
that handle the requests from the SAP application servers. The system assigns each work
process on the application server side to exactly one work process in the database.
398
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
Data Transport
Figure 175: Database Architecture and Data Transport
The system stores the data in the file system of the database server and loads it from the file
system to the DB work processes when it receives requests from the database service
processes. Because the operation takes a long time, a database cache (DB buffer in the figure
Database Architecture and Data Transport) is available for storing frequently used data. The
system accesses the data in this buffer more quickly than it is retrieved from the database
server.
Apart from the database buffer, the database allocates another shared memory area, the DB
cursor cache (database access paths), which contains the redo log and other information.
Hint:
ABAP developers have no influence on the buffering mechanisms within the DB
server. ABAP developers use settings in the ABAP Dictionary to define which
tables can be stored in the SAP table buffer in the Application Server layer.
In addition to the database work processes, other database services are available for various
purposes such as starting communications, changing database tables, locking mechanisms,
and archiving.
Database Optimizer
When processing a specific database access, it is important that the database determine the
addressed records and provide them to the DB-Wp quickly. The database manages one or
more indexes for each database table in addition to its actual contents. An index consists of
© Copyright. All rights reserved.
399
Unit 6: ABAP Open SQL
selected fields of the database table that are stored in the database copy as a sorted table.
These fields refer to the actual table lines.
When a table is accessed, the database determines whether to access the contents of the
database table directly, or read an index first and then determine the actual data through the
references in the index or a combination of multiple indexes. A variety of factors influences
the speed of data delivery for specific SQL statements. The database feature that weighs all
these factors and determines the access strategy (and thus whether indexes are used) is
called an optimizer.
Database Optimizer – Overview
Figure 176: Database Optimizer
A database optimizer is a database feature that analyzes an SQL statement and then
determines an access strategy based on the WHERE condition and the structure of the
existing indexes. It is the database optimizer that determines whether one of the existing
indexes is used, and if so, which one.
Even if all of the fields in an index are valuated, it is not certain that the optimizer will select
that index. There is always a chance, for example, that the optimizer will select a sequential
search of the entire table contents instead.
Distinguishing between the Two Groups of Optimizers
You can distinguish two groups of optimizers by the way they work as follows:
400
●
A rule-based optimizer analyzes the structure of an SQL statement (mainly the SELECT
and WHERE conditions without values), and the index structure of the table or tables. The
optimizer then uses a set of analysis rules to determine the most appropriate procedure
for executing the statement. The specific contents of the table are irrelevant.
●
A cost-based optimizer analyzes values in the WHERE condition 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 produce faster access to the data. One of the disadvantages of cost-based
optimizers is that the statistics must be updated periodically.
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
Database Index Definition
Figure 177: Index Tree
When you create a database table in the ABAP dictionary, you specify the combination of
fields that uniquely identify an entry within the table. These are called key fields or primary
keys, and you place them at the start of the table. In most database systems, the key fields
are used to create an index in addition to the table. This index is called the primary index, and
is unique.
Note:
In contrast to other database systems, the primary index and the actual table data
are a single unit on Microsoft SQL Server. Therefore, it is not possible to access
the data without using the primary index in this database.
In addition to the primary index, you can define one or more secondary indexes for a table in
the ABAP dictionary and save them in the database. Secondary indexes are either unique or
non-unique.
Data Blocks
Both index records and table records are organized in data blocks. When an ABAP program
sends an SQL statement to the database, the system searches the requested data records
either in the database table directly by using a full table scan or with the assistance of an
index, by using an index unique scan or an index range scan. If the index contains all the
requested fields, the table itself does not need to be accessed.
Data blocks are either index blocks or table blocks. They represent the granularity with which
data can be written to or read from the hard drive. Data blocks can contain several data
records, or one data record can stretch over several data blocks.
© Copyright. All rights reserved.
401
Unit 6: ABAP Open SQL
The root level contains a single index block with pointers to the index blocks at branch level.
The branch blocks either contain part of the index fields and pointers to the index blocks at
leaf level, or all the index fields and a pointer to the table records organized in the table blocks.
The index blocks at leaf level contain all index fields and pointers to the table records from the
table blocks.
Note:
The expression ROWID for the pointer is specific to Oracle databases.
The system saves the index records in the index tree and sorts the records by index field. This
process makes index-based access faster. The table records in the table blocks are not
sorted.
Hint:
To reduce the amount of storage space that an index requires, the index must
not consist of too many fields. Using just a few carefully selected fields promotes
reusability and reduces the possibility of the database optimizer selecting a
processing-intensive access path.
Database Index Usage
Figure 178: Index Search String (1)
If you want a rough estimate of how useful an index is for a specific SELECT statement, look at
the index search string for this statement. The index search string is formed from the WHERE
condition. The system concatenates the desired values of the fields contained in the index.
402
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
The longer the search string is, starting from the left, without placeholders ("_" or "%"), the
more efficient the access through this index.
In the example, all three fields of the primary index, that is, MANDT, CARRID, and CONNID of
table SFLIGHT are evaluated in the WHERE condition (the client is set automatically by the
DBSS). FLDATE, which is the last field of the index, is not qualified. Therefore, the search
string for the database is 802AA0017%. Starting from the left, there are no gaps in the search
string until the last field. As a result, the database requires relatively little effort to search the
index tree and can return the result set quickly.
Index Search String (2)
Figure 179: Index Search String (2)
In the example, the CARRID and CONNID fields are missing in the WHERE condition. The
corresponding positions for the two fields are set to "_" in the index search string. Therefore,
the fully specified area that is used to select the index blocks only consists of the MANDT
field. Because multiple index records fulfill the condition MANDT = "802", the system has to
read multiple index blocks and check their index records. The system filters the index records
that fulfill the condition FLDATE="20051201".
Hint:
Qualify (fill with values) as many index fields as possible, from left to right, and do
not leave any gaps in the index search string. Ultimately, the application logic
determines how the SELECT statement is coded, possibly justifying the example
above.
© Copyright. All rights reserved.
403
Unit 6: ABAP Open SQL
Reducing the Search Effort
Figure 180: Reducing the Search Effort
The more index fields are qualified or assigned values from left to right, the smaller the search
effort required by the database to make to determine the hit list. Using the CARRID, CONNID,
and SEATSOCC fields in the WHERE condition to access table SFLIGHT results in a primary
index access. In this primary index access, the first three index fields, including the client, are
used. Because the SEATSOCC field is also specified, the exact records are read from the hit
list and transferred to the application server. In this example, the search delivers excellent
performance, transferring exactly the records that the application needs.
404
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
SAP Table Buffering
Figure 181: Table Buffering – Overview
The SAP table buffer is a memory area in the shared memory of the active application server.
You can store table contents in it as needed to avoid database accesses and conserve
database resources such as CPU load and main memory.
Reducing the database load is important because the database server is a central resource. In
addition, accesses to the SAP table buffer are much faster than database accesses. If data is
available in the database buffers on the SAP application servers, retrieval takes around 0.1
milliseconds (ms) per record. When the system reads the records from the database data
buffer, approximately 1 ms per record is needed. If the system needs to read the data from
the DB disk, approximately 10 ms per record is needed. This means that the records that are
buffered on the application server can be accessed up to 100 times faster than data in the
database. As a result, the work processes on the application server encounter shorter wait
times.
Whether, and how, the database table is buffered is determined when the database table is
defined.
The database interface controls the filling and reading of the buffer at runtime, and is usually
effective during access using Open SQL statements. However, it can be bypassed by certain
variants (see performance aspects of Open SQL).
© Copyright. All rights reserved.
405
Unit 6: ABAP Open SQL
Buffering Types
Figure 182: Buffering Types
When you define a database table in the ABAP dictionary, you can allow, forbid, or require
table buffering in the technical settings.
You can differentiate between the single record buffer (technically TABLP), the generic table
buffer (technically TABL), and the buffer for complete tables (full table buffering). The single
record buffer contains the records from the single record-buffered tables. Physically, the
generic table buffer contains the records of the generically and fully buffered tables.
Technically, both of these buffering types use the same memory area on the application
server.
Buffering Types – Overview
If buffering is allowed, it takes place according to one of the following buffering types:
●
Full buffering
The first time the table is accessed, the entire table is loaded into the table buffer (generic
table buffer). All subsequent accesses of the table are served from the table buffer.
●
Generic buffering
If you want to buffer a table generically, you need to define the generic area first. The
generic area consists of the first n key fields of the table. If an SQL statement is executed
with a specific instantiation of the generic area (such as SELECT * FROM TAB1 WHERE
KEY1 = ‘002’ or SELECT * FROM TAB2 WHERE KEY1 = ‘002’ AND KEY2 = ‘A’)
for a generically buffered table, the corresponding records are loaded into the table buffer.
406
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
All subsequent accesses with the same instantiation (and, potentially with additional fields
that are not part of the generic area) can be served from the table buffer.
●
Single record buffering
Only single records are read from the database and loaded into the table buffer (single
record buffer).
Note:
The single record buffer is only read if the SELECT SINGLE statement is used.
The WHERE clause has to contain restrictions for all key fields. Restrictions for
non-key fields may be added.
Each buffering type can be considered to be a variant of generic buffering with n key fields as
follows:
●
Full buffering
n=0
●
Generic buffering
0 < n < number of key fields
●
Single record buffering
n = number of key fields
Buffer Synchronization
Figure 183: Buffer Synchronization
© Copyright. All rights reserved.
407
Unit 6: ABAP Open SQL
Buffer synchronization is a mechanism that the application servers in a system use to ensure
that obsolete data is removed from the table buffers when data in a buffered table is changed.
The buffer is synchronized at fixed intervals that you can configure in the system profile.
Hint:
The system parameter for the synchronization interval is rdisp/bufreftime, which
specifies the length of the interval in seconds. The value is between 60 and 3600.
A value between 60 and 240 is recommended.
Steps to Buffer Synchronization
When a database write operation is applied to a buffered table, the following steps occur:
●
The corresponding records are changed in the database. In the table buffer of the local
SAP instance (application server A), they are invalidated or changed.
●
The local database interface (application server A) propagates the changes to the other
application servers by writing an appropriate entry to database table DDLOG. The
database buffers of the other SAP instances are not yet current.
●
The database interfaces of the SAP instances start buffer synchronization. The frequency
of this synchronization (typically every one to two minutes) is controlled by profile
parameters. Within synchronization, a SELECT statement is sent to table DDLOG. If the
returned records in table DDLOG indicate that change access has been made to buffered
tables, the data in the table buffers of the non-local SAP instances is invalidated according
to the buffering type. Subsequent SQL statements requesting invalidated data are thus
served by the database instead.
Note:
Once the system invalidates data in the buffer, it waits for a certain number of
read accesses (controlled by a profile parameter) before the data is stored in the
buffer again. This is done to prevent fast invalidation and buffering of data.
Caution:
SAP table buffering does not synchronize until after the synchronization interval
passes; therefore, temporary data inconsistencies can occur. Buffer data only if
reading obsolete data within this limit can be tolerated.
Invalidation Granularity
Invalidating Buffered Records During Buffer Synchronization
●
Single record processing (when a single record in a buffered table is changed)
●
Mass processing (when several records in a buffered table are changed)
All data records, regardless of buffering type
408
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
Table 12: Single Record Processing
Single record processing (when a single record in a buffered table is changed) has the
following characteristics:
Buffering Type
Coverage
Full buffering
All records
Generic buffering
Generic area
Single record buffering
Current record
SAP buffer contents are invalidated during buffer synchronization.
The scope to which data is invalidated depends on the type of access, in addition to the
buffering type. The access types are as follows:
●
Work area mode (single record access)
In work area mode, only a single record is changed, deleted, or inserted. This is done with
the ABAP statements UPDATE/INSERT/MODIFY/DELETE dbtab (FROM wa) or
INSERT dbtab VALUES wa.
●
Set mode (mass access)
In set mode, several data records are changed, deleted, or inserted with a single database
access. Database update access as mass processing is formulated in ABAP with the
statements UPDATE/INSERT/MODIFY/DELETE dbtab FROM itab, UPDATE dbtab
SET <field> = <value> WHERE <field> = <condition>, or DELETE dbtab
WHERE <field> = <condition> .
Database update accesses generally invalidate all the records in fully buffered tables.
For generically buffered tables in work area mode, records are invalidated for which the
generic area has the same expression as the work area fields in the SQL update statement. If
a generically buffered table is accessed in set mode, all the records are invalidated.
If a single-record-buffered-record is accessed in work area mode, only the changed single
record is invalidated. If an update access is performed in set mode, the entire single-recordbuffered table is invalidated.
Note:
The granularity of the invalidation corresponds to the granularity used to fill the
table buffers.
Criteria for Table Buffering
Using Table Buffering
●
Do not buffer transaction data. There is a large amount of data and it changes too often.
●
Generally avoid buffering master data. There is a large amount and has too many access
paths.
●
Generally it is ok to buffer customizing data. It is small and has few changes.
© Copyright. All rights reserved.
409
Unit 6: ABAP Open SQL
The Criteria for Buffering
●
Small tables that have <10 MB
●
Frequently read, few changes
●
Temporary inconsistency acceptable
●
Accessed primarily using key fields
●
Memory must be checked by the system administrator before buffering additional tables
The records of the buffered tables are held redundantly in the shared memory of the
participating application servers. You should only buffer tables that are relatively small.
Tables that are larger than 10 MB should only be buffered in exceptional cases. To keep the
number of invalidations and subsequent buffer load operations small, buffer those tables that
are accessed primarily for read access (change accesses less than 1% of read accesses).
Immediately after a change access to a buffered table, the table buffers of the non-local SAP
instances are no longer current. Inconsistent data can be read during this period, so only
buffer tables where this is acceptable. The records of buffered tables are sorted and saved by
the primary key. Accordingly, use key fields to access them. You cannot use secondary
indexes to access the records of buffered tables.
Before you decide to buffer tables, consult your system administrator to make sure that
sufficient space is available in shared memory (single record buffer needs approximately 40
MB and generic table buffer needs approximately 80 MB). Otherwise, the table buffers
overwrite each other. Before you change the buffer settings for standard SAP tables, search
for appropriate SAP Notes in the SAP Notes system. You need a modification key to perform
the changes.
Proper Access to Buffered Database Tables
To benefit from SAP table buffering when accessing a buffered database table, the SELECT
statement needs to meet certain conditions. Only then is the data stored in the buffer or
retrieved from it.
Access to Buffered Database Tables
●
Single record buffering
Buffer only used for SELECT SINGLE ... with fully qualified key
●
Generic buffering
Buffer only used if first n key fields are restricted to exactly one value
●
All buffering types
Buffer only used if no additions are used that have to be processed by the database
If these conditions are not met, the SELECT statement will bypass the buffer.
Note:
With the release of SAP NetWeaver 7.0 Enhancement Package 2, you do not need
to access single record buffered tables with the SELECT SINGLE statement. As
long as the key is fully qualified in the WHERE condition, the buffer is also used in
an array fetch or SELECT loop.
410
© Copyright. All rights reserved.
Lesson: Describing the Technical Background of Database Accesses with Open SQL
Hint:
There is a dedicated check in the Code Inspector tool that helps you to identify
SELECT statements that bypass the SAP table buffer.
LESSON SUMMARY
You should now be able to:
●
Explain the architecture of database accesses
●
Explain database indices
●
Explain SAP table buffering
© Copyright. All rights reserved.
411
Unit 6
Lesson 2
Implementing Complex WHERE Conditions and
Special INTO Clauses
LESSON OVERVIEW
This lesson explains the logical expressions that are used in WHERE conditions of Open SQL
statements. It also discusses a variety of other operators apart from simple value
comparisons with = and EQ.
Business Example
You want to implement database accesses with Open SQL in your applications. These
database accesses must be sophisticated and efficient. Therefore, you need to find out about
the special options of using logical expressions in the WHERE condition and specifying data
objects in INTO clauses. For this reason, you require the following knowledge:
●
An understanding of the importance of the possible operators in WHERE conditions
●
An understanding of how to use the different operators correctly
●
An understanding of the options available for specifying data objects after INTO
●
An understanding of how to implement sequential processing of large data volumes
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Filter datasets selected from the database using the WHERE clause
●
Use different types of data objects as the target for SELECT statements
●
Read large volumes of data from the database
Operators in WHERE Conditions
When formulating WHERE conditions, you should be familiar with comparing single values
and evaluating select options. The comparison values here are data objects (variables and
literals). However, Open SQL also supports a variety of operators and enables you to compare
database table fields with one another.
Table 13: Possible Operators that can be Used in WHERE Conditions
Possible operators that can be used in WHERE conditions are listed in the following table:
412
Operator
Meaning and Use
=, <, >, <=, <=, <>
Comparison with a single value
EQ, LT, GT, LE, GE, NE
In character-type fields, the result of size
comparisons may depend on the database
code page.
© Copyright. All rights reserved.
Lesson: Implementing Complex WHERE Conditions and Special INTO Clauses
Operator
Meaning and Use
IN (dobj1, dobj2, ...)
Comparison with a list of single values
BETWEEN dobj1 AND
Comparison with an interval
dobj2
In character-type fields, the result may depend on the database code page.
LIKE dobj
Comparison with character strings
The _ and % placeholders let you define a
comparison pattern in DOBJ.
IN seltab
Evaluation of a selection table (select-options)
IS [NOT] NULL
Checks whether the database field has a null
value
AND, OR
Link of logical expressions
NOT
Negation of a logical expression
Note:
Some of the operators can have a negative impact on performance if the
operators use potential index fields for delimitation because the database
optimizer does not find an efficient access strategy.
© Copyright. All rights reserved.
413
Unit 6: ABAP Open SQL
Operators in WHERE Conditions (2)
Figure 184: Operators in WHERE Conditions
The figure Operators in WHERE Conditions illustrates an example of a complex search for
airline customers using name and address data.
Hint:
The “_” and “%” placeholders correspond to the SQL standard in delimitation
with LIKE. In other ABAP statements, the “+” and “*” characters are used for
similar comparisons, for example, within comparison tables.
To search for the “_” or “%” characters, use the ESCAPE addition to define an
escape symbol. A condition that the column contents must contain a “_” in any
location is then formulated as LIKE '%! _%' ESCAPE '!'.
When the developer links conditions, the AND operators are evaluated before the OR
operators. Use parentheses to change this order as needed.
Note:
The selection of the operator can have a major impact on the usability of a
condition for an index search string. The formulation of the WHERE condition
influences the search strategy of the optimizer and the performance of the
database access.
414
© Copyright. All rights reserved.
Lesson: Implementing Complex WHERE Conditions and Special INTO Clauses
Table Field Comparison
Figure 185: Comparing Table Fields
In addition to variables and constants, you can also use fields from the same database tables
after the comparison operators (for example, =, EQ, <>, NE, <, LT) in the WHERE conditions
of open SQL statements. Entering fields from the same database tables after the comparison
operators makes it possible to compare two database fields with each other in the WHERE
condition and only read the records whose contents fulfill the condition.
To avoid the confusion of the second table field with a data object, the name of the database
table must be specified with the field name connected with the “~” character. Alternatively,
use an alias for the table name, which you can define with the AS addition after the table name
in the FROM clause.
Note:
Aliases for table names play a subordinate role here. They are used to abbreviate
the WHERE condition. However, you see aliases again in the formulation of joins,
where they are crucial if the same database table appears several times in the
FROM clause.
Caution:
The fields that are compared must have the same basic type and length (ideally,
they are based on the same domain). Otherwise, the result depends on how the
respective database system stores the different types and how it handles spaces
at the end of values.
© Copyright. All rights reserved.
415
Unit 6: ABAP Open SQL
Target Areas for INTO Clause
When you specify data objects as targets of SELECT statements, you need to differentiate
whether the target area that is specified after INTO is single line or multiline.
Table 14: Single Line and Multiline Result Sets
Do not confuse this with single line and multiline result sets, as listed in the following table:
Statement
Result-Set
Target Area
SELECT SINGLE…
single-line
single-line
SELECT… INTO TABLE…
multiline
multiline
SELECT… ENDSELECT.
multiline
single-line
Single Line Target Area
Figure 186: List of Data Objects Instead of Single Structure
Single line target areas are used for single record access using SELECT SINGLE and in select
loops using SELECT ... ENDSELECT. The target may be a structure (structured data object),
and is always specified with the INTO addition (without TABLE) or with INTO
CORRESPONDING FIELDS OF. You can also specify a list of elementary data objects or
elementary structure components. In this case, the individual fields are separated by
commas, while the entire list is enclosed in parentheses.
416
© Copyright. All rights reserved.
Lesson: Implementing Complex WHERE Conditions and Special INTO Clauses
Hint:
The syntax is correct only if there are no spaces between the open parentheses
and the first data object. Any number of spaces can appear before the closing
parentheses, before and after commas, but are not required.
Specifying individual structure components is a more robust alternative to specifying the
entire structure after the CORRESPONDING FIELDS OF addition. In theory, you can also
specify a list of individual data objects and structure components after INTO
CORRESPONDING FIELDS OF.
Multiline Target Area
Figure 187: APPENDING Instead of INTO
When SELECT statements have multiline target areas, you must specify an internal table as
the data object. Specify the table, for example, after the INTO TABLE addition or after INTO
CORRESPONDING FIELDS OF TABLE.
Alternatively, replace INTO TABLE and INTO CORRESPONDING FIELDS OF TABLE with
APPENDING TABLE and APPENDING CORRESPONDING FIELDS OF TABLE, respectively. If
you use INTO, the contents of the internal table are replaced completely with the selected
data. If you use APPEND, the data is added to any existing lines in the table.
© Copyright. All rights reserved.
417
Unit 6: ABAP Open SQL
Hint:
If you use APPENDING for sorted and hashed tables, no append is performed.
Specifically, the addition is not treated as an index access to the internal table,
which means it can also be used for hashed tables. In sorted tables, the new lines
are inserted at the correct position in accordance with the sort sequence.
Explicit Package Size
Figure 188: PACKAGE SIZE Addition
When you process multiline result sets, SAP recommends reading them into an internal table
(array fetch). However, if large result sets are involved, the program can terminate because
the available working memory is insufficient for an internal table of that size.
One solution to this is sequential processing in a SELECT loop. This approach has low
memory requirements because only one record is transported to the working memory at any
one time.
Note:
The database interface reads entire packages from the database but then copies
the records to the work area individually. When a package is processed
completely, the next one is requested from the database. As a result, the
application server never transports the entire data volume at once.
A disadvantage of sequential processing in the SELECT loop is the fact that only one record is
available to the application at a time. The availability of a record is particularly problematic
when you want to change the records in the database because the changes can only be
418
© Copyright. All rights reserved.
Lesson: Implementing Complex WHERE Conditions and Special INTO Clauses
carried out by single record access. However, a large number of single record write accesses
have a negative impact on the database and program performance.
For such cases, Open SQL provides a variant of the SELECT statement in which the data is
processed in a loop (SELECT ... ENDSELECT) but the target area is multiline (INTO TABLE).
The number of records that are placed in the internal table at the same time and processed in
the current loop pass is defined with the PACKAGE SIZE addition. You can specify this
number either statically or dynamically, but it is defined once at the start of the loop. The
same number of lines are processed during each loop pass.
Hint:
The value after PACKAGE SIZE determines the number of lines that the database
interface provides to the application program in each loop pass. It has no major
impact on the size of the packages that are transferred from the database to the
application server.
Explicit Cursor
Figure 189: OPEN CURSOR ... FETCH ... CLOSE CURSOR
Packages of different sizes can be processed sequentially with the syntax illustrated in the
figure OPEN CURSOR ... FETCH ... CLOSE CURSOR.
In this variant of database read access, the access itself is detached from the transfer of the
result set to the application program.
The OPEN CURSOR statement defines and executes the access, but does not pass any data
on to the application program.
© Copyright. All rights reserved.
419
Unit 6: ABAP Open SQL
The FETCH NEXT CURSOR statement retrieves the desired number of lines (PACKAGE SIZE
addition) from the result set and copies them to an internal table.
The CLOSE CURSOR statement completes the database access.
The importance of the cursor variable, which is a variable with a special CURSOR type, is
highlighted as follows:
●
The cursor variable identifies the database access in the subsequent statements.
●
The cursor variable stores the position in the result set of the database access up to which
processing is already complete.
After OPEN CURSOR, the cursor variable points to a position before the first line.
The sequential FETCH statements not only allow you to read different numbers of records,
but also allow you to specify a different data object as the target (structures or internal
tables) after each INTO.
Hint:
You can also keep a limited number of accesses open at the same time, for
example, to process several database tables in parallel.
Caution:
The cursor is closed implicitly by a database commit or database rollback.
Therefore, no statements that cause an implicit DB commit or DB rollback can
appear between OPEN CURSOR and CLOSE CURSOR. When a FETCH statement
is performed for a cursor that has already been closed, a catchable exception is
raised (exception class CX_SY_OPEN_SQL_DB).
LESSON SUMMARY
You should now be able to:
420
●
Filter datasets selected from the database using the WHERE clause
●
Use different types of data objects as the target for SELECT statements
●
Read large volumes of data from the database
© Copyright. All rights reserved.
Unit 6
Lesson 3
Processing and Aggregating Datasets on the
Database
LESSON OVERVIEW
This lesson discusses several additions for the SELECT statement with which you can instruct
the database to sort the desired data before it is transferred, aggregated, or used to perform
calculations.
Business Example
You want to implement database access with Open SQL in your applications. You want the
data access of your application to be efficient and effective.
Therefore, you need to learn about the options and functions for sorting and aggregating
data.
For this reason, you require the following knowledge:
●
An understanding of how to request sorted or aggregated data from the database
●
An understanding of how to use aggregate functions correctly
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Request ordered or condensed datasets from the database
●
Perform calculations on the database
© Copyright. All rights reserved.
421
Unit 6: ABAP Open SQL
Ordered Datasets
Figure 190: ORDER BY Addition Variants
In Open SQL, you can have the database sort the dataset by specific criteria directly as part of
the SELECT operation. To do so, use the ORDER BY clause for the SELECT statement.
In the simplest form of the ORDER BY PRIMARY KEY clause, the table is sorted by its
complete primary key in ascending order.
To use ORDER BY PRIMARY KEY, the prerequisites are as follows:
●
The FROM clause contains a single database table (no views or joins).
●
The field list after SELECT contains all the table’s key fields (including the client, which is
often forgotten).
The syntax ORDER BY COL1, COL2 … sorts the data by any existing columns. The sequence of
the specified columns determines their sort priority.
The restrictions on ORDER BY are as follows:
422
●
You cannot sort pooled tables and cluster tables simply by any field.
●
You can only sort by columns that appear after the SELECT statement, which means the
sort columns must be a part of the result set.
●
You cannot sort by fields with type LCHAR, LRAW, STRING, or RAWSTRING.
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
ORDER BY Addition
Figure 191: ORDER BY Addition
The figure ORDER BY Addition shows an example of the ORDER BY addition with free column
selection.
If you do not use an addition, the system sorts retrieved datasets in ascending order. You can
use the optional DESCENDING and ASCENDING clauses after a given field to define the sort
direction.
Note:
Sorting can be a computationally expensive process if the result set is large and
the sort fields are not also index fields.
© Copyright. All rights reserved.
423
Unit 6: ABAP Open SQL
Condensed Datasets
Figure 192: SELECT DISTINCT Statement
The SELECT DISTINCT statement in Open SQL instructs the database to aggregate the result
set of a SELECT statement such that it does not contain any duplicate entries. All fields of the
result set are used for the comparison. You can either load the result of SELECT DISTINCT
into an internal table (array fetch) or process it sequentially (SELECT loop).
For SELECT DISTINCT, the applicable restrictions are as follows:
424
●
The field list cannot contain any columns with type LCHAR, LRAW, STRING, or
RAWSTRING.
●
You must use SELECT DISTINCT * to access pooled tables and cluster tables. You cannot
select individual columns.
© Copyright. All rights reserved.
Unit 6
Exercise 19
Request Ordered and Condensed Datasets
from the Database
Business Example
You want to enhance a program that outputs a customer's flight bookings, so that the travel
agencies which made the bookings are displayed.
Template
BC402_DBT_SQL_DISTINCT
Solution
BC402_DBS_SQL_DISTINCT
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy the template BC402_DBT_SQL_DISTINCT to ZBC402_##_DISTINCT. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test your program.
3. Which input options are available on the selection screen?
4. Which data is output in the list? Which missing data do you still need?
Implement Subroutine GET_TRAVELAGS
Implement subroutine GET_TRAVELAGS to determine the travel agencies that made the
bookings. Make sure that each travel agency appears only once and that travel agencies are
sorted alphabetically by name. Implement a single database access that returns the data
completely in the desired form. Read from database view BC402_SCUS_BOOK.
© Copyright. All rights reserved.
425
Unit 6: ABAP Open SQL
1. Analyze the interface of the subroutine, particularly the typing of the parameters. Which
components are contained in the line type of CT_TRAVELAGS?
2. Implement a SELECT statement to fill CT_TRAVELAGS with the data for the travel
agencies. Access database view BC402_SCUS_BOOK and select data based on the
customer number.
3. Supplement the SELECT statement with a clause that removes repeated entries from the
result set.
4. Supplement the SELECT statement with a clause that returns the result set sorted by
travel agency name.
5. Activate and test your program.
426
© Copyright. All rights reserved.
Unit 6
Solution 19
Request Ordered and Condensed Datasets
from the Database
Business Example
You want to enhance a program that outputs a customer's flight bookings, so that the travel
agencies which made the bookings are displayed.
Template
BC402_DBT_SQL_DISTINCT
Solution
BC402_DBS_SQL_DISTINCT
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy the template BC402_DBT_SQL_DISTINCT to ZBC402_##_DISTINCT. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DBT_SQL_DISTINCT.
c) Choose Display.
d) Right-click BC402_DBT_SQL_DISTINCTand choose Copy....
e) In the Copy Program BC402_DBT_SQL_DISTINCTdialog box, in the Target program
field, enter ZBC402_##_DISTINCT and choose Copy.
f) In the Copy Program BC402_DBT_SQL_DISTINCT to ZBC402_##_DISTINCTdialog
box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test your program.
a) Choose the Activate button.
b) Choose the Direct Processingbutton.
© Copyright. All rights reserved.
427
Unit 6: ABAP Open SQL
3. Which input options are available on the selection screen?
An airline customer number.
4. Which data is output in the list? Which missing data do you still need?
Data output is the customer’s name, form of address, and a list of all the customer’s
bookings (without cancellations). Still missing are a list of total bookings (separated by
currency) and a list of travel agencies who made the bookings.
Implement Subroutine GET_TRAVELAGS
Implement subroutine GET_TRAVELAGS to determine the travel agencies that made the
bookings. Make sure that each travel agency appears only once and that travel agencies are
sorted alphabetically by name. Implement a single database access that returns the data
completely in the desired form. Read from database view BC402_SCUS_BOOK.
1. Analyze the interface of the subroutine, particularly the typing of the parameters. Which
components are contained in the line type of CT_TRAVELAGS?
AGENCYNUM: Travel agency number, NAME: Travel agency name, CITY: City.
2. Implement a SELECT statement to fill CT_TRAVELAGS with the data for the travel
agencies. Access database view BC402_SCUS_BOOK and select data based on the
customer number.
a) See the source code excerpt from the model solution.
3. Supplement the SELECT statement with a clause that removes repeated entries from the
result set.
a) DISTINCT clause. See the source code excerpt from the model solution.
4. Supplement the SELECT statement with a clause that returns the result set sorted by
travel agency name.
a) ORDER BY clause. See the source code excerpt from the model solution.
5. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_dbs_sql_distinct.
TYPES: BEGIN OF gty_s_travelags,
agencynum TYPE bc402_scus_book-agencynum,
name
TYPE bc402_scus_book-name,
city
TYPE bc402_scus_book-city,
END OF gty_s_travelags.
TYPES:
428
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
gty_t_bookings
TYPE STANDARD TABLE OF scus_book
WITH NON-UNIQUE KEY
carrid connid fldate bookid,
gty_t_travelags TYPE STANDARD TABLE OF gty_s_travelags
WITH NON-UNIQUE KEY agencynum.
DATA:
gs_customer TYPE scustom,
gt_bookings TYPE gty_t_bookings,
gt_travelags TYPE gty_t_travelags.
PARAMETERS:
pa_cust TYPE sbook-customid DEFAULT '00000001'.
START-OF-SELECTION.
SELECT SINGLE * FROM scustom INTO gs_customer
WHERE id = pa_cust.
SELECT * FROM scus_book
INTO TABLE gt_bookings
WHERE customid = pa_cust
AND cancelled <> 'X'.
PERFORM get_travelags USING
pa_cust
CHANGING gt_travelags.
PERFORM output_list USING gs_customer
gt_bookings
gt_travelags.
*&---------------------------------------------*
*&
Form GET_TRAVELAGS
*&---------------------------------------------*
FORM get_travelags USING
pv_customid TYPE sbook-customid
CHANGING ct_travelags TYPE gty_t_travelags.
SELECT DISTINCT agencynum name city
FROM bc402_scus_book
INTO TABLE ct_travelags
WHERE customid = pv_customid
ORDER BY name.
ENDFORM.
" GET_TRAVELAGS
*&--------------------------------------------*
*&
Form OUTPUT_LIST
*&--------------------------------------------*
FORM output_list USING ps_customer TYPE scustom
pt_bookings TYPE gty_t_bookings
pt_travelags TYPE gty_t_travelags.
DATA:
ls_bookings LIKE LINE OF pt_bookings,
ls_travelags LIKE LINE OF pt_travelags.
DATA lv_text TYPE string.
CONCATENATE text-wcm
ps_customer-form
ps_customer-name
INTO lv_text
© Copyright. All rights reserved.
429
Unit 6: ABAP Open SQL
SEPARATED BY space.
CONDENSE lv_text.
WRITE: / lv_text.
SKIP.
WRITE / text-lob.
ULINE.
SKIP.
LOOP AT pt_bookings INTO ls_bookings.
WRITE: /
ls_bookings-bookid,
ls_bookings-carrid RIGHT-JUSTIFIED,
ls_bookings-connid,
ls_bookings-fldate,
ls_bookings-cityfrom RIGHT-JUSTIFIED,
'->',
ls_bookings-cityto.
ENDLOOP.
SKIP 2.
WRITE / text-tag.
ULINE.
SKIP.
LOOP AT pt_travelags INTO ls_travelags.
WRITE: /
ls_travelags-name,
ls_travelags-city.
ENDLOOP.
ENDFORM.
430
" OUTPUT_LIST
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
Aggregate Expressions
An aggregate expression uses an aggregate function to perform calculations on a specified
column in the SELECT statement. Aggregate expressions determine values from multiple
rows in a column of a database table. The calculation is performed in the database system.
Table 15: Aggregate Functions Supported by ABAP Open SQL
The aggregate functions supported by ABAP Open SQL are as follows:
Function
Meaning of Result and Condi-Data Type of Result
tions
MIN( col )
Minimum value in the col column within the result set
MAX( col )
Maximum value in the col col- Like the col column
umn within the result set
SUM( col )
Sum of the contents of the
col column in the result setcol column must be numeric
Like the col column
AVG( col )
Average (arithmetic mean)
value of the contents of the
col column in the result setcol column must be numeric
Float (F)
COUNT( * )
Number of lines in the result
set
Integer (I)
Like the col column
When an INTO clause is used with aggregate expressions, the data object in the INTO clause
must provide a structure component or table column with the appropriate type for each
aggregate expression in the SELECT statement.
When aggregate functions are used, there is a major difference between cases in which the
field list consists exclusively of aggregate expressions, and cases in which the field list also
contains fields that are not arguments to an aggregate function.
© Copyright. All rights reserved.
431
Unit 6: ABAP Open SQL
Field Lists Only with Aggregate Expressions
Figure 193: SELECT Statement with Aggregate Expressions
If the field list in a SELECT statement contains only aggregate expressions, the result consists
of a single line. A structure may be specified as the target if an INTO clause is used (similar to
the SELECT SINGLE statement). The figure illustrates an example.
Hint:
If the field list only contains the MIN, MAX, SUM, and AVG functions, but not
COUNT, an internal table can also be specified as the target. As the result is a
single line, only the first line of the internal table is filled.
432
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
Aggregate Functions with the DISTINCT Addition
Figure 194: Aggregate Functions with the DISTINCT Addition
In addition to COUNT(*), the COUNT function can be used in combination with a DISTINCT
clause, in the form COUNT ( DISTINCT col ).
This aggregate expression returns the number of unique, distinct values in the specified
column.
You can use the DISTINCT addition for all other aggregate functions as well, for example, AVG
(DISTINCT col). Values that occur multiple times in the column in the selection result are only
included once in the aggregate calculation. This means that the table is aggregated before the
aggregate is formed.
Note:
In the example, the aggregate SUM (DISTINCT seatsocc) is only intended as an
illustration, not as a typical example of the technique. In general, the DISTINCT
clause is most useful when applied together with the COUNT function, and is not
commonly combined with the MIN, MAX, SUM, and AVG functions.
© Copyright. All rights reserved.
433
Unit 6: ABAP Open SQL
Special Situations
Figure 195: Special Situations
When writing SELECT statements that consist only of aggregate expressions, keep in mind
the following considerations:
●
Special case 1
The value set is empty before aggregate formation. Unlike SELECT statements, these
database accesses return a result even if no matching records are found in the database.
In this case, the result of COUNT is zero and the other aggregate functions return initial
values. SY-SUBRC is set to 0 and SY-DBCNT to 1.
Caution:
If the MIN (col) aggregate function returns an initial value, for example, you
cannot conclude that the table actually contains at least one line with the
initial value in the col column. It might also mean that the table does not
contain any entries that satisfy the WHERE condition.
●
Special case 2
The SELECT statement only contains the COUNT (*) function. If the field list only contains
the COUNT (*) aggregate function, you can omit the INTO clause completely. If no data is
found in the database, SY-SUBRC is set to 4 and SY-DBCNT to 0.
434
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
Caution:
For performance reasons, do not use the COUNT function to perform
existence checks. Use SELECT ... UP TO 1 ROWS WHERE ... instead. While
COUNT (*) looks for all records that match the WHERE condition, scanning
through the entire table, ... UP TO 1 ROWS stops searching after the first
record is found.
Field Lists with Aggregate Expressions and Field Names
Figure 196: GROUP BY Addition
If the field list of a SELECT statement contains fields and aggregate expressions, the result is
always multiline. As a result, it must be loaded into an internal table (array fetch) or processed
sequentially (SELECT loop). The SELECT statement must contain the GROUP BY clause and
all fields that are not arguments of an aggregate function in the field list must be listed after
the GROUP BY clause.
When the GROUP BY clause is specified, the database does not apply the aggregate functions
to all the retrieved records together, but instead sorts them into groups first. A group
contains all the records that have the same contents in the columns specified after GROUP
BY. The aggregate functions are evaluated separately for each of these groups. Each group
then corresponds to one line in the selection result.
© Copyright. All rights reserved.
435
Unit 6: ABAP Open SQL
Hint:
All the fields in the field list that are not arguments of an aggregate function must
be listed after GROUP BY. GROUP BY can also contain fields that are not part of
the field list - at least theoretically. However, this makes it difficult to trace which
line in the result belongs to a specific group. Therefore, every field after GROUP
BY should also appear as a column in the selection result.
For the GROUP BY clause, the restrictions are as follows:
●
Individual columns are listed after SELECT (SELECT * is not allowed)
●
No pooled tables or cluster tables
●
The fields after GROUP BY cannot have type STRING or RAWSTRING
HAVING Addition
Figure 197: HAVING Addition
When you use GROUP BY, you can specify a logical expression after the HAVING expression
to restrict the result set further.
In contrast to the WHERE condition, the logical expression after HAVING can also contain
aggregate functions (in SAP Web AS 6.10 and later). Apart from the aggregate functions, the
logical expression after HAVING can only contain fields that are specified after GROUP BY.
436
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
Caution:
If you use fields after HAVING that are not listed after GROUP BY, this does not
cause a syntax error but instead results in a catchable runtime error
(CX_SY_OPEN_SQL_DB).
The aggregate functions after HAVING are different from the aggregate functions after
SELECT. In the example, you could specify a condition COUNT (*) > 1 after HAVING to only
evaluate groups that contain more than one flight. You do not have to use the aggregate
COUNT (*) function after SELECT in this case.
© Copyright. All rights reserved.
437
Unit 6: ABAP Open SQL
438
© Copyright. All rights reserved.
Unit 6
Exercise 20
Perform Calculations on the Database
Business Example
You need to change your flight bookings report to also display the total booking amount by
currency for the chosen customer.
Implement subroutine GET_SUMS to calculate the booking totals separated by currency.
Program a single database access that returns the data completely in the desired form. Read
directly from database table SBOOK.
Template
BC402_DBT_AGG
Solution
BC402_DBS_AGG
Copy Template Program
Copy the template BC402_DBT_AGG to ZBC402_##_AGG. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
2. Analyze the interface of the subroutine GET_SUMS, particularly the typing of the
parameters. Which components are part of the line type of CT_SUMS?
Implement the SELECT Statement
1. Implement a SELECT statement to fill CT_SUMS with the booking totals. Access database
table SBOOK, selecting data based on the customer number.
Use aggregate functions to have the database calculate the totals.
2. Which addition do you use to calculate the totals separated by currency?
3. Activate and test your program.
© Copyright. All rights reserved.
439
Unit 6
Solution 20
Perform Calculations on the Database
Business Example
You need to change your flight bookings report to also display the total booking amount by
currency for the chosen customer.
Implement subroutine GET_SUMS to calculate the booking totals separated by currency.
Program a single database access that returns the data completely in the desired form. Read
directly from database table SBOOK.
Template
BC402_DBT_AGG
Solution
BC402_DBS_AGG
Copy Template Program
Copy the template BC402_DBT_AGG to ZBC402_##_AGG. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DBT_AGG.
c) Choose Display.
d) Right-click BC402_DBT_AGGand choose Copy....
e) In the Copy Program BC402_DBT_AGGdialog box, in the Target program field, enter
ZBC402_##_AGG and choose Copy.
f) In the Copy Program BC402_DBT_AGG to ZBC402_##_AGGdialog box, select all
checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Analyze the interface of the subroutine GET_SUMS, particularly the typing of the
parameters. Which components are part of the line type of CT_SUMS?
FORCURAM - Price of booking in foreign currency (dependent on booking location),
FORCURKEY - Payment currency.
Implement the SELECT Statement
1. Implement a SELECT statement to fill CT_SUMS with the booking totals. Access database
table SBOOK, selecting data based on the customer number.
440
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
Use aggregate functions to have the database calculate the totals.
a) See the source code excerpt from the model solution.
2. Which addition do you use to calculate the totals separated by currency?
a) GROUP BY forcurkey
3. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_dbs_agg.
TYPES: BEGIN OF gty_s_sums,
forcuram TYPE sbook-forcuram,
forcurkey TYPE sbook-forcurkey,
END OF gty_s_sums.
TYPES: BEGIN OF gty_s_travelags,
agencynum TYPE bc402_scus_book-agencynum,
name
TYPE bc402_scus_book-name,
city
TYPE bc402_scus_book-city,
END OF gty_s_travelags.
TYPES:
gty_t_sums
TYPE SORTED TABLE OF gty_s_sums
WITH UNIQUE KEY forcurkey,
gty_t_bookings
TYPE STANDARD TABLE OF scus_book
WITH NON-UNIQUE KEY
carrid connid fldate bookid,
gty_t_travelags TYPE STANDARD TABLE OF gty_s_travelags
WITH NON-UNIQUE KEY agencynum.
DATA:
gs_customer
gt_bookings
gt_sums
gt_travelags
TYPE
TYPE
TYPE
TYPE
scustom,
gty_t_bookings,
gty_t_sums,
gty_t_travelags.
PARAMETERS:
pa_cust TYPE sbook-customid DEFAULT '00000001'.
START-OF-SELECTION.
SELECT SINGLE * FROM scustom INTO gs_customer
WHERE id = pa_cust.
SELECT * FROM scus_book
INTO TABLE gt_bookings
WHERE customid = pa_cust
AND cancelled <> 'X'.
PERFORM get_sums USING
© Copyright. All rights reserved.
pa_cust
441
Unit 6: ABAP Open SQL
CHANGING gt_sums.
PERFORM get_travelags USING
pa_cust
CHANGING gt_travelags.
PERFORM output_list USING gs_customer
gt_bookings
gt_sums
gt_travelags.
*&-----------------------------------------------*
*&
Form GET_SUMS
*&-----------------------------------------------*
FORM get_sums USING
pv_customid TYPE sbook-customid
CHANGING ct_sums
TYPE gty_t_sums.
SELECT SUM( forcuram ) forcurkey
FROM sbook
INTO TABLE ct_sums
WHERE customid = pv_customid
GROUP BY forcurkey.
ENDFORM.
" GET_SUMS
*&-----------------------------------------------*
*&
Form GET_TRAVELAGS
*&-----------------------------------------------*
FORM get_travelags USING
pv_customid TYPE sbook-customid
CHANGING ct_travelags TYPE gty_t_travelags.
SELECT DISTINCT agencynum name city
FROM bc402_scus_book
INTO TABLE ct_travelags
WHERE customid = pv_customid
ORDER BY name.
ENDFORM.
" GET_TRAVELAGS
*&---------------------------------------------*
*&
Form OUTPUT_LIST
*&---------------------------------------------*
FORM output_list USING ps_customer TYPE scustom
pt_bookings TYPE gty_t_bookings
pt_sums
TYPE gty_t_sums
pt_travelags TYPE gty_t_travelags.
DATA:
ls_bookings LIKE LINE OF pt_bookings,
ls_sums
LIKE LINE OF pt_sums,
ls_travelags LIKE LINE OF pt_travelags.
DATA lv_text TYPE string.
CONCATENATE text-wcm
ps_customer-form
ps_customer-name
INTO lv_text
SEPARATED BY space.
CONDENSE lv_text.
WRITE: / lv_text.
SKIP.
WRITE / text-lob.
ULINE.
442
© Copyright. All rights reserved.
Lesson: Processing and Aggregating Datasets on the Database
SKIP.
LOOP AT pt_bookings INTO ls_bookings.
WRITE: /
ls_bookings-bookid,
ls_bookings-carrid RIGHT-JUSTIFIED,
ls_bookings-connid ,
ls_bookings-fldate,
ls_bookings-cityfrom RIGHT-JUSTIFIED,
'->',
ls_bookings-cityto.
ENDLOOP.
SKIP 2.
WRITE: / text-sum.
ULINE.
SKIP.
LOOP AT pt_sums INTO ls_sums.
WRITE: /
ls_sums-forcuram CURRENCY ls_sums-forcurkey,
ls_sums-forcurkey.
ENDLOOP.
SKIP 2.
WRITE / text-tag.
ULINE.
SKIP.
LOOP AT pt_travelags INTO ls_travelags.
WRITE: /
ls_travelags-name,
ls_travelags-city.
ENDLOOP.
ENDFORM.
© Copyright. All rights reserved.
" OUTPUT_LIST
443
Unit 6: ABAP Open SQL
LESSON SUMMARY
You should now be able to:
444
●
Request ordered or condensed datasets from the database
●
Perform calculations on the database
© Copyright. All rights reserved.
Unit 6
Lesson 4
Selecting Data from Multiple Database Tables
LESSON OVERVIEW
This lesson discusses the various techniques that can be used to read data from multiple
tables.
Business Example
You want to implement database access with Open SQL in your applications. You want the
data access of your application to be efficient and effective. Cases in which data has to be
read from several databases in combination are especially performance-critical. Therefore,
you need to learn about the techniques you can use to improve performance when accessing
multiple database tables.
For this reason, you require the following knowledge:
●
An understanding of how to use views and joins correctly
●
An understanding of subqueries and their usage
●
An understanding of how to use the FOR ALL ENTRIES clause correctly
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Identify the disadvantages of nested selects
●
Use ABAP joins and database views
© Copyright. All rights reserved.
445
Unit 6: ABAP Open SQL
The Problem with Nested Selects
Figure 198: Nested SELECTs
When data is stored in a relational database and is accessed in one database table (the
primary table), entries from other database tables (secondary tables) have to be read as well.
One method is to access the secondary tables in a loop over the records from the primary
table. This approach is called a nested SELECT. However, secondary tables may themselves
have associated tables that need to be read in turn. There is no theoretical or practical limit to
the nesting depth; the nested SELECT model can indefinitely chain tables as long as the tables
are linked by common data columns.
For a number of reasons, nested SELECTS are the most resource-intensive method possible
for reading multiple linked database tables, and good program design will avoid this method
for any but the smallest and simplest of data access procedures. Nested SELECTS place a
high load on the database server and produce large amounts of network traffic, because
many partially-filled data packages are transferred and the same data may be read many
times in a row (identical accesses).
In this lesson, you will learn several techniques that enable you to largely avoid nested
SELECTs, and to reduce their negative impact on system performance when their use is
unavoidable.
446
© Copyright. All rights reserved.
Lesson: Selecting Data from Multiple Database Tables
ABAP Joins
Figure 199: Example – Inner or Outer Join
To read data that is distributed across multiple tables, you must create a link between the
functionally dependent tables. The corresponding logical database operator is called a JOIN.
To implement a join, you can use either database views in the ABAP dictionary or ABAP joins.
Hint:
Database views and ABAP joins can only be used with transparent tables. If you
are working with pooled tables or cluster tables, you have to use other
techniques.
You can derive the logic of the inner join and outer join from the intended result set.
An inner join produces a result set that only considers the records from the outer table for
which suitable data records exist in the inner table (as in the example).
A left outer join produces a result set that contains all the records from the outer table,
regardless of whether or not suitable records exist in the inner table. If no suitable records
exist in the inner table, the fields of the inner (the other table that is used in the left outer join
condition) table are set to zero values in the result set. The tables involved in a join are called
base tables. A projection (column selection) or a selection (line selection) can be applied on
the result of a join.
Prior to SAP NetWeaver 7.40 SP5, because not all of the databases supported by SAP
support the standard syntax for ON conditions, restricted syntax had to be used to ensure
that only JOINs that return the same result set on all database systems were allowed. With
© Copyright. All rights reserved.
447
Unit 6: ABAP Open SQL
the new features available in Open SQL in SAP NetWeaver 7.40 SPS5, some of these
restrictions have been removed.
Restrictions for an outer joins prior to SAP NetWeaver 7.40 SP5 are as follows:
●
You can only have a table or a view to the right of the join operator. You cannot have
another join expression.
●
Only AND can be used as a logical operator in an ON condition.
●
Every comparison in the ON condition must contain a field from the table on the right.
●
None of the fields in the table on the right can appear in the WHERE conditions of the left
outer join.
For more information about implementing join functions, see the ABAP documentation.
Example – ABAP Inner Join
Figure 200: Example – ABAP Inner Join
A disadvantage of using ABAP joins is that the statement is more complex than using a
dictionary view, where the syntax of the SELECT statement (specifically, the FROM clause)
corresponds to a regular table access.
Hint:
Note that ABAP joins always bypass the table buffer, which is only a
disadvantage for joins involving buffered tables.
Dictionary views can be buffered in SAP R/3 Release 4.0 and later (depending on
which tables are used in the view).
Advantages of Database Views
Attributes and benefits of database views are as follows:
448
© Copyright. All rights reserved.
Lesson: Selecting Data from Multiple Database Tables
●
You can also use views in other programs.
●
You can use where-used lists and search functions (SE84 or SE81) to find existing views
quickly.
●
You can buffer views (technical settings) like database tables.
●
Fields common to both tables (join fields) are only transferred from the database to the
application server once.
●
The view is implemented in the ABAP Dictionary as an inner join. This means no data is
transferred if the inner table does not contain any entries that correspond to the outer
table.
●
If you do not want to use an inner join to read from a text table, use an ABAP left outer join.
For example, if you have a situation where the results of an inner join do not contain any
records because no entry is available in a certain language, you can use an ABAP left outer
join instead.
Hint:
A disadvantage of both ABAP joins and database views is that redundant 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, use a field list with a join to
retrieve only those fields that are needed. The runtime of a join formation is
highly dependent on the query optimizer, especially when the join involves more
than two tables. However, it is usually faster than using nested SELECT
statements.
© Copyright. All rights reserved.
449
Unit 6: ABAP Open SQL
450
© Copyright. All rights reserved.
Unit 6
Exercise 21
Implement a Join of Multiple Database Tables
Business Example
Your company uses a custom program that displays a list of bookings for a selection of travel
agencies, customers, and flight data.
Users frequently complain about long runtimes.
An analysis shows that the poor performance is due to numerous single record accesses of
tables SCARR and STRAVELAG within a loop.
You have been asked to redesign the program so it can read the necessary data in one
consolidated database access.
Template
BC402_DBT_3JOIN
Solution
BC402_DBS_3JOIN
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy template BC402_DBT_3JOIN to ZBC402_##_3JOIN. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
2. From which database tables does the program read the data? Which tables are read in a
loop?
3. The database administrators detected the repeated single record accesses for tables
SCARR and STRAVELAG, but not for SCUSTOM. Do you have an explanation for this?
© Copyright. All rights reserved.
451
Unit 6: ABAP Open SQL
4. In this situation, does it make sense to combine the access to SCUSTOM with an access to
the other tables in a JOIN?
Implement the Join
Implement a database access that reads from several tables together in a JOIN. Select the
three tables for which this makes sense. Note where an outer join is required to ensure the
same number of bookings is read. Only read the columns that are required. Enhance structure
type GTY_S_BOOKINGS with the appropriate components.
1. Enhance the database access to table SBOOK. Change the FROM clause to read the
necessary data from tables SCARR and STRAVELAG in a triple join. Note that SBOOK also
contains postings that were not made by travel agencies, which means the agencynum
field is INITIAL (suggesting that it is empty).
2. Which changes do you have to make to the WHERE condition?
3. In the SELECT clause, add the fields you want to read from database tables SCARR and
STRAVELAG. Enhance the line type of the internal table (structure type
GTY_S_BOOKINGS) with appropriately typed components.
4. Which other changes in the SELECT clause do you have to make?
Remove Unnecessary Statements
Remove or comment out unnecessary statements and declarations. Activate and test your
program.
1. Remove or comment out the SELECT statements for SCARR and STRAVELAG.
2. In the WRITE statement, output the additional fields from internal table GT_BOOKINGS.
3. Remove or comment out the declaration of the unnecessary data objects.
4. Activate and test your program.
452
© Copyright. All rights reserved.
Unit 6
Solution 21
Implement a Join of Multiple Database Tables
Business Example
Your company uses a custom program that displays a list of bookings for a selection of travel
agencies, customers, and flight data.
Users frequently complain about long runtimes.
An analysis shows that the poor performance is due to numerous single record accesses of
tables SCARR and STRAVELAG within a loop.
You have been asked to redesign the program so it can read the necessary data in one
consolidated database access.
Template
BC402_DBT_3JOIN
Solution
BC402_DBS_3JOIN
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy template BC402_DBT_3JOIN to ZBC402_##_3JOIN. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DBT_3JOIN.
c) Choose Display.
d) Right-click BC402_DBT_3JOINand choose Copy....
e) In the Copy Program BC402_DBT_3JOINdialog box, in the Target program field, enter
ZBC402_##_3JOIN and choose Copy.
f) In the Copy Program BC402_DBT_3JOIN to ZBC402_##_3JOINdialog box, select all
checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
© Copyright. All rights reserved.
453
Unit 6: ABAP Open SQL
2. From which database tables does the program read the data? Which tables are read in a
loop?
The database tables from which the program reads the data are SBOOK - Flight bookings,
SCUSTOM - Flight customers, SCARR - Airlines, and STRAVELAG - Travel agencies. The
database tables from which the program reads the data in the loop are SCUSTOM - Flight
customers, SCARR - Airlines, and STRAVELAG - Travel agencies.
3. The database administrators detected the repeated single record accesses for tables
SCARR and STRAVELAG, but not for SCUSTOM. Do you have an explanation for this?
Table SCUSTOM uses single-record buffering, which means the data for a specific
customer is only read from the database once on a given server.
4. In this situation, does it make sense to combine the access to SCUSTOM with an access to
the other tables in a JOIN?
No, because the buffering of SCUSTOM is ignored in a JOIN.
Implement the Join
Implement a database access that reads from several tables together in a JOIN. Select the
three tables for which this makes sense. Note where an outer join is required to ensure the
same number of bookings is read. Only read the columns that are required. Enhance structure
type GTY_S_BOOKINGS with the appropriate components.
1. Enhance the database access to table SBOOK. Change the FROM clause to read the
necessary data from tables SCARR and STRAVELAG in a triple join. Note that SBOOK also
contains postings that were not made by travel agencies, which means the agencynum
field is INITIAL (suggesting that it is empty).
a) See the source code excerpt from the model solution.
The triple join consists of an inner join between SBOOK and SCARR (the carrid field is
filled for all bookings) and a left outer join between this result and table STRAVELAG.
2. Which changes do you have to make to the WHERE condition?
The agencynum field is no longer unique. Therefore, you have to prefix it with the table
name, SBOOK, or an appropriate alias.
3. In the SELECT clause, add the fields you want to read from database tables SCARR and
STRAVELAG. Enhance the line type of the internal table (structure type
GTY_S_BOOKINGS) with appropriately typed components.
a) See the source code excerpt from the model solution.
4. Which other changes in the SELECT clause do you have to make?
The carrid and agencynum fields are no longer unique. Therefore, you have to prefix them
with the table name, SBOOK, or an appropriate alias.
Remove Unnecessary Statements
Remove or comment out unnecessary statements and declarations. Activate and test your
program.
454
© Copyright. All rights reserved.
Lesson: Selecting Data from Multiple Database Tables
1. Remove or comment out the SELECT statements for SCARR and STRAVELAG.
a) See the source code excerpt from the model solution.
2. In the WRITE statement, output the additional fields from internal table GT_BOOKINGS.
a) See the source code excerpt from the model solution.
3. Remove or comment out the declaration of the unnecessary data objects.
a) See the source code excerpt from the model solution.
4. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
REPORT
bc402_dbs_3join.
TYPES: BEGIN OF gty_s_booking,
carrid
TYPE sbook-carrid,
connid
TYPE sbook-connid,
fldate
TYPE sbook-fldate,
bookid
TYPE sbook-bookid,
customid
TYPE sbook-customid,
agencynum TYPE sbook-agencynum,
carrname
TYPE scarr-carrname,
agencyname TYPE stravelag-name,
agencycity TYPE stravelag-city,
END OF gty_s_booking.
TYPES:
gty_t_bookings TYPE STANDARD TABLE OF gty_s_booking
WITH NON-UNIQUE KEY
carrid connid fldate bookid.
DATA:
gt_bookings TYPE gty_t_bookings,
gs_booking TYPE gty_s_booking.
DATA:
gv_custname
TYPE scustom-name.
* gv_carrname
TYPE scarr-carrname,
* gv_agencyname TYPE stravelag-name,
* gv_agencycity TYPE stravelag-city.
FIELD-SYMBOLS:
<fs_booking> LIKE LINE OF gt_bookings.
SELECT-OPTIONS :
so_agy FOR gs_booking-agencynum DEFAULT '100',
so_cus FOR gs_booking-customid,
so_fld FOR gs_booking-fldate.
START-OF-SELECTION.
SELECT b~carrid b~connid b~fldate b~bookid
b~customid b~agencynum
c~carrname a~name a~city
FROM sbook AS b INNER JOIN scarr AS c
© Copyright. All rights reserved.
455
Unit 6: ABAP Open SQL
ON b~carrid
= c~carrid
LEFT OUTER JOIN stravelag AS a
ON b~agencynum = a~agencynum
INTO TABLE gt_bookings
WHERE b~agencynum IN so_agy AND
b~customid IN so_cus AND
b~fldate
IN so_fld AND
cancelled
<> 'X'.
LOOP AT gt_bookings ASSIGNING <fs_booking>.
* scustom is buffered - no need for optimizations
SELECT SINGLE name FROM scustom INTO gv_custname
WHERE id = <fs_booking>-customid.
*
SELECT SINGLE carrname FROM scarr
*
INTO gv_carrname
*
WHERE carrid = <fs_booking> -carrid.
*
*
SELECT SINGLE name city FROM stravelag
*
INTO (gv_agencyname, gv_agencycity)
*
WHERE agencynum = <fs_booking> -agencynum.
WRITE: /
<fs_booking>-carrid,
*
gv_carrname,
<fs_booking>-carrname,
<fs_booking>-connid,
<fs_booking>-fldate,
<fs_booking>-bookid,
gv_custname,
*
gv_agencyname,
*
gv_agencycity.
<fs_booking>-agencyname,
<fs_booking>-agencycity.
ENDLOOP.
456
© Copyright. All rights reserved.
Lesson: Selecting Data from Multiple Database Tables
LESSON SUMMARY
You should now be able to:
●
Identify the disadvantages of nested selects
●
Use ABAP joins and database views
© Copyright. All rights reserved.
457
Unit 6
Lesson 5
Explaining Additional Techniques for Reading
from Multiple Database Tables
LESSON OVERVIEW
This lesson shows how to read from multiple database tables by using subqueries, cursors or
the FOR ALL ENTRIES addition. Buffering techniques for the cases when joins are not
permitted are also explained.
Business Example
You have to read data from multiple database tables, including data from a pooled table. To
find the best way to read the data, you must familiarize yourself with the usage of subqueries,
cursors, or FOR ALL ENTRIES statements. For this reason, you require the following
knowledge:
●
An understanding of subselects and subqueries, parallel cursors, and parallel cursors
instead of nested SELECTS
●
An understanding of buffering techniques and read-on-demand buffering
●
An understanding of the FOR ALL ENTRIES addition
LESSON OBJECTIVES
After completing this lesson, you will be able to:
458
●
Explain special techniques for reading from multiple database tables
●
Use explicit buffering techniques
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
Subselects and Subqueries
Figure 201: Subselects and Subqueries
A subquery is a query within a SELECT, UPDATE, or DELETE statement. It is formulated in the
WHERE or HAVING clause to check whether the data in various database tables or views
possess certain attributes.
A SELECT statement with a subquery has a more restricted syntax than a SELECT statement
without a subquery.
If the subquery returns exactly one value, you can use the usual comparison operators apart
from LIKE and BETWEEN. If you use a subquery with a comparison operator instead of with
EXISTS, then the SELECT clause of the subquery can only contain a single column, which can
be a field in the database table or an aggregate expression.
In this example, the subquery is supposed to return several lines, each with one value. If you
want to compare all the returned values, use IN. Subqueries whose WHERE condition contains
fields from the main query are called correlated subqueries. If subqueries are nested, each
subquery can use all the fields from the higher-level subqueries in the hierarchy. Query
designers should formulate positive subqueries whenever possible; negative formulations
may result in performance-degrading database reads if no adequate index is available.
© Copyright. All rights reserved.
459
Unit 6: ABAP Open SQL
Hint:
In many cases, you can also use a join to obtain the same result as that produced
with a subquery. The SQL code for a join is easier for other developers to read
and understand, but no blanket statements can be made about the relative
performance of subqueries and joins, because the table design, query logic, and
amount of data to be retrieved all can have major impacts on the performance of
both methods. For performance-critical systems, it is advisable to prototype the
query using each method and run performance profiles with real-world data to
ascertain which approach will produce faster output.
Parallel Cursors
Figure 202: Initial Situation – Nested SELECTs
Using the Open SQL statements OPEN CURSOR, FETCH NEXT CURSOR, and CLOSE
CURSOR to program explicit cursor handling with several database tables concurrently allows
you to process the contents of multiple database tables in parallel without using nested
SELECTs.
In the example in the figure Initial Situation – Nested SELECTs, you want the program to
process all flights from database table SFLIGHT, and you want to read the non-canceled
bookings in the economy class for each flight from database table SBOOK and process the
bookings together with the flight. The obvious solution is a nested SELECT, but that solution is
likely to have poor performance.
Due to the large data volume involved, you do not want to buffer the bookings completely in
an internal table.
460
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
Parallel Cursors Instead of Nested SELECTs
Figure 203: Parallel Cursors Instead of Nested SELECTs
Rather than solving the problem with nested SELECTs, you can achieve the same result by
addressing the two database tables with two concurrently open database cursors.
Parallel cursors work as follows:
●
Each fetch for the first cursor (cursor variable GV_CURSOR_SFLIGHT) places the next
respective record from database table SFLIGHT into structure GS_FLIGHT (similar to
a SELECT loop).
●
Each fetch for the second cursor (cursor variable GV_CURSOR_SBOOK) reads the
corresponding non-canceled economy bookings into internal table GT_BOOKINGS.
However, these bookings are not actually selected based on their key. Instead, the next n
records are simply read. The value of n corresponds to the value of the seatsocc field in the
record for the flight. Because the selection results are sorted (ORDER BY clause), the next
n bookings are the bookings for the current flight.
For this technique to work correctly, the following prerequisites must be met:
●
Both tables must be sorted by the same criteria (ORDER BY clause).
●
Every record in the outer table must specify exactly how many corresponding records
exist in the inner table.
If these conditions for the data are not met, then the concurrent cursor program design will
return incorrect results, or fail to work at all. It is therefore a less robust, though much betterperforming, approach to the problem.
© Copyright. All rights reserved.
461
Unit 6: ABAP Open SQL
Hint:
To circumvent the second criterion and improve the robustness of the solution,
you can open two cursors for the same database table and have the outer cursor
use the count (*) aggregate function to determine the number of records in each
group.
Buffering Techniques
Avoiding database accesses in the first place is the simplest way to reduce database load. You
can do this by taking table contents that have already been read and saving them in an
internal table (with type SORTED or HASHED, if possible).
In many cases, the application logic does not permit the use of joins. If you need to read data
from multiple tables in such cases, you can use a separate internal table to buffer the read
data.
Read-On-Demand and Buffering
Figure 204: Read-On-Demand and Buffering
In the example, you want to read the matching data from STRAVELAG (travel agency master
data) within a loop for the bookings from table SBOOK. You can accomplish this with a
SELECT SINGLE statement or a read routine. If you use SELECT SINGLE in this approach,
multiple identical SQL statements are executed. Therefore, it may be better to encapsulate
the reading of STRAVELAG records in a read routine. In the example, the table contents read
from STRAVELAG are buffered in a static internal table. Before each database access, the
system checks whether the corresponding table entry has already been read.
462
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
The read routine can also be a method of a local or global class instead of a subroutine. In this
case, a private attribute of the corresponding class would be used as buffer instead of the
static internal table ST_TRAVELAGS.
© Copyright. All rights reserved.
463
Unit 6: ABAP Open SQL
464
© Copyright. All rights reserved.
Unit 6
Exercise 22
Implement Full Buffering and Buffering on
Demand
Business Example
Your company uses a standard SAP program that displays a list of bookings for a customer.
This program has been enhanced as follows to meet your company’s needs:
●
A BAdI implementation was created to fill additional fields which were added to the
structure type BC402_S_BOOKING using an append structure.
●
The BAdI implementation is called inside a loop through the bookings internal table.
You realize that you can improve your enhancement by buffering the data in instance
attributes of the BAdI implementation class (these instance attributes will be internal tables),
instead of accessing the database every time the BAdI method is called.
Hint:
To avoid making this exercise unnecessarily complicated, you do not use an
actual BAdI. Instead, the BAdI implementation is simulated using a local class.
Only change the definition and implementation of this local class during the
exercise. Imagine that the source code outside of this class represents the SAP
program and is unchangeable.
Template
BC402_DBT_BUFFER
Solution
BC402_DBS_BUFFER
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy template BC402_DBT_BUFFER to ZBC402_##_BUFFER. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
© Copyright. All rights reserved.
465
Unit 6: ABAP Open SQL
2. Which methods does class LCL_IM_BADI have? Which parameters exist in these
methods? How are they typed?
3. Display dictionary structure type BC402_S_BOOKING. Which fields were added in an
append?
4. Where is method ADD_DATA of class LCL_IM_BADI called?
5. Which database tables are accessed within the local class LCL_IM_BADI?
Define Table-Type Attributes to Buffer the Data
Edit the definition of class LCL_IM_BADI. Create two table-type private instance attributes to
buffer the data that is read from the database in method ADD_DATA. Declare private
structure and table types to define the new attributes, also in the class definition.
1. Create a structure type in the private section of the class definition whose components
include the key and required fields from the table (suggested name: TY_S_SCARR).
2. Create a table type in the private section of the class definition that has the structure type
as its line type (suggested name: TY_T_SCARR).
3. Which table type is particularly suited to this type of buffering?
4. Create an instance attribute in the private section of the class definition (suggested name:
mt_carriers) and type it with this table type.
5. Create an appropriate structure type, table type, and instance attribute to buffer the data
from database table STRAVELAG (suggested names: ty_s_stravelag,
ty_t_stravelag, mt_travelags).
Edit the Implementation of Method ADD_DATA
Make sure the data is buffered in the instance attributes of the class after it is read from the
database. Full buffering in an internal table is possible for one of the tables. Make sure that all
entries in this database table are read and buffered the first time the method is called. Full
buffering does not make sense for the other database table. Make sure the data from this
table is read and buffered individually on demand.
466
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
1. Which database table is a candidate for full buffering? Why?
2. Program a database access in which the database table that you want to buffer is loaded
completely into the corresponding attribute. Ensure that the database table is only read
during the first call of the ADD_DATA method.
3. Replace the single record access to the database table with an access to the internal table
(the Instance attribute).
4. Make sure that each time the database table that you do not want to buffer is accessed
(on a single record basis), the individual data is buffered in the Instance attribute.
5. Implement an access to the internal table (the Instance attribute) before the database
access. Make sure the database access is skipped if the corresponding record is already
found in the internal table.
6. Activate and test your program.
© Copyright. All rights reserved.
467
Unit 6
Solution 22
Implement Full Buffering and Buffering on
Demand
Business Example
Your company uses a standard SAP program that displays a list of bookings for a customer.
This program has been enhanced as follows to meet your company’s needs:
●
A BAdI implementation was created to fill additional fields which were added to the
structure type BC402_S_BOOKING using an append structure.
●
The BAdI implementation is called inside a loop through the bookings internal table.
You realize that you can improve your enhancement by buffering the data in instance
attributes of the BAdI implementation class (these instance attributes will be internal tables),
instead of accessing the database every time the BAdI method is called.
Hint:
To avoid making this exercise unnecessarily complicated, you do not use an
actual BAdI. Instead, the BAdI implementation is simulated using a local class.
Only change the definition and implementation of this local class during the
exercise. Imagine that the source code outside of this class represents the SAP
program and is unchangeable.
Template
BC402_DBT_BUFFER
Solution
BC402_DBS_BUFFER
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy template BC402_DBT_BUFFER to ZBC402_##_BUFFER. Familiarize yourself with the
program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
468
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DBT_BUFFER.
c) Choose Display.
d) Right-click BC402_DBT_BUFFERand choose Copy....
e) In the Copy Program BC402_DBT_BUFFERdialog box, in the Target program field,
enter ZBC402_##_BUFFER and choose Copy.
f) In the Copy Program BC402_DBT_BUFFER to ZBC402_##_BUFFERdialog box, select
all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Which methods does class LCL_IM_BADI have? Which parameters exist in these
methods? How are they typed?
The class only has one method, ADD_DATA. The only parameter is changing parameter
CS_BOOKING, which is typed with dictionary structure type BC402_S_BOOKING.
3. Display dictionary structure type BC402_S_BOOKING. Which fields were added in an
append?
CARRNAME, AGENCYNAME, and AGENCYCITY.
4. Where is method ADD_DATA of class LCL_IM_BADI called?
Within a loop of internal table GT_BOOKINGS.
5. Which database tables are accessed within the local class LCL_IM_BADI?
The database tables SCARR - Airlines and STRAVELAG - Travel agencies are accessed
within the local class LCL_IM_BADI.
Define Table-Type Attributes to Buffer the Data
Edit the definition of class LCL_IM_BADI. Create two table-type private instance attributes to
buffer the data that is read from the database in method ADD_DATA. Declare private
structure and table types to define the new attributes, also in the class definition.
1. Create a structure type in the private section of the class definition whose components
include the key and required fields from the table (suggested name: TY_S_SCARR).
a) See the source code excerpt from the model solution.
2. Create a table type in the private section of the class definition that has the structure type
as its line type (suggested name: TY_T_SCARR).
a) See the source code excerpt from the model solution.
© Copyright. All rights reserved.
469
Unit 6: ABAP Open SQL
3. Which table type is particularly suited to this type of buffering?
A hashed table, because the same unique key is always used to access the content later in
single record access.
4. Create an instance attribute in the private section of the class definition (suggested name:
mt_carriers) and type it with this table type.
a) See the source code excerpt from the model solution.
5. Create an appropriate structure type, table type, and instance attribute to buffer the data
from database table STRAVELAG (suggested names: ty_s_stravelag,
ty_t_stravelag, mt_travelags).
a) See the source code excerpt from the model solution.
Edit the Implementation of Method ADD_DATA
Make sure the data is buffered in the instance attributes of the class after it is read from the
database. Full buffering in an internal table is possible for one of the tables. Make sure that all
entries in this database table are read and buffered the first time the method is called. Full
buffering does not make sense for the other database table. Make sure the data from this
table is read and buffered individually on demand.
1. Which database table is a candidate for full buffering? Why?
Database table SCARR. It only has a few entries, so the probability that many of these
entries will actually be needed is high. In contrast, database table STRAVELAG is fairly
large, and you can assume that a given flight customer has only booked flights at a few
travel agencies.
2. Program a database access in which the database table that you want to buffer is loaded
completely into the corresponding attribute. Ensure that the database table is only read
during the first call of the ADD_DATA method.
a) See the source code excerpt from the model solution.
3. Replace the single record access to the database table with an access to the internal table
(the Instance attribute).
a) See the source code excerpt from the model solution.
4. Make sure that each time the database table that you do not want to buffer is accessed
(on a single record basis), the individual data is buffered in the Instance attribute.
a) See the source code excerpt from the model solution.
5. Implement an access to the internal table (the Instance attribute) before the database
access. Make sure the database access is skipped if the corresponding record is already
found in the internal table.
a) See the source code excerpt from the model solution.
6. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
470
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
Source code excerpt from the model solution:
Interface lif_badi
INTERFACE lif_badi.
METHODS:
add_data
CHANGING cs_booking TYPE bc402_s_booking.
ENDINTERFACE.
"lif_badi
Class lcl_im_badi (Definition)
CLASS lcl_im_badi DEFINITION.
PUBLIC SECTION.
INTERFACES lif_badi.
PRIVATE SECTION.
TYPES: BEGIN OF ty_s_scarr,
carrid TYPE scarr-carrid,
carrname TYPE scarr-carrname,
END OF ty_s_scarr.
TYPES: ty_t_scarr TYPE HASHED TABLE OF ty_s_scarr
WITH UNIQUE KEY carrid.
TYPES: BEGIN OF ty_s_stravelag,
agencynum TYPE stravelag-agencynum,
name
TYPE stravelag-name,
city
TYPE stravelag-city,
END OF ty_s_stravelag.
TYPES: ty_t_stravelag TYPE HASHED TABLE OF ty_s_stravelag
WITH UNIQUE KEY agencynum.
DATA: mt_carriers TYPE ty_t_scarr,
mt_travelags TYPE ty_t_stravelag.
ENDCLASS.
"lcl_im_badi DEFINITION
Class lcl_im_badi (Implementation)
CLASS lcl_im_badi IMPLEMENTATION.
METHOD lif_badi~add_data.
DATA:
ls_carrier LIKE LINE OF mt_carriers,
ls_travelag LIKE LINE OF mt_travelags.
* carrname - Buffer full
*
SELECT SINGLE carrname FROM scarr
*
INTO cs_booking-carrname
*
WHERE carrid = cs_booking-carrid.
IF mt_carriers IS INITIAL.
SELECT carrid carrname FROM scarr
INTO TABLE mt_carriers.
ENDIF.
READ TABLE mt_carriers INTO ls_carrier
WITH TABLE KEY carrid = cs_booking-carrid.
cs_booking-carrname = ls_carrier-carrname.
© Copyright. All rights reserved.
471
Unit 6: ABAP Open SQL
* agencyname and agencycity - buffer on demand
*
*
*
*
SELECT SINGLE name city FROM stravelag
INTO (cs_booking-agencyname,
cs_booking-agencycity)
WHERE agencynum = cs_booking-agencynum.
IF cs_booking-agencynum IS NOT INITIAL.
READ TABLE mt_travelags INTO ls_travelag
WITH TABLE KEY agencynum = cs_booking-agencynum.
IF sy-subrc <> 0.
SELECT SINGLE agencynum name city
FROM stravelag
INTO ls_travelag
WHERE agencynum = cs_booking-agencynum.
INSERT ls_travelag INTO TABLE mt_travelags.
ENDIF.
cs_booking-agencyname = ls_travelag-name.
cs_booking-agencycity = ls_travelag-city.
ENDIF.
ENDMETHOD.
ENDCLASS.
472
"lif_badi~add_data
"lcl_im_badi IMPLEMENTATION
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
FOR ALL ENTRIES Addition
Figure 205: SELECT with FOR ALL ENTRIES Addition
SELECT … FOR ALL ENTRIES was created in Open SQL at a time when it was not possible to
perform database joins (this was not supported for all SAP-approved DBMS). The connection
between the inner and outer database tables was created in ABAP.
Nowadays, this technique is often used when some data is already available in an internal
table, but additional data is to be read from the database. In such cases, SELECT … FOR ALL
ENTRIES replaces a SELECT SINGLE statement inside a LOOP over the internal table, and
normally shows better performance than such a LOOP.
Note:
As a possible scenario, use a program exit in which data can be added to an
internal table provided by the standard SAP program.
The figure SELECT with FOR ALL ENTRIES Addition illustrates an example of how the
statement works.
The content of the internal table (driving table) is used as a restriction for the database
access, and may depend on the database system. In general, the database interface takes a
certain number of entries in the internal table (in the example it takes 5) and sends one native
SQL statement to the database for each group. In the end, the results of the individual native
SQL statements are combined to form the result of the Open SQL statement. Duplicate
entries are automatically removed. Note that the size of the packages is controlled by a profile
parameter.
© Copyright. All rights reserved.
473
Unit 6: ABAP Open SQL
Caution:
If you use FOR ALL ENTRIES, make sure that the driving table is not blank. If the
table is blank, it provides no boundary condition for the SELECT statement and
often the full database table is read. This can cause very long execution times for
the statement.
Hint:
Because duplicates are automatically removed from the result, the driving table
does not have to be free of duplicate entries. However, you can improve the
performance of the statement if you condense the driving table before the FOR
ALL ENTRIES statement (maybe by using a copy of the table). If you do not
remove duplicate entries from the driving table, the same data will be read
multiple times from the database and only removed in the final combination of
the result.
If you want to read large data volumes, use FOR ALL ENTRIES only in exceptional cases.
474
© Copyright. All rights reserved.
Unit 6
Exercise 23
Read Additional Data with the FOR ALL
ENTRIES Addition
Business Example
After a release upgrade, you realize that SAP has changed the BAdI that you use in your
bookings report, by including another method which is called before the loop through the
bookings internal table. You realize that you can improve performance further by moving the
filling of the table-type instance attributes to an implementation of this new method.
Hint:
To avoid making this exercise unnecessarily complicated, you do not use an
actual BAdI. Instead, simulate the BAdI implementation using a local class. Only
change the definition and implementation of this local class during the exercise.
You should consider the source code outside of this class, which represents the
SAP program, to be unchangeable.
Template
BC402_DBT_FOR_ALL_ENTRIES
Solution
BC402_DBS_FOR_ALL_ENTRIES
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy template BC402_DBT_FOR_ALL_ENTRIES to ZBC402_##_FOR_ALL_ENTRIES.
Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Which methods does class LCL_IM_BADI have? Which parameters exist in these
methods? How are they typed?
© Copyright. All rights reserved.
475
Unit 6: ABAP Open SQL
3. Where is the prepare method of class LCL_IM_BADI called?
Edit the Implementation of Method PREPARE
Program a database access to the database tables SCARR and STRAVELAG. Fill instance
attribute MT_CARRIERS with the data for all airlines and fill instance attribute
MT_TRAVELAGS with the data for the travel agencies. Make sure you do not buffer the data
for all the travel agencies, but instead only for those you require during the loop pass.
1. Copy the filling of MT_CARRIERS from method ADD_DATA to method PREPARE.
2. Do you still need the query that determines whether this call is the first call?
3. Program a SELECT statement (array fetch) in which you fill instance attribute
MT_TRAVELAGS. Use the contents of the IT_BOOKINGS import parameter to ensure that
only the travel agencies that appear in the bookings in IT_BOOKINGS are read.
4. Why is it essential to check whether IT_BOOKINGS is filled? What would happen if
IT_BOOKINGS were blank?
Edit the implementation of method ADD_DATA
Remove all the database accesses and replace them with accesses to the instance attributes
with the buffered data.
1. Remove the SELECT statement for database table SCARR.
2. Remove the SELECT statement for database table STRAVELAG as well as the filling of the
buffer.
3. Activate and test your program.
476
© Copyright. All rights reserved.
Unit 6
Solution 23
Read Additional Data with the FOR ALL
ENTRIES Addition
Business Example
After a release upgrade, you realize that SAP has changed the BAdI that you use in your
bookings report, by including another method which is called before the loop through the
bookings internal table. You realize that you can improve performance further by moving the
filling of the table-type instance attributes to an implementation of this new method.
Hint:
To avoid making this exercise unnecessarily complicated, you do not use an
actual BAdI. Instead, simulate the BAdI implementation using a local class. Only
change the definition and implementation of this local class during the exercise.
You should consider the source code outside of this class, which represents the
SAP program, to be unchangeable.
Template
BC402_DBT_FOR_ALL_ENTRIES
Solution
BC402_DBS_FOR_ALL_ENTRIES
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy template BC402_DBT_FOR_ALL_ENTRIES to ZBC402_##_FOR_ALL_ENTRIES.
Familiarize yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DBT_FOR_ALL_ENTRIES.
c) Choose Display.
d) Right-click BC402_DBT_FOR_ALL_ENTRIESand choose Copy....
© Copyright. All rights reserved.
477
Unit 6: ABAP Open SQL
e) In the Copy Program BC402_DBT_FOR_ALL_ENTRIESdialog box, in the Target
program field, enter ZBC402_##_FOR_ALL_ENTRIES and choose Copy.
f) In the Copy Program BC402_DBT_FOR_ALL_ENTRIES to
ZBC402_##_FOR_ALL_ENTRIESdialog box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Which methods does class LCL_IM_BADI have? Which parameters exist in these
methods? How are they typed?
Class LCL_IM_BADI has a method called ADD_DATA and another one called PREPARE.
The only parameter in the ADD_DATA method is the changing parameter, CS_BOOKING,
which is typed with dictionary structure type BC402_S_BOOKING. The only parameter in
the prepare method is the import parameter, IT_BOOKINGS, which is typed with
dictionary table type BC402_T_BOOKINGS.
3. Where is the prepare method of class LCL_IM_BADI called?
The prepare method of class LCL_IM_BADI is called directly before the loop over internal
table GT_BOOKINGS.
Edit the Implementation of Method PREPARE
Program a database access to the database tables SCARR and STRAVELAG. Fill instance
attribute MT_CARRIERS with the data for all airlines and fill instance attribute
MT_TRAVELAGS with the data for the travel agencies. Make sure you do not buffer the data
for all the travel agencies, but instead only for those you require during the loop pass.
1. Copy the filling of MT_CARRIERS from method ADD_DATA to method PREPARE.
a) See the source code excerpt from the model solution.
2. Do you still need the query that determines whether this call is the first call?
No, because the PREPARE method is only called before the loop over the bookings.
3. Program a SELECT statement (array fetch) in which you fill instance attribute
MT_TRAVELAGS. Use the contents of the IT_BOOKINGS import parameter to ensure that
only the travel agencies that appear in the bookings in IT_BOOKINGS are read.
a) See the source code excerpt from the model solution.
4. Why is it essential to check whether IT_BOOKINGS is filled? What would happen if
IT_BOOKINGS were blank?
The FOR ALL ENTRIES addition is only a restriction if the specified internal table is filled.
Therefore, if IT_BOOKINGS is blank, all records from STRAVELAG are buffered, even
though no data is required later, because ADD_DATA is not executed.
Edit the implementation of method ADD_DATA
Remove all the database accesses and replace them with accesses to the instance attributes
with the buffered data.
1. Remove the SELECT statement for database table SCARR.
478
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
a) See the source code excerpt from the model solution.
2. Remove the SELECT statement for database table STRAVELAG as well as the filling of the
buffer.
a) See the source code excerpt from the model solution.
3. Activate and test your program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
Interface lif_badi
INTERFACE lif_badi.
METHODS:
prepare
IMPORTING it_bookings TYPE bc402_t_bookings,
add_data
CHANGING cs_booking TYPE bc402_s_booking.
ENDINTERFACE.
"lif_badi
Class lcl_im_badi (Definition)
CLASS lcl_im_badi DEFINITION.
PUBLIC SECTION.
INTERFACES lif_badi.
PRIVATE SECTION.
TYPES: BEGIN OF ty_s_scarr,
carrid
TYPE scarr-carrid,
carrname TYPE scarr-carrname,
END OF ty_s_scarr.
TYPES: ty_t_scarr TYPE HASHED TABLE OF ty_s_scarr
WITH UNIQUE KEY carrid.
TYPES: BEGIN OF ty_s_stravelag,
agencynum TYPE stravelag-agencynum,
name
TYPE stravelag-name,
city
TYPE stravelag-city,
END OF ty_s_stravelag.
TYPES ty_t_stravelag TYPE HASHED TABLE OF ty_s_stravelag
WITH UNIQUE KEY agencynum.
DATA: mt_carriers TYPE ty_t_scarr,
mt_travelags TYPE ty_t_stravelag.
ENDCLASS.
"lcl_im_badi DEFINITION
Class lcl_im_badi (Implementation)
CLASS lcl_im_badi IMPLEMENTATION.
METHOD lif_badi~prepare.
* carrname - buffer full
SELECT carrid carrname FROM scarr
© Copyright. All rights reserved.
479
Unit 6: ABAP Open SQL
INTO TABLE mt_carriers.
* agencyname agencycity - buffer for all entries
IF it_bookings IS NOT INITIAL.
SELECT agencynum name city
FROM stravelag
INTO TABLE mt_travelags
FOR ALL ENTRIES IN it_bookings
WHERE agencynum = it_bookings-agencynum.
ENDIF.
ENDMETHOD.
"lif_badi~prepare
METHOD lif_badi~add_data.
DATA:
ls_carrier LIKE LINE OF mt_carriers,
ls_travelag LIKE LINE OF mt_travelags.
* carrname - read from buffer
*
IF mt_carriers IS INITIAL.
*
SELECT carrid carrname FROM scarr
*
INTO TABLE mt_carriers.
*
ENDIF.
READ TABLE mt_carriers INTO ls_carrier
WITH TABLE KEY carrid = cs_booking-carrid.
cs_booking-carrname = ls_carrier-carrname.
* agencyname and agencycity - read from buffer
IF cs_booking-agencynum IS NOT INITIAL.
*
*
*
*
*
*
*
*
READ TABLE mt_travelags INTO ls_travelag
WITH TABLE KEY agencynum = cs_booking-agencynum.
IF sy-subrc <> 0.
SELECT SINGLE agencynum name city
FROM stravelag
INTO ls_travelag
WHERE agencynum = cs_booking-agencynum.
INSERT ls_travelag INTO TABLE mt_travelags.
ENDIF.
cs_booking-agencyname = ls_travelag-name.
cs_booking-agencycity = ls_travelag-city.
ENDIF.
ENDMETHOD.
ENDCLASS.
480
"lif_badi~add_data
"lcl_im_badi IMPLEMENTATION
© Copyright. All rights reserved.
Lesson: Explaining Additional Techniques for Reading from Multiple Database Tables
LESSON SUMMARY
You should now be able to:
●
Explain special techniques for reading from multiple database tables
●
Use explicit buffering techniques
© Copyright. All rights reserved.
481
Unit 6
Lesson 6
Accessing Large Objects (LOBs) on the
Database
LESSON OVERVIEW
This lesson explains the handling of large objects (LOBs) in database tables. Large objects
may be large binary strings (BLOBs) or large character strings (CLOBs). The use of data
streams and locators for LOBs in database tables can lead to improved performance with
regard to the program runtime by omitting unnecessary data transports, and reducing
memory consumption on the application server.
Business Example
You want to read large strings from a database table and store this information in an internal
table or as a file. You also want to copy large strings within the database. In both cases, you
want to reduce the memory consumption and increase the performance of your program.
For this reason, you require the following knowledge:
●
An understanding of access subsequences or properties of LOBs on the database table
using locators
●
An understanding of how to use locators to copy LOBs in the database table without first
transferring the data to the application server
●
An understanding of how to process LOBs sequentially by using the stream concept
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Explain streams and locators
Overview of LOBs in the Database
For normal access to Large Objects (LOBs), use the ABAP data object types string and
xstring, into which the entire LOB is transferred for read access, and from which the entire
LOB is taken for write access. Depending on the string length, this transfer may lead to high
memory consumption on the application server. For certain operations on the LOB (for
example, copying the LOB within the database table or storing the LOB in a data object that is
not of type string or xstring), it is not necessary to realize the complete LOB in the ABAP
program.
You can reduce memory consumption and improve the program performance with regard to
runtime by omitting unnecessary data transports. You do so by using streaming and/or
locator objects (LOB handles).
482
© Copyright. All rights reserved.
Lesson: Accessing Large Objects (LOBs) on the Database
Hint:
SQL streams and locators are supported as of SAP NetWeaver 7.0 EhP 2.
Streams
Figure 206: Create Stream Reader Object and Assign it to LOB (1)
For read access, read streams can be linked to LOBs using the assignment of corresponding
streaming objects. The same applies for write access and write streams. LOB data can be
partially processed using the stream methods.
Specific Instances of ABAP Classes that can be Linked to LOBs
●
CL_ABAP_DB_C_READER
Can be linked to a large string (CLOB), located on a database table. Use this to read CLOBs
sequentially.
●
CL_ABAP_DB_X_READER
Can be linked to a large binary string (BLOB), located on a database table. Use this to read
BLOBs sequentially.
●
CL_ABAP_DB_C_WRITER
Can be linked to a large string (CLOB), located on a database table. Use this to write
CLOBs sequentially.
© Copyright. All rights reserved.
483
Unit 6: ABAP Open SQL
●
CL_ABAP_DB_X_WRITER
Can be linked to a large binary string (BLOB), located on a database table. Use this to write
BLOBs sequentially.
To create a streaming class instance, use a reference variable in the appropriate SQL
statement. To read streams, use the reference variable in the INTO clause of the SELECT
statement. A LOB from the result set can be assigned to a LOB handle component of a work
area or to an individual reference variable for a LOB handle.
After the execution of the SQL statement, the reference variable points to the LOB handle.
The related class is determined using the data type of the result set column and the static
type of the target variable, or using the CREATING addition if required. The LOB to be read
can be evaluated or forwarded using LOB handle methods.
Create Stream Reader Object and Assign it to LOB (2)
Figure 207: Create Stream Reader Object and Assign it to LOB (2)
The figure Create Stream Reader Object and Assign it to LOB (2) illustrates how to create a
structure that contains a reference field for the stream reader, and how to assign the reader
to the LOB during selection.
484
© Copyright. All rights reserved.
Lesson: Accessing Large Objects (LOBs) on the Database
Create LOB Handler and Assign it to LOB
Figure 208: Create LOB Handler and Assign it to LOB
The figure Create LOB Handler and Assign it to LOB shows how to use one handle and, by
using down-casting, how to refer a stream reading object or a locator object assigned to an
LOB.
Methods Defined to Read Streams
●
DATA_AVAILABLE ( )
Check whether input stream is empty
●
READ( <length> )
Read the next <length> bytes (characters) from the input stream
●
SKIP( <length> )
Skip the next <length> bytes (characters)
●
IS_CLOSED( )
Check whether data stream is closed
●
CLOSE( )
Close data stream
●
IS_MARK_SUPPORTED( )
Check whether setting a marker is possible
© Copyright. All rights reserved.
485
Unit 6: ABAP Open SQL
●
SET_MARK( )
Set marker at current reading position
●
RESET_TO_MARK( )
Position read cursor to marking position
●
DELETE_MARK( )
Delete marker
●
IS_RESET_SUPPORTED( )
Check whether jumping to the beginning of the LOB is possible
●
RESET( )
Position reading cursor to beginning of LOB
●
IS_X_READER( )
Check if stream is binary data stream or character data stream
●
GET_STATEMENT_HANDLE( )
Get object describing SQL statement
Streams – Example
Figure 209: Streams – Example
The figure Streams – Example illustrates an example of streams.
486
© Copyright. All rights reserved.
Lesson: Accessing Large Objects (LOBs) on the Database
Hint:
A maximum of 1000 LOB handles can be open in a database LUW (Logical Unit of
Work).
Hint:
Because the number of data streams open at one time is only limited to 16, close
them as soon as possible using the CLOSE method. Independently of this, read
streams are closed implicitly at the end of a SELECT statement and at the end of
a database LUW. You can close an open write stream implicitly only by using a
database rollback. Database commits for open write streams, on the other hand,
cause a non-catchable runtime error, COMMIT_STREAM_ERROR.
Locators
Figure 210: Locator Example – Determine Metadata of CLOBs
For read and write access, you can link locators to LOBs by assigning the corresponding
reference variables. Using the methods of the locators, you can access the subsequences of
LOBs or the properties of LOBs without requiring a complete realization in the ABAP program.
Furthermore, locators enable the copying of LOBs within the database without having to
transport the data between the database and the application server.
© Copyright. All rights reserved.
487
Unit 6: ABAP Open SQL
Specific Instances of Classes that can be Linked to LOBs
●
CL_ABAP_DB_C_LOCATOR
Can be linked to a large string (CLOB), located on a database table. Use these to get
metadata related to the string, or to read a subsequence of the string.
●
CL_ABAP_DB_X_LOCATOR
Can be linked to a large binary string (BLOB), located in a database table. Use these to get
metadata related to the xstring, or to read a subsequence of the xstring.
The creation of a locator class instance and the assignment of this object to the LOB is similar
to the situation for stream reader classes and stream writer classes.
Important Methods Defined in the Locator Classes
●
GET_LENGTH ( )
Returns the length of the LOB in characters or bytes
●
FIND (start_offset = <off> pattern = <pat>)
Find first occurrence of pattern <pat> in string or xstring and begin the search at offset
<off>. Returns offset of find spot
●
GET_SUBSTRING(offset = <off> length = <length>)
Return substring beginning at offset <off> and having the length <length>
●
IS_CLOSED ( )
Check whether data stream is closed
●
CLOSE( )
Close data stream
488
© Copyright. All rights reserved.
Lesson: Accessing Large Objects (LOBs) on the Database
Locator Example – Copy BLOB Within Database
Figure 211: Locator Example – Copy BLOB Within Database
This figure Locator Example – Copy BLOB Within Database illustrates how a BLOB can be
read and duplicated within the database.
Disadvantages of Streams and Locators
The use of locators leads to higher resource consumption in the database system.
Additionally, locators are not yet supported by all databases. In such cases, the locators have
to be emulated from the database interface on the application server.
The use of data streams does not lead to increased resource consumption in the database
system, but data streams are somewhat more limited in their use. In particular, data streams
cannot be used if internal tables are being processed in the Open SQL statements.
LESSON SUMMARY
You should now be able to:
●
Explain streams and locators
© Copyright. All rights reserved.
489
Unit 6
Lesson 7
Using New Open SQL
LESSON OVERVIEW
This lesson discusses new Open SQL and explains the new syntax and how to use expressions
in Open SQL. It also describes the new possibilities for JOINs and other features that can
simplify the code.
Business Example
You want to simplify your code by using new Open SQL. To do so, you must familiarize
yourself with the new features. For this reason, you require the following knowledge:
●
An understanding of arithmetic and string expressions in new Open SQL
●
An understanding of JOINS in new Open SQL
●
An understanding of CASE expression in new Open SQL
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use the new Open SQL syntax
Previous Restrictions of Open SQL
Open SQL is a database abstraction layer with an SQL-like syntax. It defines a common SQL
semantic for all databases supported by SAP, (as opposed to being just a subset of SQL
commands common to all databases). This common semantic for all supported DBs ensures
that the result of an Open SQL query is independent of the underlying database.
However, in the past there were a long list of SQL-92 standard features, which were not
available in Open SQL. For example, Open SQL lacked expressions, had only limited JOIN
types, and did not support UNION or UNION ALL.
Luckily, as of SAP NetWeaver 7.40 SPS5, these limitations are minimized, because Open SQL
has been extended. These extensions, like the rest of Open SQL, are relevant regardless of the
database. (It is worth noting that one scenario where these extensions are of particular
importance is when we think about the performance guidelines for SAP HANA).
490
© Copyright. All rights reserved.
Lesson: Using New Open SQL
Figure 212: Previous Limitations of Open SQL
New Open SQL Syntax
Figure 213: Summary of New Open SQL Features and Syntax
To extend Open SQL, it was necessary to define a common semantic for the new features and
functionality. Once this had been settled, the new syntax was incorporated and the available
Open SQL syntax was enhanced.
© Copyright. All rights reserved.
491
Unit 6: ABAP Open SQL
In the figure Summary of New Open SQL Features and Syntax, you can see a summary of the
main features of the new syntax in Open SQL, along with a syntax example on the right-hand
side.
The first thing you might notice is the “@” symbol used to escape so-called host variables.
The ABAP system and language are considered the host of the embedded Open SQL, so the
term ‘host variable’ basically means an ABAP variable or constant inside an Open SQL
statement.
Remember the following:
●
Every host variable (except literals) should be escaped with a preceding “@” sign at every
position in the statement.
●
If one host variable is escaped, all host variables have to be escaped.
Moreover, a comma-separated list of fields can now be used.
In addition, Open SQL now supports the use of arithmetic and string expressions, as well as
conditional expressions like the CASE command shown in the second coding example.
Using the new Open SQL features has the following implications:
●
If you use any of these new features, you have to use the new syntax throughout your
statements. For example, the usage of arithmetic expressions and/or a comma-separated
field list implies the escaping of host variables with the “@” symbol.
●
The usage of the new Open SQL syntax implies a so-called strict mode, whereby nearly
everything that formerly resulted in a syntax warning now results in a syntax error in the
context of Open SQL commands.
Arithmetic and String Expressions in Open SQL
Figure 214: Arithmetic and String Expressions in New Open SQL
492
© Copyright. All rights reserved.
Lesson: Using New Open SQL
In Open SQL, not all arithmetic expressions are available for all types of variables.
Basic features like ADDITION, SUBTRACTION, MULTIPLICATION or the calculation of the
absolute value (ABS) are available for variables of type I and P (with and without decimals).
On the other hand, the MOD function is only available for variables of type I and type P without
decimals. The arithmetic expression CAST is only available for FLOAT-typed columns or host
variables, and FLOOR and CEIL can be used for all variables of type P with decimals (even
mixed with I- and P-types without decimals).
In addition to arithmetic expressions, Open SQL now also features string expressions, and
string concatenation using the && operator. Spaces are trimmed from columns and host
variables, unless you use an ABAP constant which contains exactly one space.
Joins in New Open SQL
Figure 215: Joins in New Open SQL
Another new possibility is the use of a RIGHT OUTER JOIN. It is similar to the LEFT OUTER
JOIN, but with switched roles for the LEFT and the RIGHT tables.
In addition to this, the limited support for using brackets in JOIN expressions with more than
two tables has been enhanced. Previously, the JOIN had to be performed left-to-right; that is,
the left-most tables always had to be joined first (left-bracketing). This limitation no longer
applies.
There is also new functionality with regard to the ON conditions of JOIN expressions, as
follows:
●
The previous restriction that a field of the right table is present in the ON condition has
been dropped.
●
Not only the “=” (equal) operator, but also operators like BETWEEN or greater than/less
than can be used in the ON condition now.
●
Fields of the right table can also be used in the WHERE clause of a LEFT OUTER JOIN
statement.
© Copyright. All rights reserved.
493
Unit 6: ABAP Open SQL
●
Implicit client handling in JOINs has been improved. If the tables on both sides of a JOIN
are client-dependent, the ON condition is enhanced automatically with a filter on equal
clients. Additionally, the client dependency is propagated to the top of the JOIN tree and
applied in the WHERE clause of the query statement. You don’t have to struggle with client
fields in JOINs any longer.
Beside these new features, two other restrictions have been removed:
●
The maximum number of tables supported in Open SQL JOIN clauses has been increased
to 50.
●
The maximum number of sub-queries supported in an Open SQL statement has been
increased from 9 to 50.
Other Features of New Open SQL
Figure 216: Existence Check in New Open SQL
Literals help determine faster if a record exists in a table. Using literals improves performance
for the cases where the number of matches is not important, as opposed to using an
aggregate function like COUNT(), which will scan all matching rows.
494
© Copyright. All rights reserved.
Lesson: Using New Open SQL
CASE Expression in New Open SQL
Figure 217: CASE Expression in New Open SQL
You can now use the very powerful CASE expression in Open SQL in the projection list. The
ELSE part is optional.
© Copyright. All rights reserved.
495
Unit 6: ABAP Open SQL
496
© Copyright. All rights reserved.
Unit 6
Exercise 24
Use New Open SQL Syntax and Features
Business Example
You want to simplify an ABAP report which displays flight booking and customer details.
Currently, once the data has been retrieved from the database, several additional pieces of
information, which are to be displayed in the report, need to be derived. You understand that
the options provided in New Open SQL allow you to determine all of the information required
in the output directly in the SELECT statement, and you decide to change your code
accordingly.
Template
BC402_DBT_NEWSQL
Solution
BC402_DBS_NEWSQL
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy the program BC402_DBT_NEWSQL and name it ZBC402_##_NEWSQL. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
2. Activate and test your program.
Edit the SELECT Statement
Edit the current SELECT statement so that the New Open SQL syntax is used instead.
1. Convert the SELECT to use a comma-separated field list, and escape any ABAP data
objects used in the statement with the @ symbol.
2. To ensure that the SELECT still works correctly, activate and test the program.
Change the SELECT Statement
Now make further changes to the SELECT statement, so that the data required for the output
is all retrieved and calculated in the SELECT statement, instead of being derived in the LOOP.
This means using a CASE expression to determine the customer type, an arithmetic
expression to perform the calculation of the total number of occupied seats, and a string
expression to concatenate the form with the customer’s name.
1. Comment out or remove the definition of the internal table GT_INITIAL, and the loop
where the records are processed.
© Copyright. All rights reserved.
497
Unit 6: ABAP Open SQL
2. Change the SELECT statement so that all required values are retrieved or derived directly
in the SELECT, and use the internal table GT_BOOKCUST as the direct target for the
SELECT.
3. Activate and test the program.
498
© Copyright. All rights reserved.
Unit 6
Solution 24
Use New Open SQL Syntax and Features
Business Example
You want to simplify an ABAP report which displays flight booking and customer details.
Currently, once the data has been retrieved from the database, several additional pieces of
information, which are to be displayed in the report, need to be derived. You understand that
the options provided in New Open SQL allow you to determine all of the information required
in the output directly in the SELECT statement, and you decide to change your code
accordingly.
Template
BC402_DBT_NEWSQL
Solution
BC402_DBS_NEWSQL
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy the program BC402_DBT_NEWSQL and name it ZBC402_##_NEWSQL. Familiarize
yourself with the program and how it works.
1. Copy the program and all its subcomponents.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program BC402_DBT_NEWSQL.
c) Choose Display.
d) Right-click BC402_DBT_NEWSQLand choose Copy....
e) In the Copy Program BC402_DBT_NEWSQLdialog box, in the Target program field,
enter ZBC402_##_NEWSQL and choose Copy.
f) In the Copy Program BC402_DBT_NEWSQL to ZBC402_##_NEWSQLdialog box,
select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Activate and test your program.
© Copyright. All rights reserved.
499
Unit 6: ABAP Open SQL
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Edit the SELECT Statement
Edit the current SELECT statement so that the New Open SQL syntax is used instead.
1. Convert the SELECT to use a comma-separated field list, and escape any ABAP data
objects used in the statement with the @ symbol.
a) Edit the SELECT statement as follows:
SELECT b~carrid,
b~connid,
b~fldate,
b~bookid,
c~id,
c~custtype,
c~form,
c~name,
f~seatsocc,
f~seatsocc_b
FROM sbook AS b
INNER JOIN scustom AS c
ON b~customid = c~id
INNER JOIN sflight AS f
ON b~carrid = f~carrid
AND b~connid = f~connid
AND b~fldate = f~fldate
INTO TABLE @gt_initial.
2. To ensure that the SELECT still works correctly, activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
Change the SELECT Statement
Now make further changes to the SELECT statement, so that the data required for the output
is all retrieved and calculated in the SELECT statement, instead of being derived in the LOOP.
This means using a CASE expression to determine the customer type, an arithmetic
expression to perform the calculation of the total number of occupied seats, and a string
expression to concatenate the form with the customer’s name.
1. Comment out or remove the definition of the internal table GT_INITIAL, and the loop
where the records are processed.
a) See the source code excerpt from the model solution.
2. Change the SELECT statement so that all required values are retrieved or derived directly
in the SELECT, and use the internal table GT_BOOKCUST as the direct target for the
SELECT.
a) See the source code excerpt from the model solution.
3. Activate and test the program.
a) Choose the Check button.
b) Choose the Activate button.
500
© Copyright. All rights reserved.
Lesson: Using New Open SQL
c) Choose the Direct Processingbutton.
Source code excerpt from the model solution:
*&----------------------------------------------------------------*
*& Report BC402_DBT_NEWSQL
*&
*&----------------------------------------------------------------*
*&
*&
*&----------------------------------------------------------------*
REPORT BC402_DBS_NEWSQL.
TYPES: BEGIN OF gty_bookcust,
carrid TYPE sbook-carrid,
connid TYPE sbook-connid,
fldate TYPE sbook-fldate,
bookid TYPE sbook-bookid,
id TYPE scustom-id,
cust_type TYPE string,
cust_name TYPE string,
no_occ_seats TYPE i,
END OF gty_bookcust.
DATA gt_bookcust TYPE TABLE OF gty_bookcust.
DATA gv_title type scrtext_m.
DATA: go_alv TYPE REF TO cl_salv_table,
go_cols TYPE REF TO cl_salv_columns_table,
go_col TYPE REF TO cl_salv_column_table.
CONSTANTS gc_space type c LENGTH 1 value ''.
SELECT b~carrid,
b~connid,
b~fldate,
b~bookid,
c~id,
CASE c~custtype
WHEN 'B' THEN 'BUSINESS'
WHEN 'P' THEN 'PRIVATE'
ELSE c~custtype
END,
c~form && @gc_space && c~name
name
( f~seatsocc + f~seatsocc_b +
"Total occ seats
FROM sbook AS b
INNER JOIN scustom AS c
ON b~customid = c~id
INNER JOIN sflight AS f
ON b~carrid = f~carrid
AND b~connid = f~connid
AND b~fldate = f~fldate
INTO TABLE @gt_bookcust.
"More meaningful code for
"customer type
as cust_name,
"Form followed by
f~seatsocc_f ) as no_occ_seats
TRY.
CALL METHOD cl_salv_table=>factory
*
EXPORTING
*
list_display
= IF_SALV_C_BOOL_SAP=>FALSE
*
r_container
=
© Copyright. All rights reserved.
501
Unit 6: ABAP Open SQL
*
container_name =
IMPORTING
r_salv_table
= go_alv
CHANGING
t_table = gt_bookcust.
CATCH cx_salv_msg .
ENDTRY.
* Set column headers for ALV
go_cols = go_alv->get_columns( ).
* Get each necessary column and set heading
go_col ?= go_cols->get_column( columnname = 'CUST_NAME' ).
gv_title = 'Customer Name'.
go_col->set_medium_text( gv_title ).
go_col ?= go_cols->get_column( columnname = 'CUST_TYPE' ).
gv_title = 'Customer Type'.
go_col->set_medium_text( gv_title ).
go_col ?= go_cols->get_column( columnname = 'NO_OCC_SEATS' ).
gv_title = 'Total Occ Seats'.
go_col->set_medium_text( gv_title ).
CALL METHOD go_alv->display.
502
© Copyright. All rights reserved.
Lesson: Using New Open SQL
LESSON SUMMARY
You should now be able to:
●
Use the new Open SQL syntax
© Copyright. All rights reserved.
503
Unit 6: ABAP Open SQL
504
© Copyright. All rights reserved.
Unit 6
Learning Assessment
1. Which of the following are tasks of the ABAP Open SQL interface?
Choose the correct answers.
X
A Translating ABAP Open SQL to native SQL
X
B Client handling, including the client in the WHERE condition
X
C Managing the SAP table buffer
X
D Forwarding static native SQL statements to the database of an AS ABAP.
2. If the buffering type Generic Buffering is chosen for a table in the ABAP Dictionary, the
generic area, which consists of the first n key fields of the table, must be defined.
Determine whether this statement is true or false.
X
True
X
False
3. The single record buffer is only read if the ________________ statement is used.
Choose the correct answer.
X
A UPDATE ONE
X
B SELECT SINGLE
X
C SELECT SOLO
X
D CREATE ONLY
4. During the buffer synchronization process, to determine whether data in buffered tables
has been changed, table __________ is read.
Choose the correct answer.
X
A TCURR
X
B DDLOG
X
C DD01L
X
D DD30L
© Copyright. All rights reserved.
505
Unit 6: Learning Assessment
5. When reading data from the database using cursors, the __________ statement defines
and executes the access, but does not pass any data on to the application program.
Choose the correct answer.
X
A FETCH
X
B OPEN CURSOR
X
C FETCH NEXT
6. Specifying the entire structure of a data object after the CORRESPONDING FIELDS OF
addition is a more robust alternative than specifying individual structure components.
Determine whether this statement is true or false.
X
True
X
False
7. The __________ operator is used in the where clause of a Select statement when you want
to compare the data with a single list of values.
Choose the correct answer.
X
A LIKE
X
B IN
X
C BETWEEN
X
D IS
8. When you process multiline result sets, you should read them into an internal table (array
fetch).
Determine whether this statement is true or false.
X
True
X
False
9. If the field list in a SELECT statement contains only aggregate expressions, the result will
consist of which of the following?
Choose the correct answer.
506
X
A A single line
X
B Multiple lines
X
C Either single or multiple lines
© Copyright. All rights reserved.
Unit 6: Learning Assessment
10. Two prerequisites of using the ORDER BY PRIMARY KEY addition to a select statement
are that the FROM clause must contain a single database table (no views or joins) and that
the field list after SELECT must contain all key fields of the table.
Determine whether this statement is true or false.
X
True
X
False
11. What is the name for the process by which secondary tables are accessed in a loop over
the records from a primary table?
Choose the correct answer.
X
A Nested SELECT
X
B Looped SELECT
X
C Iterative SELECT
X
D Repeat SELECT
12. _____________ corresponds to the result set that only considers the records from the
outer table for which suitable data records exist in the inner table.
Choose the correct answer.
X
A LEFT OUTER JOIN
X
B INNER JOIN
X
C OUTER JOIN
13. A SELECT statement with a subquery has a more restricted syntax than a SELECT
statement without a subquery.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
507
Unit 6: Learning Assessment
14. Which of the following techniques in a Select statement should be used when you want to
create a join between an internal table and a database table?
Choose the correct answer.
X
A Select with for all entries
X
B Select with Inner Join
X
C Select with Outer Join
X
D Select with Read table
15. To read large data volumes, you should use _______________ only in exceptional cases.
Choose the correct answer.
X
A SELECT
X
B SELECT SINGLE
X
C FOR ALL ENTRIES
16. You can link an instance of class CL_ABAP_DB_X_READER to a ________ located on a
database table.
Choose the correct answer.
X
A Large binary string
X
B Large string
X
C SELECT statement
17. When using the new Open SQL syntax, all host variables must be escaped using which
character?
Choose the correct answer.
508
X
A !
X
B /
X
C @
X
D :
© Copyright. All rights reserved.
Unit 6
Learning Assessment - Answers
1. Which of the following are tasks of the ABAP Open SQL interface?
Choose the correct answers.
X
A Translating ABAP Open SQL to native SQL
X
B Client handling, including the client in the WHERE condition
X
C Managing the SAP table buffer
X
D Forwarding static native SQL statements to the database of an AS ABAP.
2. If the buffering type Generic Buffering is chosen for a table in the ABAP Dictionary, the
generic area, which consists of the first n key fields of the table, must be defined.
Determine whether this statement is true or false.
X
True
X
False
3. The single record buffer is only read if the ________________ statement is used.
Choose the correct answer.
X
A UPDATE ONE
X
B SELECT SINGLE
X
C SELECT SOLO
X
D CREATE ONLY
© Copyright. All rights reserved.
509
Unit 6: Learning Assessment - Answers
4. During the buffer synchronization process, to determine whether data in buffered tables
has been changed, table __________ is read.
Choose the correct answer.
X
A TCURR
X
B DDLOG
X
C DD01L
X
D DD30L
5. When reading data from the database using cursors, the __________ statement defines
and executes the access, but does not pass any data on to the application program.
Choose the correct answer.
X
A FETCH
X
B OPEN CURSOR
X
C FETCH NEXT
6. Specifying the entire structure of a data object after the CORRESPONDING FIELDS OF
addition is a more robust alternative than specifying individual structure components.
Determine whether this statement is true or false.
X
True
X
False
7. The __________ operator is used in the where clause of a Select statement when you want
to compare the data with a single list of values.
Choose the correct answer.
510
X
A LIKE
X
B IN
X
C BETWEEN
X
D IS
© Copyright. All rights reserved.
Unit 6: Learning Assessment - Answers
8. When you process multiline result sets, you should read them into an internal table (array
fetch).
Determine whether this statement is true or false.
X
True
X
False
9. If the field list in a SELECT statement contains only aggregate expressions, the result will
consist of which of the following?
Choose the correct answer.
X
A A single line
X
B Multiple lines
X
C Either single or multiple lines
10. Two prerequisites of using the ORDER BY PRIMARY KEY addition to a select statement
are that the FROM clause must contain a single database table (no views or joins) and that
the field list after SELECT must contain all key fields of the table.
Determine whether this statement is true or false.
X
True
X
False
11. What is the name for the process by which secondary tables are accessed in a loop over
the records from a primary table?
Choose the correct answer.
X
A Nested SELECT
X
B Looped SELECT
X
C Iterative SELECT
X
D Repeat SELECT
© Copyright. All rights reserved.
511
Unit 6: Learning Assessment - Answers
12. _____________ corresponds to the result set that only considers the records from the
outer table for which suitable data records exist in the inner table.
Choose the correct answer.
X
A LEFT OUTER JOIN
X
B INNER JOIN
X
C OUTER JOIN
13. A SELECT statement with a subquery has a more restricted syntax than a SELECT
statement without a subquery.
Determine whether this statement is true or false.
X
True
X
False
14. Which of the following techniques in a Select statement should be used when you want to
create a join between an internal table and a database table?
Choose the correct answer.
X
A Select with for all entries
X
B Select with Inner Join
X
C Select with Outer Join
X
D Select with Read table
15. To read large data volumes, you should use _______________ only in exceptional cases.
Choose the correct answer.
512
X
A SELECT
X
B SELECT SINGLE
X
C FOR ALL ENTRIES
© Copyright. All rights reserved.
Unit 6: Learning Assessment - Answers
16. You can link an instance of class CL_ABAP_DB_X_READER to a ________ located on a
database table.
Choose the correct answer.
X
A Large binary string
X
B Large string
X
C SELECT statement
17. When using the new Open SQL syntax, all host variables must be escaped using which
character?
Choose the correct answer.
X
A !
X
B /
X
C @
X
D :
© Copyright. All rights reserved.
513
Unit 6: Learning Assessment - Answers
514
© Copyright. All rights reserved.
UNIT 7
Analysis and Testing
Lesson 1
Defining and Activating Checkpoints
Exercise 25: Define and Activate Checkpoints
516
523
Lesson 2
Using the ABAP Trace
530
Lesson 3
Using the SQL Trace
536
UNIT OBJECTIVES
●
Define checkpoints
●
Activate checkpoints
●
Use the ABAP trace
●
Use the SQL trace
© Copyright. All rights reserved.
515
Unit 7
Lesson 1
Defining and Activating Checkpoints
LESSON OVERVIEW
This lesson shows how conditional assertions can be used.
In addition, the lesson shows how to group breakpoints and assertions and activate or
deactivate them together. Logpoints are also discussed in this lesson.
Business Example
Your company is implementing a major ABAP development project, and you are responsible
for developing a reliable ABAP application for the project team. You want to use assertions
and breakpoints to ensure that the ABAP application responds correctly and has stability.
For this reason, you require the following knowledge:
●
An understanding of how to plan the correctness of your ABAP programs
●
An understanding of how to improve the maintainability of ABAP coding
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Define checkpoints
●
Activate checkpoints
Checkpoints
Checkpoints define places in a program where the program state is tested during execution.
Checkpoints are marked with special statements in the source code. Checkpoints can be
made activatable by assigning them to a checkpoint group.
ABAP supports the following types of checkpoints:
●
Breakpoints
The BREAK-POINT statement defines an unconditional checkpoint. When the program
execution reaches an active breakpoint, the program flow is interrupted and the Debugger
starts. You can activate breakpoints and create them without assignment to a checkpoint
group.
●
Assertions
The ASSERT statement defines a conditional checkpoint. It is always linked with a logical
condition. When an active assertion is reached, the system checks the logical condition. If
the condition is not true, the assertion is violated and the system terminates the program
with a runtime error or dump. If assigned to a checkpoint group, you can select a different
response for violated assertions.
516
© Copyright. All rights reserved.
Lesson: Defining and Activating Checkpoints
Note:
Assertions are available in SAP Web AS 6.20 and later versions.
●
Logpoints
The LOG-POINT statement defines an unconditional checkpoint that serves merely to log
when execution reaches a certain point in the source code. A logpoint never interrupts or
terminates a program. Logpoints must always be assigned to a specific checkpoint group,
which means they can always be activated.
Note:
Logpoints are available in SAP Web AS 6.40 and later versions.
The ASSERT, BREAK-POINT, and LOG-POINT statements for defining checkpoints do not
have any effect on the way the program operates. You use them exclusively for test purposes.
Breakpoints
You can start the Debugger when an ABAP program is executed by creating a breakpoint.
Breakpoints are places in the program that instruct the ABAP runtime processor to interrupt
program execution at a specific place in the source text. The Debugger is not activated until
one of these positions are reached. To set a static breakpoint, use the BREAK-POINT ABAP
keyword. Set the breakpoint at the line where you want to interrupt the program.
Note:
In contrast to static breakpoints that are a part of the source code, you can also
set dynamic breakpoints. Dynamic breakpoints are user-specific and they are set
in the ABAP Debugger.
Facts about the BREAK-POINT Statement
●
It pauses processing and switches to the Debugger.
●
It has no influence on the program.
●
It is always passed.
●
It is unconditional.
When you start the program, the ABAP processor interrupts it when it reaches the
breakpoint. You can identify the breakpoints more easily if you number them, for example,
BREAK-POINT 1 or BREAK-POINT 2. Static breakpoints are always independent of the user
without specifying the user name. The program is always interrupted as soon as the runtime
processor reaches the line containing the breakpoint, regardless of which user executes the
program. You can also set user-specific static breakpoints. To do this, enter the BREAK
<user name> statement.
It is essential to remove static breakpoints from a program before you transport it to a
production system. The extended program check is helpful here. It displays an error message
if the program in question contains static breakpoints.
© Copyright. All rights reserved.
517
Unit 7: Analysis and Testing
In SAP Web AS 6.10 and later versions, you can use activatable breakpoints in your programs.
Their use increases maintainability.
Caution:
If you do not remove static breakpoints from your program, they are transported
to your production system. This can affect users in the production system.
Assertions
In order to debug and analyze complex programs, you can implement breakpoints and
assertions. Assertions verify certain assumptions about the program state at a specific place
in the program, and ensure that these assumptions are fulfilled. A new ABAP statement,
ASSERT, was introduced by SAP for this purpose. The syntax of ASSERT is ASSERT
<log_expr>.
Program Behavior of the ASSERT Statement
●
Logical expression is evaluated.
●
Program continues if result is true.
●
Runtime error occurs if result is false.
Advantages of Assertions
Figure 218: Advantages of Assertions
If the logical expression is not fulfilled, the assertion is violated, and a runtime error is raised.
In contrast to an IF query, the ASSERT statement is shorter, its purpose is directly
recognizable, and it is activatable.
Assertions help you check whether the program flow is progressing the way that is intended.
The program reacts if its results, or interim results, lie outside of a range of expected values.
518
© Copyright. All rights reserved.
Lesson: Defining and Activating Checkpoints
An Example of a Method where Assertion is Used
The following code is an example of a method where an assertion could be used:
CLASS cl DEFINITION.
...
CLASS-METHODS find_item IMPORTING item_key
TYPE ty_key
RETURNING value(item) TYPE ty_item.
...
ENDCLASS.
CLASS cl IMPLEMENTATION.
...
METHOD find_item.
READ TABLE item_table INTO item
WITH KEY table_key = item_key.
ENDMETHOD.
...
ENDCLASS.
...
my_item = cl=>find_item( item_key = my_key ).
The method call returns a table line for a specified key. The method itself uses an assertion to
check whether a key was actually passed on.
An Example of How to Verify Assertions
The following code shows the use of assertions in the method:
...
METHOD find_item.
ASSERT item_key >= 1 AND
item_key <= LINES( item_table ).
READ TABLE item_table INTO item
WITH KEY table_key = item_key.
ASSERT item is not initial.
ENDMETHOD.
...
my_item = cl=>find_item( item_key = my_key ).
Before the method ends, the system checks whether or not an entry is actually found in the
internal table.
Exceptions and assertions play complementary roles. Exceptions handle unexpected
conditions, while assertions are suitable for handling incorrect application states.
If a check using assertions is performance-intensive, it makes sense to run the assertion in
the development and test systems but skip it in the production system as it has been already
tested enough by this point. Activatable assertions and breakpoints are available for this
purpose.
Activatable Checkpoints
You can design assertions and breakpoints which, instead of being unconditional, are only
analyzed by the system under certain circumstances. To do so, assign a checkpoint group to
the BREAK-POINT and ASSERT statements by using the ID addition.
© Copyright. All rights reserved.
519
Unit 7: Analysis and Testing
Table 16: Checkpoint Types
The following are the different types of checkpoint:
Checkpoints
Always Active
Can Be Activated
Breakpoint
BREAK-POINT
BREAK-POINT
ID <grp>
Assertion
ASSERT
ASSERT
<log_expr>
ID
<group>
FIELDS
<f1> … <fn>
CONDITION
<log_expr>
Logpoints
LOG-POINT
Not possible
ID
<group>
FIELDS
<f1> … <fn>
Use the BREAK-POINT ID <GROUP> or ASSERT ID <GROUP> statement to assign a
checkpoint group. The checkpoint group determines whether the breakpoint or assertion is
active or not.
The LOG-POINT statement is always used with the ID addition.
Checkpoint Groups
Figure 219: Transaction SAAB Initial Screen for Checkpoint Group Maintenance
Checkpoint groups represent a new type of Repository object. They can be created in the
Object Navigator, or in transaction SAAB (be sure to observe the naming convention).
To create checkpoint groups directly in transaction SAAB, perform the following steps:
1. Start transaction code SAAB. The initial screen appears.
2. Give the checkpoint group a name and choose
520
(Create).
© Copyright. All rights reserved.
Lesson: Defining and Activating Checkpoints
3. Enter a short text and save the checkpoint group. Then maintain the settings for activating
and deactivating checkpoints in the next screen.
Note:
A checkpoint group is a repository object. Thus, the name has to be chosen in the
customer name space.
Maintenance Screen of Transaction SAAB
Figure 220: Maintenance Screen of Transaction SAAB
You can activate and deactivate breakpoints and logpoints in the maintenance screen of
transaction SAAB.
When the system encounters an active breakpoint during program execution, program
execution is interrupted and it calls the Debugger automatically. When the system encounters
an active logpoint, this is recorded in the log of the assigned checkpoint group.
States of Assertions
Table 17: States of Assertions
The possible states of assertions are as follows:
State of Assertion
Description
Inactive
Assertion is ignored or not processed.
Break
The system starts the Debugger if the logical
expression is false.
Log
If the expression is false, a log entry is written.
© Copyright. All rights reserved.
521
Unit 7: Analysis and Testing
State of Assertion
Description
Abort
If the expression is false, a runtime error is
raised.
Different Activation Modes for Activatable Checkpoints
Figure 221: Different Activation Modes for Activatable Checkpoints
For logpoints and logged assertions, the content of any data objects (except for reference
variables) can be stored in the log. Here you use the supplement FIELDS in the ASSERT
statement. If Abort has been set for assertions, the system displays the content of the first
eight data objects that are listed behind FIELDS in the generated short dump.
522
© Copyright. All rights reserved.
Unit 7
Exercise 25
Define and Activate Checkpoints
Business Example
You need to include specific tests in your application, which splits a data string into
appropriately typed components.
To do this, you must define activatable assertions and breakpoints in the application.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy program BC402_IDS_DATA_SET (or your own program, ZBC402_##_DATA_SET) to
ZBC402_##_CHECKPOINTS. Insert assertions in your application to make it more reliable.
This helps you detect error states sooner.
1. Copy the program.
2. Add three assertions to your application. After the function module call, make sure the
returned data string is not INITIAL. After the data string is moved two places to the left,
make sure the first character is not “#”. After the identically named fields in the flight
structure are filled, make sure the flight date lies in the future.
Create a Checkpoint Group
Create a checkpoint group (suggested name: ZBC402_##).
1. Create a checkpoint group and enter a descriptive short text.
2. Configure the settings such that nothing happens when an activatable breakpoint is
reached, and processing is interrupted when an activatable assertion is reached (if the
program runs in the background, only a log entry should be written).
3. Adjust all assertions in the program, so that they are controlled using your checkpoint
group.
4. Adjust the third assertion in such a way that, when you create a log entry, the flight date is
also written in the log.
5. Run the program and check the system reaction.
6. Change the settings of the checkpoint group so the assertions are now logged.
7. Start the program again and check the activation log.
© Copyright. All rights reserved.
523
Unit 7
Solution 25
Define and Activate Checkpoints
Business Example
You need to include specific tests in your application, which splits a data string into
appropriately typed components.
To do this, you must define activatable assertions and breakpoints in the application.
Note:
In the exercises for this course, when the input values include ##, replace ## with
your group number.
Copy Template Program
Copy program BC402_IDS_DATA_SET (or your own program, ZBC402_##_DATA_SET) to
ZBC402_##_CHECKPOINTS. Insert assertions in your application to make it more reliable.
This helps you detect error states sooner.
1. Copy the program.
a) To start the Object Navigator, enter transaction code se80.
b) In the unnamed dropdown menu on the left of the screen, choose Program and specify
the name of the program ZBC402_##_DATA_SET.
c) Choose Display.
d) Right-click ZBC402_##_DATA_SETand choose Copy....
e) In the Copy Program ZBC402_##_DATA_SETdialog box, in the Target program field,
enter ZBC402_##_CHECKPOINTS and choose Copy.
f) In the Copy Program ZBC402_##_DATA_SET to ZBC402_##_CHECKPOINTSdialog
box, select all checkboxes and choose Copy.
g) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Add three assertions to your application. After the function module call, make sure the
returned data string is not INITIAL. After the data string is moved two places to the left,
make sure the first character is not “#”. After the identically named fields in the flight
structure are filled, make sure the flight date lies in the future.
a) See the source code excerpt from the model solution.
Create a Checkpoint Group
Create a checkpoint group (suggested name: ZBC402_##).
1. Create a checkpoint group and enter a descriptive short text.
524
© Copyright. All rights reserved.
Lesson: Defining and Activating Checkpoints
a) To return to the SAP Easy Access screen, choose Back.
b) Enter transaction code SAAB.
c) In the Checkpoint Grouppanel, in the Name field, enter ZBC402_## and choose Create.
d) In the Create Checkpoint Groupdialog box, in the Description field, enter a meaningful
short text and choose Continue.
e) In the Create Object Directory Entrydialog box, in the Package field, enter ZBC402_##
and choose Save.
2. Configure the settings such that nothing happens when an activatable breakpoint is
reached, and processing is interrupted when an activatable assertion is reached (if the
program runs in the background, only a log entry should be written).
a) In the Change Checkpoint Groupwindow, in the Assertions (Foreground)panel, select
the Break radio button.
b) In the Activation for Background Processingdialog box, select the Log radio button and
choose Continue.
c) Choose Back.
d) In the Change Checkpoint Groupdialog box, choose Yes.
e) In the Maximum Validity Period of the Activationdialog box, choose Continue.
3. Adjust all assertions in the program, so that they are controlled using your checkpoint
group.
a) See the source code excerpt from the model solution.
4. Adjust the third assertion in such a way that, when you create a log entry, the flight date is
also written in the log.
a) See the source code excerpt from the model solution.
5. Run the program and check the system reaction.
a) Choose the Check button.
b) Choose the Activate button.
c) Choose the Direct Processingbutton.
6. Change the settings of the checkpoint group so the assertions are now logged.
a) To return to the SAP Easy Access screen, choose Back.
b) Enter transaction code SAAB.
c) In the Checkpoint Grouppanel, in the Name field, enter ZBC402_## and choose
Change.
d) In the Change Checkpoint Groupwindow, in the Assertions (Foreground)panel, select
the Log radio button.
e) Choose Back.
f) In the Change Checkpoint Groupdialog box, choose Yes.
g) In the Maximum Validity Period of the Activationdialog box, choose Continue.
7. Start the program again and check the activation log.
© Copyright. All rights reserved.
525
Unit 7: Analysis and Testing
a) To return to the SAP Easy Access screen, choose Back three times.
b) In SE80, run program ZBC402_##_CHECKPOINTS.
c) To return to the SAP Easy Access screen, choose Back three times.
d) Enter transaction code SAAB.
e) In the Checkpoint Grouppanel, in the Name field, enter ZBC402_## and choose
Change.
f) Choose the Log tab.
g) If there are log entries, open the tree and display the details for an entry (the Display
details button or corresponding entry in the context menu for the log entry).
Source code excerpt from the model solution:
REPORT
bc402_cps_checkpoints MESSAGE-ID bc402.
TYPES:
BEGIN OF ty_s_flight_c,
mandt
TYPE c LENGTH
carrid
TYPE c LENGTH
connid
TYPE n LENGTH
fldate
TYPE n LENGTH
price
TYPE c LENGTH
currency
TYPE c LENGTH
planetype TYPE c LENGTH
seatsmax
TYPE n LENGTH
seatsocc
TYPE n LENGTH
paymentsum TYPE c LENGTH
seatsmax_b TYPE n LENGTH
seatsocc_b TYPE n LENGTH
seatsmax_f TYPE n LENGTH
seatsocc_f TYPE n LENGTH
END OF ty_s_flight_c,
3,
3,
4,
8,
20,
5,
10,
10,
10,
22,
10,
10,
10,
10,
BEGIN OF ty_s_flight,
carrid
TYPE sflight-carrid,
connid
TYPE sflight-connid,
fldate
TYPE sflight-fldate,
price
TYPE sflight-price,
currency
TYPE sflight-currency,
planetype TYPE sflight-planetype,
seatsmax
TYPE sflight-seatsmax,
seatsocc
TYPE sflight-seatsocc,
END OF ty_s_flight.
DATA:
gv_datastring
gv_set_string
gv_offset
gs_flight_c
gs_flight
TYPE
TYPE
TYPE
TYPE
TYPE
string,
string,
i,
ty_s_flight_c,
ty_s_flight.
START-OF-SELECTION.
* retrieve character string with data
CALL FUNCTION 'BC402_CREATE_SEP_STRING'
526
© Copyright. All rights reserved.
Lesson: Defining and Activating Checkpoints
*
*
*
*
*
EXPORTING
im_number
= '1'
im_table_name = 'SFLIGHT'
im_separator = '#'
im_unique
= 'X'
IMPORTING
ex_string
= gv_datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038.
ENDIF.
* make sure the string is filled
*- - - - - - - - - - - - - - - - - -- - - - - - - - - -*
ASSERT ID
zbc402_##
CONDITION gv_datastring IS NOT INITIAL.
* remove leading and trailing separators
*--------------------------------------------------------*
* solution 1 - SHIFT, FIND & Offset access
gv_set_string = gv_datastring.
SHIFT gv_set_string BY 2 PLACES.
FIND '##' IN gv_set_string
MATCH OFFSET gv_offset.
IF sy-subrc = 0.
gv_set_string = gv_set_string(gv_offset).
ENDIF.
* solution 2 - REPLACE
* gv_set_string = gv_datastring.
* REPLACE ALL OCCURRENCES OF '##'
*
IN gv_set_string WITH ''.
* solution 3 - SHIFT CIRCULAR & SHIFT
* gv_set_string = gv_datastring.
* SHIFT gv_set_string RIGHT CIRCULAR BY 2 PLACES.
* SHIFT gv_set_string LEFT BY 4 PLACES.
*
* solution 4 - SHIFT DELETING
* gv_set_string = gv_datastring.
* SHIFT gv_set_string LEFT DELETING LEADING '#'.
* SHIFT gv_set_string RIGHT DELETING TRAILING '#'.
* SHIFT gv_set_string LEFT DELETING LEADING ' '.
* make sure first character is not '#'
*- - - - - - - - - - - --- - - - - - - - - - - - - - - -*
ASSERT ID
zbc402_##
CONDITION gv_set_string(1) <> '#'.
* split into (charlike) fragments corresponding components
SPLIT gv_set_string AT '#' INTO
gs_flight_c-mandt
gs_flight_c-carrid
gs_flight_c-connid
gs_flight_c-fldate
gs_flight_c-price
gs_flight_c-currency
gs_flight_c-planetype
gs_flight_c-seatsmax
gs_flight_c-seatsocc
gs_flight_c-paymentsum
gs_flight_c-seatsmax_b
© Copyright. All rights reserved.
527
Unit 7: Analysis and Testing
gs_flight_c-seatsocc_b
gs_flight_c-seatsmax_f
gs_flight_c-seatsocc_f.
* convert fragments into proper data types
MOVE-CORRESPONDING gs_flight_c TO gs_flight.
* make sure flight date not in the past
* (will not always be the case)
*--------------------------------------------------*
ASSERT ID
zbc402_##
FIELDS
gs_flight-fldate
CONDITION gs_flight-fldate > sy-datum.
* output result
WRITE:
/
gs_flight-carrid,
gs_flight-connid,
gs_flight-fldate DD/MM/YYYY,
gs_flight-price CURRENCY gs_flight-currency,
gs_flight-currency,
gs_flight-planetype,
gs_flight-seatsmax,
gs_flight-seatsocc.
528
© Copyright. All rights reserved.
Lesson: Defining and Activating Checkpoints
LESSON SUMMARY
You should now be able to:
●
Define checkpoints
●
Activate checkpoints
© Copyright. All rights reserved.
529
Unit 7
Lesson 2
Using the ABAP Trace
LESSON OVERVIEW
This lesson describes how you can improve the performance of your ABAP applications by
using the ABAP trace for runtime analysis. The purpose of the lesson is to teach you how to
run the tool and interpret the results to get the best performance from your applications.
Business Example
You want to improve the performance of your ABAP applications by using the ABAP trace for
runtime analysis. To do so, you must familiarize yourself with the tool. For this reason, you
require the following knowledge:
●
An understanding of the ABAP trace and the ABAP trace execution
●
An understanding of the various options for using variants to restrict a trace
●
An understanding of the various ways of evaluating trace results
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use the ABAP trace
The ABAP Trace
Analyzing the runtime behavior of your ABAP applications can be very helpful when
performance is an issue.
One of the tools to perform such a runtime analysis is the ABAP Trace (transaction code SAT),
which replaces the older Runtime Analysis (SE30).
Please note the following:
●
Both tools let you locate the source code blocks in your program that are responsible for
poor performance and tune them accordingly.
●
Both tools measure runtime of processing blocks (methods, functions, subroutines) or
single statements.
●
No database-specific functions are available.
If you are already familiar with the former ABAP Runtime Analysis Tool, transaction SE30, you
will find that transaction SAT has been enhanced with effective new analysis tools and
features.
530
© Copyright. All rights reserved.
Lesson: Using the ABAP Trace
Note:
The ABAP Trace makes it possible to take detailed measurements of the runtime
requirements of your programs. However, the measurement results also depend
on the current system and network load, as well as the active table buffer and
dataset. Because the analysis is usually carried out in development and test
systems, you have to qualify the results accordingly.
SAT offers benefits such as a modern state-of-the art user interface, new analysis tools and
easy navigation between tools.
Additional features include the following:
●
In the old SE30, internal tables were identified only by their internal names (IT_<nn>). SAT
can determine and show the real names of internal tables for the trace measurement
results.
●
SAT stores traces in the database. That means that you can display a trace from any
application server in the system (in SE30 only traces of the current application server are
visible). You can also keep traces for a longer time (in SE30 traces older than one week are
deleted to save file system space). When you display a trace measurement result the first
time (for example, when you double-click it on the Evaluate tab), it is formatted and written
to the database.
ABAP Trace Execution
Starting a trace measurement in SAT is quite similar to starting one in transaction SE30.
You can maintain trace conditions and restrictions in a variant. Variants are used to ensure
the trace data you need while keeping extraneous data and storage use to a minimum.
When creating a variant, a screen with the following three tabs appears: Duration and type,
Statements and Program Components. If you do not specify an explicit variant for a
measurement, the system uses the standard variant, named DEFAULT. It makes sense to
restrict them as much as possible in order to not reach the maximum trace file size,
particularly when you expect long running trace measurements.
© Copyright. All rights reserved.
531
Unit 7: Analysis and Testing
Figure 222: Conducting an ABAP Trace
Using Variants to Restrict a Trace
The following are some suggestions for using variants to restrict a trace:
●
When running a trace for performance measurement use Per Call Position aggregation to
get one trace entry for all similar calls. If, for example, the same method gets called 10
times, only one entry will be created in the trace file, which would contain 10 as number of
the hits and the sum of the runtimes of the hits. Without aggregation 10 entries with
runtimes will be written into the trace file, which results in a larger trace file.
Note:
If you run a trace to follow the program flow of your application, use the
aggregation option None to get a call hierarchy in the trace.
532
●
Use the Explicit Switching on and Off of Measurementoption to switch on/off the trace only
where you need it, for example if you are interested in a special part of a transaction
(between screen 3 and 4). This option allows you to switch on/off the trace during the
runtime of the ABAP program. You also must activate Limitation on Program Components
on the Program Componentstab. The trace will start as soon as you enter /RON (trace on)
in the OK code field in the transaction. With /ROFF (trace off), the trace is stopped.
Alternatively, you can choose: System → Utilities → Runtime Analysis → Switch On/Switch
Off.
●
Don't trace everything - restrict the statements. Remember that about 40% of all trace
records belong to the operations on internal tables, so do not record statements on
internal tables unless you really need to, as they will increase the size of the trace file.
Instead, you could trace, for example, only Processing Blocksin a first execution to find out
the relevant parts of code, and then in a second execution, trace most (or even all)
© Copyright. All rights reserved.
Lesson: Using the ABAP Trace
statements of the Statements tab, but specifying only the relevant code (programs,
classes, function groups, and so on) on the Program Componentstab.
●
Explicitly name your programs/classes/functions, and so on, on the Program Components
tab if you know beforehand which parts of the code you want to trace. You can even
specify which sub elements (like a subroutine, function of a function group, a method of a
class, and so on) should be traced.
After creating the measurement variant, you can run the trace. Enter the name of your
transaction (or program, or function module) into the field in the In Dialog area on the initial
screen and then choose the Execute button.
Note:
If you used Explicit Switching on and Off of Measurementoption in your variant to
switch the trace on or off only where you really need it, you have to activate the
trace after your ABAP program is running. Enter /RON (trace on) command in the
OK code field in your transaction.
Trace Results Evaluation
After the trace measurement has been executed, the trace results can be analyzed. Choose
the Evaluate tab on the initial screen of transaction SAT, find your trace result and doubleclick it. Transaction SAT can also display trace results immediately after trace execution if you
select the Eval. Immediately checkbox on the initial screen.
Certain measurements in the results display are specified in gross and net figures. The gross
figure is the total runtime for the respective action, while the net figure only contains the
share of the gross time that is not identified separately as a sub-action runtime.
The results are displayed in a number of desktops (similar to the new ABAP Debugger). You
can set up each desktop as you wish, with up to four trace evaluation tools. By default
Desktop 1 presents tools for analyzing performance and Desktop 2 shows tools for analyzing
program flow.
Tools
The tools that can be displayed on the different desktops are as follows:
●
Hit List Tool
Displays a hit list of all measured statements. Identical events are summarized into one
trace line together with their execution times. But identical events from different calling
positions in the source code appear as different entries in the hit list.
●
Call Hierarchy Tool
Displays operations and events as they occur in a program.
●
Profile Tool
Shows you the runtime distribution of components, packages, programs and even
debugger layers.
●
Processing Blocks Tool
Displays a tree of processing blocks to provide an aggregated view on the call sequence.
●
Call Stack
© Copyright. All rights reserved.
533
Unit 7: Analysis and Testing
Displays the call stack for each item in the call hierarchy.
●
Database Tables Tool
Identifies time-consuming database accesses.
●
Times Tool
Displays more specific time measurement values for the single events of the call hierarchy.
ABAP Trace Results
Figure 223: ABAP Trace Results
Depending on what you are trying to analyze, use the following tools:
●
To measure performance, use the Profile tool in combination with the Hit List tool.
The benefit of the Profile tool is that you can start a trace evaluation and drill down through
the trace results view through the sub-components and their packages to follow up on the
top performance consumers. Afterwards, you can display the subarea of a detected
performance consumer in the Hit List tool to analyze its trace events. It saves time and a
transparent hit list appears which is easier to understand.
●
To analyze program flow, use the Call Hierarchy tool in combination with the Call Stack
and Processing Blocks tools.
You can use the call hierarchy to display trace events the way they were called by the
program. Since the display of the call hierarchy is a little large, you can display a call stack
for a chosen event of the call hierarchy or just choose the event and position its display in
the Processing Blocks tool. There you will see all processing blocks (methods, functions,
and so on) that you configured in your trace measurement variant and can better follow
the call hierarchy of the trace event and even display the critical processing blocks in
terms of consumed runtime or memory.
●
To display detailed information on runtimes in the call hierarchy, use the Times tool.
The Times tool shows a distribution of runtimes across non-system and system programs.
534
© Copyright. All rights reserved.
Lesson: Using the ABAP Trace
●
Identify time-consuming database operations and accesses to buffered tables with the
Database Tables tool.
By using the easy navigation of SAT, you can display the subarea in the detailed Hit List
tool to follow the runtime distribution of database accesses, or position in the call
hierarchy (and, for example, display a call stack) to follow the callers of the database
access.
Hint:
In the initial screen of the runtime analysis, you can choose Tips & Tricks to
display a demonstration environment that contains useful performance tips and
illustrates the benefits of different source codes by comparing their runtimes.
These tips can help you replace the statements that the runtime analysis has
identified as performance intensive with other statements that give better
performance.
LESSON SUMMARY
You should now be able to:
●
Use the ABAP trace
© Copyright. All rights reserved.
535
Unit 7
Lesson 3
Using the SQL Trace
LESSON OVERVIEW
This lesson discusses how you can improve the performance of your ABAP applications by
using the SQL trace. It describes the functions and features of the SQL trace, including how
the system translates ABAP OPEN SQL commands into standard SQL commands and the
indices used in an SQL statement.
Business Example
You want to improve the performance of your ABAP applications by using the SQL trace. To
do so, you must familiarize yourself with the functions and features of the SQL trace. For this
reason, you require the following knowledge:
●
An understanding of SQL trace execution and SQL trace list analysis
●
An understanding of the display execution plan function
●
An understanding of identical SQL statements
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Use the SQL trace
SQL Trace Execution
The SQL trace allows you to precisely analyze and track the database accesses that the
database interface in the SAP system initiates. This makes the trace an effective tool for
performance analysis. To start the SQL performance trace, enter transaction code ST05 or
choose System → Utilities → Performance Trace.
536
© Copyright. All rights reserved.
Lesson: Using the SQL Trace
Figure 224: SQL Trace: Initial Screen and Overview
Before you activate the SQL trace for a program or transaction, you should execute that
program or transaction once first, to avoid recording the refresh operations for the table
buffer related to the SAP system, program buffer, and so on. You can also activate the trace in
a production system, because it does not cause any errors or inconsistencies. You can
restrict the SQL performance trace to any user and any single object. However, you should
ensure that the user being recorded is not working in an additional session and that no other
processing forms (batch processing, update tasks) are running in parallel under the same
user on the same application server. If there are, the SQL performance trace is unreadable.
Hint:
Each application server only has one active trace file. As a result, the trace can
only be activated for one user on each application server. The standard size of
the trace file is 800K. We recommend increasing the size of the trace file to 16
MB (parameter rstr/max_filesize_MB = 16 384 000).
From the recorded SQL trace you can deduce the following:
●
Which SQL statements your application carries out
●
Which values the system uses for specific database accesses and changes
●
How the system translates ABAP OPEN SQL commands (such as SELECT) into standard
SQL commands
●
Where your application positions COMMIT statements
●
Where your application makes repeated database accesses
●
What database accesses or changes occur in the update section of your application
© Copyright. All rights reserved.
537
Unit 7: Analysis and Testing
SQL Trace List Analysis
There are slight differences in the trace list between the different database systems.
The columns in the expanded trace list have the following meanings:
●
Duration
Duration of the database operation in microseconds (depends on the system load)
●
Object name
Name of the table/ the view from the SQL statement
●
Records
Number of data records that the database operation supplies
●
Statement
Text of the observed SQL statement
Figure 225: SQL Trace List
The Display Execution Plan Function
From the main trace file, if you select a SQL statement from the trace list and choose the
Display Execution Planbutton, the execution plan for that statement will be displayed.
Caution:
Note that this function is database-specific, and therefore the exact use,
functions and presentation of the data vary widely between databases.
538
© Copyright. All rights reserved.
Lesson: Using the SQL Trace
The following information can be obtained by using this option:
●
Display of the native SQL statement
●
Information about the optimizer strategy
●
Information about the costs of the access
●
The index used by the statement
●
Information about the optimizer statistics
Figure 226: The EXPLAIN Function: Execution Plan
Some databases display the text of the SQL statement with placeholders (also called bind
variables) in addition to the access strategy of the SQL statement. These variables serve as
placeholders in case the same command is executed again with different contents. The
proper navigation (usually a double-click) displays the content of the bind variables.
An important function is the display of the access strategy that the optimizer uses – that is,
the utilized index. When a suitable index is used, the search effort required to compile the
result set for the SQL statement can be reduced significantly. Therefore, developers can
verify whether the resulting command was processed by the database quickly.
Identical SQL Statements
From within the trace list, to display an overview of how many identically structured SQL
statements were performed for the various tables and/or views, choose Trace → Structureidentical Statements. Identically structured statements use the same access strategy,
possibly with different values for the bind variables.
The list is sorted by total time required in microseconds.
The list contains the following information for each SQL statement:
●
How often was the statement executed?
●
How many records were transported (total and average)?
●
How much time was required for the access (total and average)?
© Copyright. All rights reserved.
539
Unit 7: Analysis and Testing
●
Which percentage of the executions was completely identical to a previous execution –
that is, with identical values in the bind variables?
Figure 227: Summarizing Trace Lists
The share of identical accesses is particularly relevant for performance aspects, because
identical accesses usually return identical results. They can be avoided through data
buffering.
A more detailed analysis of identical SQL statements is available under menu path
Trace → Value-Identical Statementsfrom within the trace list. This will show statements
which use the same access strategy with the same values for the bind variables.
Because identical SQL statements usually return identical result sets, they can often be
avoided by buffering the results, which can significantly improve the performance of an
application.
The optimization potential results from the identical executions of an SQL statement (for
example: of the four identical executions of an SQL statement involving a database table,
three are unnecessary if the results are buffered in an internal table; the optimization
potential for this SQL statement is therefore 75%).
LESSON SUMMARY
You should now be able to:
●
540
Use the SQL trace
© Copyright. All rights reserved.
Unit 7
Learning Assessment
1. Which of the following checkpoints is used in ABAP code to instruct the ABAP runtime to
interrupt program execution at a specific place and start the Debugger?
Choose the correct answer.
X
A Assertion
X
B Breakpoint
X
C Logpoint
2. The __________________ statement must always be used with the ID addition.
Choose the correct answer.
X
A BREAK-POINT
X
B LOG-POINT
X
C ASSERT
3. When using the ABAP Trace to analyze the runtime of an application, the measurement
results also depend on the current system and network load, as well as the active table
buffer and dataset.
Determine whether this statement is true or false.
X
True
X
False
4. The SQL Trace does not contain any database-specific functions.
Determine whether this statement is true or false.
X
True
X
False
© Copyright. All rights reserved.
541
Unit 7
Learning Assessment - Answers
1. Which of the following checkpoints is used in ABAP code to instruct the ABAP runtime to
interrupt program execution at a specific place and start the Debugger?
Choose the correct answer.
X
A Assertion
X
B Breakpoint
X
C Logpoint
2. The __________________ statement must always be used with the ID addition.
Choose the correct answer.
X
A BREAK-POINT
X
B LOG-POINT
X
C ASSERT
3. When using the ABAP Trace to analyze the runtime of an application, the measurement
results also depend on the current system and network load, as well as the active table
buffer and dataset.
Determine whether this statement is true or false.
X
True
X
False
4. The SQL Trace does not contain any database-specific functions.
Determine whether this statement is true or false.
542
X
True
X
False
© Copyright. All rights reserved.
UNIT 8
Best Practices for ABAP
Lesson 1
Avoiding Common Errors in ABAP Programming
544
Lesson 2
Creating Readable and Easy-to-Maintain ABAP Programs
548
Lesson 3
Optimizing the Runtime of ABAP Applications
552
Lesson 4
Avoiding Slow Database Accesses
560
UNIT OBJECTIVES
●
Avoid common mistakes when declaring and typing data objects
●
Avoid common mistakes when accessing data objects
●
Develop readable programs to facilitate maintenance by other developers
●
Develop robust programs
●
Avoid unnecessary processing
●
Optimize access to internal tables
●
Describe general performance rules in ABAP
●
Access buffered database tables
© Copyright. All rights reserved.
543
Unit 8
Lesson 1
Avoiding Common Errors in ABAP
Programming
LESSON OVERVIEW
This lesson describes common mistakes made when creating ABAP programs and explains
how to avoid them.
Business Example
You want to develop robust programs using ABAP. Therefore, you want to find out how to
avoid frequently made mistakes in ABAP development. For this reason, you require the
following knowledge:
●
An understanding of how to avoid frequent mistakes
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Avoid common mistakes when declaring and typing data objects
●
Avoid common mistakes when accessing data objects
Visibility and Lifetime of Data Objects
Incorrect Visibility and Lifetime of Data Objects
●
●
Possible Problems:
-
Data objects in dialog modules and event blocks are global.
-
There may be naming conflicts.
-
When called again, the data objects are no longer initial.
Solutions:
-
Do not define any data objects in dialog modules and event blocks.
-
Move source code to methods and subroutines, and use local data objects there.
Use of TABLES Structures
●
●
544
Possible Problems:
-
TABLES structures are always global.
-
TABLES structures are shared within the program group.
Solutions:
© Copyright. All rights reserved.
Lesson: Avoiding Common Errors in ABAP Programming
-
Use TABLES structures only in dynpro (screen) programming.
-
Never create TABLES structures in processing blocks.
-
Avoid external subroutine calls.
Use of Numeric Types
Incorrect Use of Numeric Types
●
Possible Problems:
-
●
There are rounding errors due to the selection of an incorrect numeric data type.
Solutions:
-
Carefully choose numeric data.
-
When calculating with integer operands, use type p result fields.
-
Avoid floating-point numbers with type f.
Access to Character-Type Data Objects
Offset Access to Character-Type Data Objects
●
●
Possible problems:
-
Illogical values are produced when developers make offset access of the entire
structure.
-
Runtime error occurs when developers make offset access outside the value range.
Solutions:
-
Limit offset access to individual components.
-
Catch the runtime error (CX_SY_RANGE_OUT_OF_BOUNDS).
-
Check the offset and length values before access.
Use of Data Types n, d, and t
●
Possible problems:
-
●
Program terminates due to invalid values such as blanks in data objects with types n, d,
and t.
Solutions:
-
Create data objects with type n, d, or t with valid initial values.
-
After SPLIT statements, check the data objects for invalid content and initialize them
when needed.
© Copyright. All rights reserved.
545
Unit 8: Best Practices for ABAP
Access to References and Field Symbols
Data References and Field Symbols
●
Possible problems:
-
●
Runtime error occurs when dereferencing references.
Solutions:
-
Always check validity before dereferencing references.
-
Always check validity before accessing field symbols.
Access to Internal Tables
BINARY SEARCH on Standard Tables
●
Possible problem:
-
●
Access to standard table with BINARY SEARCH does not find a line when the table is
not sorted.
Solution:
-
Sort the table once before accessing it with BINARY SEARCH.
Use of FOR ALL ENTRIES
●
Possible problem:
-
●
SELECT statement with addition FOR ALL ENTRIES reads all data when the internal
table is empty.
Solution:
-
Before accessing the database with FOR ALL ENTRIES, always make sure that the
internal table is not empty.
Accessing Internal Tables
●
Possible problem:
-
●
Runtime errors occur due to index access to sorted tables.
Solution:
-
Use only key access when changing data in sorted tables.
Access to System Fields
System Fields
●
546
Possible problems:
-
Obsolete and internal system fields do not necessarily have logical contents.
-
Inconsistency occurs after overwriting system fields.
© Copyright. All rights reserved.
Lesson: Avoiding Common Errors in ABAP Programming
●
Solutions:
-
Do not allow access to obsolete or internal system fields.
-
Do not allow write access to system fields.
-
Do not use system fields as actual parameters (particularly during transfer by
reference).
Use of SY-SUBRC
●
●
Possible problems:
-
There are inconsistencies.
-
There are security gaps.
-
There are follow-on errors.
Solutions:
-
Evaluate sy-subrc after every statement that sets the field (possibly with assertion).
-
Evaluate sy-subrc immediately.
Access to Interface Parameters
Use of Parameters
●
Possible problem:
-
●
Export parameters are not necessarily initial during transfer by reference at the start of
the processing block.
Solutions:
-
Pass on small export parameters as values.
-
Pass on large export parameters as references but do not access the read access
before the first write access.
Generic Types
●
Possible problem:
-
●
Runtime error occurs in the case of incorrect access to parameters with a generic type
or field symbols with a generic type.
Solutions:
-
Select the generic type as specifically as possible.
-
Use Runtime Type Identification (RTTI) to check the actual type before access.
LESSON SUMMARY
You should now be able to:
●
Avoid common mistakes when declaring and typing data objects
●
Avoid common mistakes when accessing data objects
© Copyright. All rights reserved.
547
Unit 8
Lesson 2
Creating Readable and Easy-to-Maintain ABAP
Programs
LESSON OVERVIEW
This lesson discusses several recommendations and conventions that help you make
programs that are easy to read and, therefore, easy to maintain. This lesson also discusses
recommendations for designing robust programs.
Business Example
You want to develop applications that are easy to read and maintain. Therefore, you want to
learn about recommendations and conventions for developing programs in ABAP. For this
reason, you require the following knowledge:
●
An understanding of the recommendations for robust and maintainable coding
●
An understanding of how to implement these recommendations
LESSON OBJECTIVES
After completing this lesson, you will be able to:
●
Develop readable programs to facilitate maintenance by other developers
●
Develop robust programs
Naming Conventions
Recommendations and Reasons for Using Naming Conventions
●
●
548
Recommendations:
-
Use naming conventions for data objects with different visibility, such as g for global
and l for local.
-
Use naming conventions for static attributes and instance attributes, such as g and m.
-
Use naming conventions for types of formal parameters, such as e, i, c, and r.
Reasons:
-
Consistent naming conventions improve readability.
-
Using conventions helps to avoid conflicts.
-
Using conventions avoids problems with inadvertently overwriting global data objects
with local data objects.
© Copyright. All rights reserved.
Lesson: Creating Readable and Easy-to-Maintain ABAP Programs
Recommendations and Reasons for Using Naming Conventions for Different Data Object
Types
●
Recommendations:
-
●
Use v for elementary, s for structure, and t for table-type objects.
Reasons:
-
Using this naming convention improves readability.
-
Using this naming convention avoids conflicts.
-
Using this naming convention avoids confusion.
Sequence of Statements
Recommendations for the Use of Declarations in Source Code
●
●
Recommendations:
-
Do not scatter declarations in the source text.
-
Group global declarations at the top of the program.
-
Group local declarations at the top of the processing blocks.
-
Do not place declarations in dialog modules or event blocks.
Reasons:
-
Grouping declarations improves readability.
-
Grouping global declarations at the top of the program and local declarations at the top
of processing avoids misunderstandings.
Use of Data Types and Constants
Figure 228: Independent or Bound Data Types
Recommendations and Reasons for Using Independent-type Definition and Bound-type
Definition
●
Recommendations:
-
●
Define independent data types instead of bound data types.
Reasons:
-
Independent data types have meaning.
-
Independent data types can be maintained centrally and are easy to reuse.
© Copyright. All rights reserved.
549
Unit 8: Best Practices for ABAP
Recommendations and Reasons for Using Constants
●
●
Recommendations:
-
Use constants instead of literals.
-
Use text symbols instead of literals for non-technical texts.
Reasons:
-
Use constants for ease of maintenance.
-
Use constants for ease of translation.
Recommendations for Using Global Data Types and Global Constants
●
●
Recommendations:
-
Whenever possible, create global data types and constants in global classes and
interfaces.
-
Create new types in the ABAP Dictionary only if you need dictionary functions (for
example, search help for user dialogs).
Reasons:
-
Groups types and constants
-
References to a context, such as method signature
-
Avoids unintended dependencies between programs
Encapsulation of Data
Recommendations for and Reasons to Maximize Encapsulation of Data Objects
●
●
Recommendations:
-
Use few global data objects.
-
Whenever possible, use data as attributes from local classes.
-
Wherever possible, make attributes private (or at least read-only).
Reasons:
-
Maximize encapsulation of data objects for ease of maintenance.
-
Maximize encapsulation of data objects for robustness.
Use of Obsolete Techniques
Recommendations for and Reasons not to use Obsolete Techniques
●
●
550
Recommendations:
-
Do not use external subroutine calls.
-
Do not use internal tables with header lines.
Reasons:
© Copyright. All rights reserved.
Lesson: Creating Readable and Easy-to-Maintain ABAP Programs
-
These techniques are difficult to read.
-
These techniques are error-prone.
Fixed Length or Strings
Figure 229: Fixed Length or Strings
Recommendations for and Reasons to use Strings
●
●
Recommendations:
-
Use strings wherever possible.
-
Use fields of fixed length only when having a fixed length is important, such as to
reference a screen field or database field.
Reasons:
-
Strings are more versatile.
-
Strings occupy only the memory that they actually need (with little overhead).
-
Strings are shared when copied.
Use of Dynamic Programming Techniques
Recommendations for the use of Dynamic Programming Techniques
●
●
Recommendations:
-
Use dynamic programming only when necessary.
-
Generate programs only if no other techniques are suitable.
-
Handle all error cases that may occur during dynamic programming.
-
Check prerequisites to avoid runtime errors.
Reasons:
-
Poor maintainability
-
Highly susceptible to errors
-
Difficult to test
LESSON SUMMARY
You should now be able to:
●
Develop readable programs to facilitate maintenance by other developers
●
Develop robust programs
© Copyright. All rights reserved.
551
Unit 8
Lesson 3
Optimizing the Runtime of ABAP Applications
LESSON OVERVIEW
This lesson gives tips for minimizing the runtime requirements for processing data in ABAP
programs. It also discusses the correct usage of internal tables.
Business Example
You want to develop an application that processes large volumes of data and you need to
minimize the program runtime. Therefore, you want to learn about programming techniques
that enable you to avoid excessive runtime requirements. For this reason, you require the
following knowledge:
●
An understanding of how excessive runtime requirements arise during the internal
processing of data in programs
●
An understanding of how to avoid excessive runtime requirements
LESSON OBJECTIVES
After completing this lesson, you will be able to:
552
●
Avoid unnecessary processing
●
Optimize access to internal tables
© Copyright. All rights reserved.
Lesson: Optimizing the Runtime of ABAP Applications
Unnecessary Type Conversions
Figure 230: Unnecessary Type Conversions
When you define assignments between data objects of different data types, the system
performs the conversion according to specific conversion rules, which generates overhead.
Therefore, avoid conversions wherever possible and only assign data objects of the same type
to each other.
To avoid unnecessary conversions, always specify the data objects in operand positions that
match the operand type.
In cases where type conversions are unavoidable (for example, character literals for noninteger values), create and use a suitably typed constant. In this case, the system only needs
to perform the conversion once.
© Copyright. All rights reserved.
553
Unit 8: Best Practices for ABAP
Unnecessary Copying of Large Data Objects
Figure 231: Pass by Reference or Pass by Value
When you define modularization units, you can choose between passing references and
passing values for a formal parameter. From a performance perspective, passing references
is preferred. However, you need to weigh this against the robustness of passing values on a
case-to-case basis.
Hint:
If sharing is used for passing values in internal tables and strings, this can
compensate for the performance disadvantage compared to passing references.
However, in this case, the system does not allow write access to the formal
parameters within the processing block because costs for copying would then be
incurred.
554
© Copyright. All rights reserved.
Lesson: Optimizing the Runtime of ABAP Applications
Logical Condition IS SUPPLIED for Parameters
Figure 232: Example of the IS SUPPLIED Logical Condition in a Function Module
When you program function modules and methods, you can design the program flow to be
dependent on whether the calling program has supplied an optional parameter. To do so, use
logical expressions in the format <name> IS SUPPLIED or <name> IS NOT SUPPLIED,
where <name> stands for the name of the optional parameter. EXPORT parameters are
always optional.
This technique helps prevent the system from retrieving and formatting data that the caller of
the modularization program does not require. This is especially useful because
unnecessary database accesses are avoided.
Note:
The obsolete logical condition IS REQUESTED still exists for the EXPORT and
CHANGING parameters.
© Copyright. All rights reserved.
555
Unit 8: Best Practices for ABAP
Selective Data Transport
Figure 233: Selective Data Transport
Use the TRANSPORTING addition when accessing the contents of internal tables to restrict the
copy operations to individual components, which improves runtime during repeated
accesses. This approach also increases the robustness of modifying accesses because it
helps avoid unintended changes to other fields.
Hint:
The TRANSPORTING addition is only available in the form TRANSPORTING NO
FIELDS for LOOP AT.
556
© Copyright. All rights reserved.
Lesson: Optimizing the Runtime of ABAP Applications
Use of Field Symbols and Data References
Figure 234: Accessing Nested Tables with Field Symbols
When you access internal tables, you can use data references or field symbols as pointers to
the table content instead of a work area. This gives better runtime performance for pure read
access with line widths of 1000 bytes or more.
Because the use of field symbols or references gives direct access to the referenced line, you
can make changes to the table contents directly without the MODIFY statement. As a result,
using field symbols or references gives better runtime performance for modifying access with
line widths of 1000 bytes or more.
Always use field symbols or references when the program uses nested internal tables. The
runtime requirements for a work area (in the right hand side of the figure Accessing Nested
Tables with Field Symbols) are high here because the entire inner internal table is copied each
time (the inner internal tables are not shared). The runtime savings are proportional to the
size of the inner internal table.
© Copyright. All rights reserved.
557
Unit 8: Best Practices for ABAP
Runtime Optimized Single Record Key Access
Figure 235: Fully Versus Partially Qualified Key for Single Record Access
The figure Fully Versus Partially Qualified Key for Single Record Access summarizes the single
record accesses to internal tables that can be accelerated by using the special sorted and
hashed table types. The key for hashed tables must be fully qualified to benefit from the hash
algorithm.
The ABAP syntax check only verifies compliance with this prerequisite if the developer
specifies the key with the WITH TABLE KEY addition. To ensure high-performance access for
hashed and sorted tables, use this syntax variant whenever possible.
The system always searches standard tables sequentially, regardless of the qualified fields.
The BINARY SEARCH addition enables a binary search. However, the binary search process
returns a correct result only if the search fields in the table have been sorted.
558
© Copyright. All rights reserved.
Lesson: Optimizing the Runtime of ABAP Applications
Optimized Mass Processing with WHERE Condition
Figure 236: Mass Processing and Table Types
During mass processing with a WHERE condition, the runtime system compares each table
line to determine whether it satisfies the specified condition. This is also called a table scan.
Sorted tables (and as of SAP NetWeaver 7.0, hashed tables where a complete key is specified
too) are the only exception to this rule. Runtime optimization is possible only for these table
types.
The prerequisite to runtime optimization is that in the WHERE clause, only the first n key fields
are filled with a = comparison operator. There can be no gaps, and n is less than or equal to
the number of all key fields.
When looping over a sorted standard table, optimize runtime by using single record access
with the BINARY SEARCH addition, a loop with a starting point, and an explicit termination
condition.
LESSON SUMMARY
You should now be able to:
●
Avoid unnecessary processing
●
Optimize access to internal tables
© Copyright. All rights reserved.
559
Unit 8
Lesson 4
Avoiding Slow Database Accesses
LESSON OVERVIEW
This lesson discusses tips to minimize runtime requirements during database accesses. It
also discusses the correct access to buffered database tables.
Business Example
You want to develop an application to process large data volumes. The program needs to
make frequent reads from the database. You want to minimize the runtime and, therefore,
learn about techniques for programming database accesses to avoid excessive runtime
requirements. For this reason, you require the following knowledge:
●
An understanding of the general performance rules for database access and how to rate
the various access techniques accordingly
●
An understanding of the importance of the WHERE condition for the database optimizer
and the access strategy
●
An understanding of the SELECT statements that bypass the table buffer
LESSON OBJECTIVES
After completing this lesson, you will be able to:
560
●
Describe general performance rules in ABAP
●
Access buffered database tables
© Copyright. All rights reserved.
Lesson: Avoiding Slow Database Accesses
Reduction of Database Load and Network Load
Figure 237: Performance Rules for Database Access
To optimize performance during database access for the system as a whole, and not just for
one individual program, reduce the load on the network between the application servers, the
database, and the database server.
To optimize performance, the application program must minimize the number of database
accesses and keeps the amount of data in each transfer small.
To reduce the load on the network between the application servers and the database server, it
is important to query data in consolidated packages and not in individual requests. Use
buffering techniques that read all the data required during the course of the program.
Buffering techniques also help you avoid multiple reads of the same data. You can also use
bundling techniques to fill data packages.
To reduce the load on the database, it is important to reduce the search effort by using WHERE
conditions that support the use of the primary or a secondary index.
© Copyright. All rights reserved.
561
Unit 8: Best Practices for ABAP
Optimized Application Logic
Figure 238: Optimizing the Application Logic
The figure Optimizing the Application Logic illustrates how to take the basic rules into account
when formulating database accesses.
To reduce the data volume, specify a list of fields in the SELECT statement if you require only
a small section of the fields.
Hint:
If you require a large number of fields, performance may be improved by reading
the complete lines. However, the extent to which you can increase performance
depends on the respective database.
Include as many conditions as possible in the WHERE condition. Avoid reading the data first
and then deciding which data you require. Specific WHERE conditions not only reduce the
data volume but also help the optimizer select a high-performance access strategy.
In this context, note that the different operators in the WHERE condition are of varying use for
the optimizer.
562
© Copyright. All rights reserved.
Lesson: Avoiding Slow Database Accesses
WHERE Conditions that Support the Use of Indexes
Figure 239: Quality of Operators in the WHERE Condition
If potential index fields are used in the WHERE condition, the EQ and = operators offer the best
optimization. Avoid conditions that use negations.
The figure Quality of Operators in the WHERE Condition illustrates the relative quality of
several operators for the optimizer.
Note:
The figure Quality of Operators in the WHERE Condition does not imply that you
should avoid certain operators completely; it merely illustrates tendencies in the
optimizer results of the various databases that you should be familiar with as a
developer.
© Copyright. All rights reserved.
563
Unit 8: Best Practices for ABAP
Statements That Bypass the Buffer
Figure 240: Statements That Bypass the Table Buffer
When you access database tables that use central SAP table buffering, you must understand
several additional rules.
Additional Rules for Accessing Database Tables that use Central SAP Table Buffering
●
Buffering data from these tables within the application does not improve performance.
●
SELECT statements for buffered database tables have to meet certain conditions for the
buffering to take effect.
If the SELECT statement contains certain additions or conditions, the SAP table buffer is
ignored and the system reads directly from the database. Such accesses are said to
bypass the table buffer.
In general, these include all Open SQL statements and additions that force an analysis by
the database, such as aggregation functions, sorted reading, join formation, and so on.
●
You can use the BYPASSING BUFFER statement to explicitly force a database read.
●
A database access always bypasses the table buffer if there is a possibility that the result
set is greater than the granularity of the buffering type.
If you use a SELECT loop to access a single-record-buffered table, for example, you cannot
guarantee that the records you need to read are completely available in the buffer.
Similarly, the buffer is always bypassed for generically buffered tables if the WHERE
condition does not specify unique values for all the fields in the generic area.
564
© Copyright. All rights reserved.
Lesson: Avoiding Slow Database Accesses
Caution:
For single-record-buffered tables in SAP NetWeaver 7.01 or earlier, the SELECT
loop bypasses the buffer even if the WHERE condition is limited to a unique
record; use the SELECT SINGLE statement for such cases.
LESSON SUMMARY
You should now be able to:
●
Describe general performance rules in ABAP
●
Access buffered database tables
© Copyright. All rights reserved.
565
Unit 8: Best Practices for ABAP
566
© Copyright. All rights reserved.
Unit 8
Learning Assessment
1. Data objects in dialog modules and event blocks are global.
Determine whether this statement is true or false.
X
True
X
False
2. Data objects defined in event blocks are local (that is, they are only visible and accessible
within that event block).
Determine whether this statement is true or false.
X
True
X
False
3. Which of the following does SAP recommend for the positioning of declarations in source
text?
Choose the correct answers.
X
A Do not scatter declarations throughout the source text.
X
B Whenever possible, create global data types and constants in global classes and
interfaces.
X
C Group local declarations at the top of the processing blocks.
X
D Do not include declarations in dialog modules or event blocks.
4. Which of the following does SAP recommend for using dynamic programming
techniques?
Choose the correct answers.
X
A Use dynamic programming only when necessary.
X
B Handle all error cases.
X
C Use strings wherever possible.
X
D Check prerequisites to avoid runtime errors.
© Copyright. All rights reserved.
567
Unit 8: Learning Assessment
5. To avoid unnecessary conversions, always specify the data objects in operand positions
that match the operand type.
Determine whether this statement is true or false.
X
True
X
False
6. When you access internal tables, the system does not allow you to use data references or
field symbols as pointers to the table content instead of a work area.
Determine whether this statement is true or false.
X
True
X
False
7. To reduce the load on the network between the application and database servers, it is
important to query data in individual requests and not in consolidated packages.
Determine whether this statement is true or false.
X
True
X
False
8. To reduce the data volume, specify a list of fields in the SELECT statement if you need only
a small section of the fields.
Determine whether this statement is true or false.
568
X
True
X
False
© Copyright. All rights reserved.
Unit 8
Learning Assessment - Answers
1. Data objects in dialog modules and event blocks are global.
Determine whether this statement is true or false.
X
True
X
False
2. Data objects defined in event blocks are local (that is, they are only visible and accessible
within that event block).
Determine whether this statement is true or false.
X
True
X
False
3. Which of the following does SAP recommend for the positioning of declarations in source
text?
Choose the correct answers.
X
A Do not scatter declarations throughout the source text.
X
B Whenever possible, create global data types and constants in global classes and
interfaces.
X
C Group local declarations at the top of the processing blocks.
X
D Do not include declarations in dialog modules or event blocks.
© Copyright. All rights reserved.
569
Unit 8: Learning Assessment - Answers
4. Which of the following does SAP recommend for using dynamic programming
techniques?
Choose the correct answers.
X
A Use dynamic programming only when necessary.
X
B Handle all error cases.
X
C Use strings wherever possible.
X
D Check prerequisites to avoid runtime errors.
5. To avoid unnecessary conversions, always specify the data objects in operand positions
that match the operand type.
Determine whether this statement is true or false.
X
True
X
False
6. When you access internal tables, the system does not allow you to use data references or
field symbols as pointers to the table content instead of a work area.
Determine whether this statement is true or false.
X
True
X
False
7. To reduce the load on the network between the application and database servers, it is
important to query data in individual requests and not in consolidated packages.
Determine whether this statement is true or false.
X
True
X
False
8. To reduce the data volume, specify a list of fields in the SELECT statement if you need only
a small section of the fields.
Determine whether this statement is true or false.
570
X
True
X
False
© Copyright. All rights reserved.
Download