Sap bc abap programming 1999 1540 05 05

Page 1

SAP AG

BC - ABAP Programming Linking a Logical DB to an Executable

Program END-OF-SELECTION.

Authorization Checks in Logical Databases It makes sense to use authorization checks using the AUTHORITY-CHECK [Page 506] statement in the following subroutines in the database program or event blocks of the executable program: •

Subroutines in the database program:

PAI

AUTHORITY_CHECK_<table>

Event blocks in the executable program:

AT SELECTION-SCREEN

AT SELECTION-SCREEN ON <fname>

AT SELECTION-SCREEN ON END OF <fname>

GET <table>

Whether you place the authorization checks in the database program or in the executable program depends on the following: •

The structure of the logical database. For example, you should only check authorizations for company code if you actually read lines containing the company code at runtime.

Performance Avoid repetitive checks (for example, within a SELECT loop).

The separation of database access and application logic allows you to program all of your authorization checks centrally in the logical database program. This makes it easier to maintain large programming systems.

December 1999

1233


BC - ABAP Programming

SAP AG

Calling a Logical Database Using a Function Module

Calling a Logical Database Using a Function Module From Release 4.5A it is possible to call logical databases independently from any ABAP program. Previously it was only possible to link a logical database to an executable program, in which the processing blocks of the logical database and the program were controlled by the ABAP runtime environment. To call a logical database from another program, use the function module LDB_PROCESS. This allows you to use the logical database as a routine for reading data. You can call more than one logical database from the same program. You may also call the same logical database more than once from the same program. In the past, it was only possible to use a logical database more than once or use more than one logical database by calling a further executable program using SUBMIT [Page 1059]. These programs had to be linked to the corresponding logical database, and the data had to be passed to the calling program using ABAP memory [Page 1073] or a similar technique. When you call a logical database using the function module LDB_PROCESS, its selection screen is not displayed. Instead, you fill the selections using the interface parameters of the function module. The logical database does not trigger any GET events in the calling program, but passes the data back to the caller in callback routines. Calling a logical database using LDB_PROCESS thus decouples the actual data retrieval from the preceding selection screen processing and the subsequent data processing. There is no need to adapt a logical database for use with LDB_PROCESS, except in the following cases: If you do not adapt a logical database, it is not possible to use the function module to call the same logical database more than once. The PAI subroutine is not called when you use LDB_PROCESS. This means that none of the checks for selections programmed in it are performed. You can work around these restrictions by including the subroutines LDB_PROCESS_INIT and LDB_PROCESS_CHECK_SELECTIONS [Page 1269] in the database program.

Runtime Behavior The subroutines in the logical database are called in the following sequence when you call the function module LDB_PROCESS: 1. LDB_PROCESS_INIT 2. INIT 3. LDB_PROCESS_CHECK_SELECTIONS 4. PUT <node>. None of the subroutines used to process the selection screen when you link the logical database to an executable program [Page 1230] are called, neither does the runtime environment trigger any reporting events in the calling program. Instead, the PUT statements in the logical database trigger actions in the function module that call callback routines in the calling program. In other words, the function module catches the events that are otherwise processed by the runtime environment.

Parameters of LDB_PROCESS The function module has the following import parameters: •

1234

LDBNAME

December 1999


SAP AG

BC - ABAP Programming

Calling a Logical Database Using a Function Module Name of the logical database you want to call. •

VARIANT Name of a variant to fill the selection screen of the logical database. The variant must already be assigned to the database program of the logical database. The data is passed in the same way as when you use the WITH SELECTION-TABLE addition in a SUBMIT [Page 1060] statement.

EXPRESSIONS In this parameter, you can pass extra selections for the nodes of the logical database for which dynamic selections are allowed. The data type of the parameter RSDS_TEXPR is defined in the type group RSDS. The data is passed in the same way as when you use the WITH FREE SELECTION addition in a SUBMIT [Page 1060] statement.

FIELD_SELECTION You can use this parameter to pass a list of the required fields for the nodes of the logical database for which dynamic selections are allowed. The data type of the parameter is the deep internal table RSFS_FIELDS, defined in the type group RSFS. The component TABLENAME contains the name of the node and the deep component FIELDS contains the names of the fields that you want to read.

The function module has the following tables parameters: •

CALLBACK You use this parameter to assign callback routines to the names of nodes and events. The parameter determines the nodes of the logical database for which data is read, and when the data is passed back to the program and in which callback routine.

SELECTIONS You can use this parameter to pass input values for the fields of the selection screen of the logical database. The data type of the parameter corresponds to the structure RSPARAMS in the ABAP Dictionary. The data is passed in the same way as when you use the WITH SELECTION-TABLE addition in a SUBMIT [Page 1060] statement.

If you pass selections using more than one of the interface parameters, values passed in SELECTIONS and EXPRESSIONS overwrite values for the same field in VARIANT.

Read Depth and Callback Routines When you link a logical database with an executable program, the GET statements determine the depth to which the logical database is read. When you call the function module LDB_PROCESS, you determine the depth by specifying a node name in the CALLBACK parameter. For each node for which you request data, a callback routine can be executed at two points. These correspond to the GET and GET LATE events in executable programs. In the table parameter CALLBACK, you specify the name of the callback routine and the required execution point for each node. A callback routine is a subroutine in the calling program or another program that is to be executed at the required point. For the GET event, the callback routine is executed directly after the data has been read for the node, and before the subordinate nodes are processed. For the GET_LATE event, the callback routine is processed after the subordinate nodes have been processed. The line type of the table parameter CALLBACK is the flat structure LDBCB from the ABAP Dictionary. It has the following components:

December 1999

1235


BC - ABAP Programming

SAP AG

Calling a Logical Database Using a Function Module •

LDBNODE Name of the node of the logical database to be read.

GET A flag (contents X or SPACE), to call the corresponding callback routine at the GET event.

GET_LATE A flag (contents X or SPACE), to call the corresponding callback routine at the GET LATE event.

CB_PROG Name of the ABAP program in which the callback routine is defined.

CB_FORM Name of the callback routine.

If you pass an internal table to the CALLBACK parameter, you must fill at least one of the GET or GET_LATE columns with X for each node (you may also fill both with X). A callback routine is a subroutine that must be defined with the following parameter interface: FORM <subr> USING <node> LIKE LDBCB-LDBNODE <wa> [TYPE <t>] <evt> <check>. The parameters are filled by the function module LDB_PROCESS. They have the following meaning: •

<node> contains the name of the node.

<wa> is the work area of the data read for the node. The program that calls the function module LDB_PROCESS and the program containing the callback routine do not have to declare interface work areas using NODES or TABLES. If the callback routine is only used for one node, you can use a TYPE reference to refer to the data type of the node in the ABAP Dictionary. Only then can you address the individual components of structured nodes directly in the subroutine. If you use the callback routine for more than one node, you cannot use a TYPE reference. In this case, you would have to address the components of structured nodes by assigning them one by one [Page 214] to a field symbol.

<evt> contains G or L, for GET or GET LATE respectively. This means that the subroutine can direct the program flow using the contents of <evt>.

<check> allows the callback routine to influence how the program is processed further (but only if <evt> contains the value G). The value X is assigned to the parameter when the subroutine is called. If it has the value SPACE when the subroutine ends, this flags that the subordinate nodes of the logical database should not be processed in the function module LDB_PROCESS. This is the same as leaving a GET event block using CHECK [Page 1015] in an executable program. If this prevents unnecessary data from being read, it will improve the performance of your program.

1236

December 1999


SAP AG

BC - ABAP Programming Calling a Logical Database Using a

Function Module

Exceptions of LDB_PROCESS •

LDB_ALREADY_RUNNING A logical database may not be called if it is still processing a previous call. If this occurs, the exception LDB_ALREADY_RUNNING is triggered.

LDB_NOT_REENTRANT A logical database may only be called repeatedly if its database program contains the subroutine LDB_PROCESS_INIT [Page 1269], otherwise, this exception is triggered.

LDB_SELECTIONS_NOT_ACCEPTED Error handling in the subroutine LDB_PROCESS_CHECK_SELECTIONS [Page 1269] of the database program can trigger this exception. The error message is placed in the usual system fields SY-MSG... [Page 486].

For details of further exceptions, refer to the function module documentation in the Function Builder.

Example TABLES SPFLI. SELECT-OPTIONS S_CARR FOR SPFLI-CARRID. TYPE-POOLS: RSDS, RSFS. DATA: CALLBACK TYPE TABLE OF LDBCB, CALLBACK_WA LIKE LINE OF CALLBACK. DATA: SELTAB TYPE TABLE OF RSPARAMS, SELTAB_WA LIKE LINE OF SELTAB. DATA: TEXPR TYPE RSDS_TEXPR, FSEL TYPE RSFS_FIELDS. CALLBACK_WA-LDBNODE = 'SPFLI'. CALLBACK_WA-GET = 'X'. CALLBACK_WA-GET_LATE = 'X'. CALLBACK_WA-CB_PROG = SY-REPID. CALLBACK_WA-CB_FORM = 'CALLBACK_SPFLI'. APPEND CALLBACK_WA TO CALLBACK. CLEAR CALLBACK_WA. CALLBACK_WA-LDBNODE = 'SFLIGHT'. CALLBACK_WA-GET = 'X'. CALLBACK_WA-CB_PROG = SY-REPID. CALLBACK_WA-CB_FORM = 'CALLBACK_SFLIGHT'. APPEND CALLBACK_WA TO CALLBACK. SELTAB_WA-KIND = 'S'. SELTAB_WA-SELNAME = 'CARRID'. LOOP AT S_CARR. MOVE-CORRESPONDING S_CARR TO SELTAB_WA.

December 1999

1237


BC - ABAP Programming

SAP AG

Calling a Logical Database Using a Function Module

APPEND SELTAB_WA TO SELTAB. ENDLOOP. CALL FUNCTION 'LDB_PROCESS' EXPORTING LDBNAME VARIANT EXPRESSIONS FIELD_SELECTION TABLES CALLBACK SELECTIONS EXCEPTIONS LDB_NOT_REENTRANT LDB_INCORRECT LDB_ALREADY_RUNNING LDB_ERROR LDB_SELECTIONS_ERROR LDB_SELECTIONS_NOT_ACCEPTED VARIANT_NOT_EXISTENT VARIANT_OBSOLETE VARIANT_ERROR FREE_SELECTIONS_ERROR CALLBACK_NO_EVENT CALLBACK_NODE_DUPLICATE OTHERS

= = = =

'F1S' ' ' TEXPR FSEL

= CALLBACK = SELTAB = = = = = = = = = = = = =

1 2 3 4 5 6 7 8 9 10 11 12 13.

IF SY-SUBRC <> 0. WRITE: 'Exception with SY-SUBRC', SY-SUBRC. ENDIF. FORM CALLBACK_SPFLI USING NAME TYPE WA TYPE EVT TYPE CHECK TYPE CASE EVT. WHEN 'G'. WRITE: / WA-CARRID, WA-CONNID, ULINE. WHEN 'L'. ULINE. ENDCASE. ENDFORM.

LDBN-LDBNODE SPFLI C C.

WA-CITYFROM, WA-CITYTO.

FORM CALLBACK_SFLIGHT USING NAME TYPE LDBN-LDBNODE WA TYPE SFLIGHT EVT TYPE C CHECK TYPE C. WRITE: / WA-FLDATE, WA-SEATSOCC, WA-SEATSMAX. ENDFORM. The program is written to read data using the logical database F1S. The structure of F1S is:

1238

December 1999


SAP AG

BC - ABAP Programming Calling a Logical Database Using a

Function Module

SPFLI SPFLI SFLIGHT SFLIGHT SBOOK SBOOK A program-specific selection screen is defined at the beginning of the program. This requires the TABLES statement. Next, the required variables are defined for the interface. The internal table CALLBACK is filled so that various callback routines are called in the program for the two nodes SPFLI and SFLIGHT. For SPFLI, the routine is to be called for GET and GET_LATE, for SFLIGHT, only at the GET event. The internal table SELTAB is filled with values for the node SPFLI from the selection table S_CARR from the program-specific selection screen. The program then calls the function module LDB_PROCESS with these parameters. The subroutines CALLBACK_SPFLI and CALLBACK_SFLIGHT serve as callback routines. The interface parameter WA is fully typed, so you can address the individual components of the work areas. The events GET and GET LATE are handled differently in CALLBACK_SPFLI. The beginning of the list output might look like this:

December 1999

1239


BC - ABAP Programming

SAP AG

Calling a Logical Database Using a Function Module

1240

December 1999


SAP AG

BC - ABAP Programming Editing Logical Databases

Editing Logical Databases You edit logical databases using the Logical Database Builder in the ABAP Workbench. To start the Logical Database Builder, use Transaction SE36 or SLDB, or choose Tools → ABAP Workbench, followed by Development → Programming environment → Logical Database Builder. You can also start it by forward navigation from the Repository Browser or other ABAP Workbench tools. In the Logical database field, you can enter a name of up to 20 characters. The name may also contain a three to ten-character namespace prefix, enclosed in forward slashes. On the initial screen, you can create, copy, and delete logical databases. However, you can only delete a logical database if it is not linked to an executable program. Even if a logical database is not linked to any executable programs, it can still be used by a program that calls it using the function module LDB_PROCESS. Before deleting one, you should therefore check that it is not still in use. However, the Where-used list function only shows where a logical database is assigned to an executable program. You can select the individual components of the logical database directly. When you are editing a logical database, two arrow icons appear in the application toolbar that allow you to navigate backwards and forwards between the most important components. You can also use the normal Goto function to navigate between components. Creating a Logical Database [Page 1242] Editing the Structure [Page 1244] Editing a Search Help [Page 1246] Editing Selections [Page 1247] Editing the Database Program [Page 1251] Editing Other Components [Page 1270] Improving Performance [Page 1271]

December 1999

1241


BC - ABAP Programming

SAP AG

Creating a Logical Database

Creating a Logical Database To create a new logical database, you should follow the procedure below. The Logical Database Builder then saves you work by using components that you have already defined to generate proposals for other components. Some of the most important attributes of a logical database are set when you define its structure. When you have defined the structure, the Logical Database Builder automatically generates a proposal for the selection include. The system then generates an input mask for the database program, based on the structure of the logical database and the selections. These generated proposals allow you to create a working logical database quickly. However, you must program refinements such as authorization checks and performance optimization yourself.

Procedure for Creating a Logical Database 1. Enter a name on the initial screen of the Logical Database Builder and choose Create. 2. A dialog box appears. Enter a short text. You can change this later by choosing Extras → Short text or Administration info. 3. Once you have entered the short text, you must define the root node of the logical database. Enter the node name and its attributes. There are three different types of nodes: §

Database tables. The table must be active in the ABAP Dictionary. Tables always have a flat structure. The name of the node must correspond with the name of the table.

§

Data types from the ABAP Dictionary: The node may refer to any data type in the ABAP Dictionary [Page 105]. The node name and the name of the data type do not have to be the same. You can use deep data types as nodes.

§

Data types from type groups: The node can also refer to a data type from a type group in the ABAP Dictionary. Enter the name of the type group in the corresponding field. You must choose Other types before specifying this type. Data types in type groups were the forerunners of real data types in the ABAP Dictionary. Wherever possible, you should use ABAP Dictionary data types. They have all of the semantic properties of their underlying data elements. This is useful, for example, when you use a logical database to create ABAP Queries.

You can use the Text from Dictionary function to adopt the text stored in the ABAP Dictionary for the relevant table or data type. 1. The structure editor of the Logical Database Builder appears. On the left is the name of the root node, followed by a code for the node type: T for a database table, S for a ABAP Dictionary type, and C for a type from a type group. The new logical database now has a structure with a single node. 2. You can now extend the structure as described in Editing the Structure [Page 1244]. 3. If you choose Next screen (right arrow in the application toolbar), a screen appears on which you can enter a search help for the logical database as described under Editing Search Helps [Page 1246]. 4. If you choose Next screen (right arrow in the application toolbar), a dialog box appears, asking you whether the system should generate the selections for the logical database.

1242

December 1999


SAP AG

BC - ABAP Programming Creating a Logical Database

When you have confirmed the dialog box, a list appears, on which you can select all of the nodes that you want to use for field selections or dynamic selections. The fields that you select are included in the source code generated by the system for the selection include. 5. The generated selection include is displayed in the ABAP Editor. You can change it as described in Editing Selections [Page 1247]. 6. If you choose Next screen (right arrow in the application toolbar), a dialog box appears, asking you whether the system should generate the database program for the logical database. The database program is generated from the structure and the selection include. It has a modular structure, consisting of several include programs and all of the necessary subroutines, with proposals for the statements that will read the data. 7. The generated database program is displayed in the ABAP Editor. You can change it as described in Editing the Database Program [Page 1251]. 8. If you repeatedly choose Previous screen (left arrow in the application toolbar), you can display and change the general attributes of the logical database. 9. Finally, you can maintain optional selection texts and documentation.

December 1999

1243


BC - ABAP Programming

SAP AG

Processing the Structure

Processing the Structure To display or change the structure of a logical database, choose Structure from the initial screen of the Logical Database Builder, or navigate to the structure editor from another component.

Displaying the Structure The structure editor displays the structure hierarchy. Each node is displayed as follows:

... <node> <node>

<id> <id> <type> <type> <text> <text>

... •

<node> is the name of the node.

<id> is the type of the node: T for a database table, S for a ABAP Dictionary type, and C for a type from a type group.

<type> is the name of the ABAP Dictionary object to which the node refers.

<text> is the short text for the node.

As usual, you can expand or collapse the subordinate tree structures, and edit individual subtrees. You can display the attributes of a node by double-clicking it. To display the structure of a node, that is, the components of its data type, place the cursor on the node and choose Display table fields. The PUT routine function allows you to display the subroutine PUT_<node>. For this to work, the subroutine must be contained in its own include that follows a particular naming convention. For further information, refer to Editing the Database Program [Page 1251].

Changing the Structure •

To rename an existing node, place the cursor on it and choose Edit → Node → Change.

To create a new node at a subordinate level to the cursor position, or on the same level, choose Edit → Node → Create. Nodes that you create like this in the structure editor consists at first only of its logical name, with which it is declared in the database program using the TABLES or NODES statement. To define the node fully, double-click it. You can then enter its type, the name of the data type from the ABAP Dictionary to which it refers, and its short text.

To select/deselect a sub-tree, choose Edit → Sub-tree → Select/deselect. To move a selected sub-tree in a structure to a position indicated by the cursor, choose Edit → Subtree → Reassign.

To delete a sub-tree, place the cursor on the node or select it and choose Edit → Subtree → Delete.

1244

December 1999


SAP AG

BC - ABAP Programming Processing the Structure

December 1999

1245


BC - ABAP Programming

SAP AG

Editing a Search Help

Editing a Search Help A search help is a ABAP Dictionary object used to define possible values (F4) help. There are two kinds of search help - elementary and collective. An elementary search help uses a search path to determine the possible entries. A collective search help consists of two or more elementary search helps, and thus provides more than one possible search path. To display or change the link between a logical database and a search help, choose Search helps from the initial screen of the Logical Database Builder or use the navigation function from another component. Here, you can assign a search help to the logical database by choosing from a list. You can also delete the link between the logical database and an existing search help. In deciding which search help is appropriate for the logical database, you must consider its content. For example, if you create a logical database that reads creditor records, the creditor number should be one of the output fields of the search help. The contents of the output fields of the search help are available to the logical database at runtime for the actual database access. There are two ways of finding information about the output fields of a search help. You can either use the ABAP Dictionary, or enter a search help and then look at the ensuing list. To enable the user to use the search help, you must declare a special parameter in the selection include using the addition AS SEARCH PATTERN. The system interprets the user’s input on the selection screen and reads the value list from the database. The values are made available to the database program in the internal table <ldb>_SP, and the subroutine PUT_<ldb>_SP is called instead of PUT_<root>. <ldb> is the name of the logical database, and <root> is the name of the root node. This subroutine can use the value list in <ldb>_SP to read the actual data and trigger the GET <root> event using the PUT_<root> statement.

1246

December 1999


SAP AG

BC - ABAP Programming Editing Selections

Editing Selections To display or change the structure of a logical database, choose Selections from the initial screen of the Logical Database Builder, or navigate to the selection include from another component. The name of the selection include is DB<ldb>SEL, where <ldb> is the name of the logical database. You must not incorporate this include program in the database program using an INCLUDE statement. Instead, the runtime environment includes the selection include in the database program and the corresponding programs when it generates the logical database. If you try to edit the selections but no selection include yet exists, the system generates one. This includes SELECT-OPTIONS statements for all of the database tables in the structure (nodes with type T). For each database table, the system proposes selection criteria [Page 718] for all of the fields in its primary key. The SELECT-OPTIONS statements are commented out, and contain question marks instead of the names of the selection criteria. For each selection criterion that you want to use, you must enter the name and delete the comment character (*). If a search help is specified for the logical database, the system also generates a corresponding PARAMETERS statement with the addition AS SEARCH PATTERN. A group box entitled Selection using search help then appears on the selection screen with input fields for the search help ID and the search string. There is also a pushbutton for complex search helps. If you choose this function, you can enter multiple selections for each field. Finally, SELECTION-SCREEN statements are generated for dynamic selections and field selections for nodes with type T or S (if this is allowed by the structure definition). As well as the default elements, you can use the following statements to extend the selection screen:

Use the PARAMETERS statement and its additions to add input fields for single values [Page 699]. You could use these, for example, to control the flow of the program. In the selection include, you must use the addition FOR NODE or FOR TABLE in the PARAMETERS statement. You can use NODE for all node types. You can only use TABLE for nodes with type T. When the selection screen is generated, the system only generates fields for the nodes declared in the executable program in the NODES or TABLES statement, or those requested by the function module LDB_PROCESS.

Use the SELECTION-SCREEN statement to format the selection screen [Page 734].

The statement SELECTION-SCREEN DYNAMIC SELECTIONS FOR NODE|TABLE <node>. allows you to define further nodes for dynamic selections. If the node has type T, you can use TABLE instead of NODE. The user can then decide at runtime the components of the node for which he or she wants to enter selections. Dynamic selections require special handling in the database program.

The statement SELECTION-SCREEN FIELD SELECTION FOR NODE|TABLE <node>. allows you to define further nodes for field selections. If the node has type T, you can use TABLE instead of NODE. In an executable program, you can use a field list in the GET statement to specify which fields of the node of the logical database should be read. In the function module LDB_PROCESS, the parameter FIELD_SELECTION must be

December 1999

1247


BC - ABAP Programming

SAP AG

Editing Selections passed accordingly. Dynamic selections require special handling in the database program. •

The statements SELECTION-SCREEN BEGIN OF VERSION <dynnr> ... SELECTION-SCREEN EXCLUDE <f>. ... SELECTION-SCREEN BEGIN OF VERSION <dynnr>. allow you to create different versions of the selection screen with screen number <dynnr> less than 1000. You can hide the input fields of selection criteria or parameters as specified in <f>. This allows an executable program to work with an appropriate selection screen version.

To check the selection include DB<dba>SEL for syntax errors, choose Check on the initial screen. The system also checks the syntax of the selection include if you choose Check while editing the database program.

Suppose the logical database TEST_LDB has the following structure:

LFA1 LFA1 LFB1 LFB1 LFC1 LFC1 BKPF BKPF The generated default selection include would look like this: *-----------------------------------------------------------* * Include DBTEST_LDBSEL * It will be automatically included into the database program *-----------------------------------------------------------* * If the source is automatically generated, * please perform the following steps: * 1. Replace ? by suitable names (at most 8 characters). * 2. Activate SELECT-OPTIONS and PARAMETERS (delete stars). * 3. Save source code. * 4. Edit database program. * * Hint: Syntax-Check is not possible within this Include! * It will be checked during syntax-check of database program. *-----------------------------------------------------------* * SELECT-OPTIONS : ? FOR LFA1-LIFNR.

1248

December 1999


SAP AG

BC - ABAP Programming Editing Selections

* Parameter for search pattern selection (Type SY-LDB_SP): * PARAMETERS p_sp AS SEARCH PATTERN FOR TABLE LFA1. * SELECT-OPTIONS : * ? FOR LFB1-LIFNR, * ? FOR LFB1-BUKRS. * SELECT-OPTIONS : * ? FOR LFC1-LIFNR, * ? FOR LFC1-BUKRS, * ? FOR LFC1-GJAHR. * SELECT-OPTIONS : * ? FOR BKPF-BUKRS, * ? FOR BKPF-BELNR, * ? FOR BKPF-GJAHR. * Enable DYNAMIC SELECTIONS for selected nodes : * Enable FIELD SELECTION for selected nodes : If the nodes LFA1 and LFB1 are defined for dynamic selections, and node LFC1 is defined for field selections, the following lines of code will also be generated: SELECTION-SCREEN DYNAMIC SELECTIONS FOR TABLE LFA1. SELECTION-SCREEN DYNAMIC SELECTIONS FOR TABLE LFB1. SELECTION-SCREEN FIELD SELECTION FOR TABLE LFC1. The automatically-created selection include could be modified as follows: * Selection criteria: SELECT-OPTIONS SLIFNR FOR LFA1-LIFNR. SELECT-OPTIONS SBUKRS FOR LFB1-BUKRS. SELECT-OPTIONS SGJAHR FOR LFC1-GJAHR. SELECT-OPTIONS SBELNR FOR BKPF-BELNR. * Self-defined parameters: PARAMETERS PSTIDA LIKE SY-DATUM FOR NODE BKPF. * Dynamic selections for LFA1 and LFB1: SELECTION-SCREEN DYNAMIC SELECTIONS FOR NODEE: LFA1, LFB1. * Field selection for LFB1 and LFC1: SELECTION-SCREEN FIELD SELECTION FOR NODE: LFB1, LFC1. Here, selections are chosen from the available selection criteria and are given names. An additional parameter PSTIDA is declared and linked to the node BKPF. Dynamic selections are defined for the tables LFA1 and LFB1. Field selections are defined for tables LFB1 and LFC1.

December 1999

1249


BC - ABAP Programming

SAP AG

Editing Selections

1250

December 1999


SAP AG

BC - ABAP Programming Editing the Database Program

Editing the Database Program To display or change the database program of a logical database, choose Database program from the initial screen of the Logical Database Builder, or navigate to the database program from another component. The name of the program is SAPDB<ldb>, where <ldb> is the name of the logical database.

Structure of the Database Program When you open the database program for editing for the very first time, the system generates it. The generated database program looks like a function group, since it consists of a series of generated include programs [Page 449]. This makes their structure easy to follow, even if the logical database has a large number of nodes. Older logical databases may not use includes and consist instead only of a main program.

INCLUDE DB<ldb>TOP.

PROGRAM PROGRAM SAPDB<ldb>. SAPDB<ldb>. NODES: NODES: ... ... TABLES: TABLES: ... ... TYPES: TYPES: ... ... DATA: DATA: ... ...

INCLUDE DB<ldb>XXX.

INCLUDE INCLUDE INCLUDE INCLUDE INCLUDE INCLUDE INCLUDE INCLUDE ... ...

INCLUDE DB<ldb>F001.

... ...

DB<ldb>001. DB<ldb>001. DB<ldb>002. DB<ldb>002. DB<ldb>FXXX. DB<ldb>FXXX. DB<ldb>SXXX. DB<ldb>SXXX.

FORM PUT_<node>. FORM PUT_<node>. FUNCTION <name>. FUNCTION <name>. ... FUNCTION <name>. ... FUNCTION <name>. ... ... ENDFORM. ... ENDFORM. ... ENDFUNCTION. ENDFUNCTION. ENDFUNCTION. ENDFUNCTION.

...

Main program SAPDB<ldb>

Include programs

The main program SAPDB<ldb> usually contains the following include programs: •

DB<ldb>TOP Contains global declarations.

DB<ldb>XXX. Contains further include programs for individual subroutines.

DB<ldb>F<001>, DB<ldb>F<002> ... User-defined include programs for extra functions.

The include program DB<ldb>XXX usually contains the following include programs:

December 1999

1251


BC - ABAP Programming

SAP AG

Editing the Database Program •

DB<ldb>001, DB<ldb>002, … Contain the subroutines PUT_<node> and AUTHORITY_CHECK_<node> for the individual nodes of the logical database.

DB<ldb>FXXX Contains most of the remaining subroutines for initialization, PBO, and PAI of the selection screen, and so on.

DB<ldb>SXXX Contains the subroutine FORM PUT_<ldb>_SP for processing the search help.

You must not change the NODES and TABLES statements, or the prescribed names of the automatically-generated include programs and subroutines. However, you can define extra includes and subroutines, and change the ABAP statements used to read data. User-defined include programs must follow the naming convention DB<ldb>F<nnn> to ensure that they are transported with the logical database.

Full Example of a Generated ABAP Program Suppose the logical database TEST_LDB has the following structure:

LFA1 LFA1 LFB1 LFB1 LFC1 LFC1 BKPF BKPF All of the nodes are database tables. Suppose the following selections are defined in the selection include: SELECT-OPTIONS: SLIFNR FOR LFA1-LIFNR. SELECT-OPTIONS: SBUKRS FOR LFB1-BUKRS. SELECT-OPTIONS: SGJAHR FOR LFC1-GJAHR. SELECT-OPTIONS: SBELNR FOR BKPF-BELNR. The essential lines of the automatically-generated database program and its include programs are listed below. The program also contains some user and performance hints as comment lines, but these are not included here.

Main Program SAPDBTEST_LDB *----------------------------------------------------------* * DATABASE PROGRAM OF LOGICAL DATABASE

1252

December 1999


SAP AG

BC - ABAP Programming Editing the Database Program

TEST_LDB *----------------------------------------------------------* INCLUDE DBTEST_LDBTOP . " header INCLUDE DBTEST_LDBXXX . " all system routines * INCLUDE DBTEST_LDBF001 . " user defined include

Include Program DBTEST_LDBTOP PROGRAM SAPDBTEST_LDB DEFINING DATABASE TEST_LDB. TABLES : LFA1, LFB1, LFC!, BKPF. * data: ...

"user defined variables

Include Program DBTEST_LDBXXX *----------------------------------------------------------* * Automatically generated file * contains all necessary system routines of the database program * !!!!! DO NOT CHANGE MANUALLY !!!!! *----------------------------------------------------------* INCLUDE INCLUDE INCLUDE INCLUDE INCLUDE INCLUDE

DBTEST_LDBN001 DBTEST_LDBN002 DBTEST_LDBN003 DBTEST_LDBN004 DBTEST_LDBFXXX DBTEST_LDBSXXX

. . . . . .

" " " " " "

Node LFA1 Node LFB1 Node LFC1 Node BKPF INIT, PBO, PAI search help

Include Program DBTEST_LDB001 *----------------------------------------------------------* * Call event GET LFA1 *----------------------------------------------------------* FORM PUT_LFA1. * SELECT * FROM LFA1 * INTO LFA1 * INTO TABLE ? (choose one!) * WHERE LIFNR = ?. PUT LFA1. * ENDSELECT. ENDFORM.

"PUT_LFA1

*----------------------------------------------------------* * Authority Check for node LFA1 *----------------------------------------------------------* * FORM AUTHORITY_CHECK_LFA1. * AUTHORITY-CHECK ... * ENDFORM.

December 1999

"AUTHORITY_CHECK_LFA1

1253


BC - ABAP Programming

SAP AG

Editing the Database Program

Include Programs DBTEST_LDB002 and DBTEST_LDB003 Similar to DBTEST_LDB001, but for the nodes LFB1 and LFC1.

Include Program DBTEST_LDB004 *----------------------------------------------------------* * Call event GET BKPF *----------------------------------------------------------* FORM PUT_BKPF. * STATICS FLAG. * IF FLAG = SPACE. * FLAG = 'X'. *** Declarations for field selection for node BKPF *** * STATICS BKPF_FIELDS TYPE RSFS_TAB_FIELDS. * MOVE 'BKPF' TO BKPF_FIELDS-TABLENAME. * READ TABLE SELECT_FIELDS WITH KEY BKPF_FIELDS-TABLENAME * INTO BKPF_FIELDS. * ENDIF. * SELECT (BKPF_FIELDS-FIELDS) INTO CORRESPONDING FIELDS OF * BKPF / TABLE ? " (choose one of them) * FROM BKPF * WHERE BUKRS = LFB1-BUKRS * AND BELNR IN SBELNR * AND GJAHR = ?. PUT BKPF. ENDFORM.

"PUT_BKPF

*----------------------------------------------------------* * Authority Check for node BKPF *----------------------------------------------------------* * FORM AUTHORITYCHECK_BKPF. * AUTHORITY-CHECK ... * ENDFORM.

"AUTHORITY_CHECK_BKPF

Include Program DBTEST_LDBFXXX *----------------------------------------------------------* * BEFORE_EVENT will be called before event EVENT * Possible values for EVENT: 'START-OF-SELECTION' *----------------------------------------------------------* * FORM BEFORE_EVENT USING EVENT. * CASE EVENT. * WHEN 'START-OF-SELECTION' * * ENDCASE. * ENDFORM. "BEFORE_EVENT *----------------------------------------------------------* * AFTER_EVENT will be called after event EVENT * Possible values for EVENT: 'END-OF-SELECTION' *----------------------------------------------------------* * FORM AFTER_EVENT USING EVENT.

1254

December 1999


SAP AG

BC - ABAP Programming Editing the Database Program

* CASE EVENT. * WHEN 'END-OF-SELECTION' * * ENDCASE. * ENDFORM. "AFTER_EVENT

*----------------------------------------------------------* * Initialize global data for multiple processing of * one logical database. * Set returncode: * 0 -> all data are initialized, multiple processing o.k. * other -> no multiple processing allowed *------------------------------------------------------------* FORM LDB_PROCESS_INIT CHANGING SUBRC LIKE SY-SUBRC. ENDFORM.

"LDB_PROCESS_INIT

*------------------------------------------------------------* * LDB_PROCESS_CHECK_SELECTIONS is called * after select-options and parameters are filled *------------------------------------------------------------* FORM LDB_PROCESS_CHECK_SELECTIONS CHANGING SUBRC LIKE SYSUBRC MSG LIKE SYMSG. ENDFORM.

"LDB_PROCESS_CHECK_SELECTIONS

*----------------------------------------------------------* * Initialize selection screen (processed before PBO) *----------------------------------------------------------* FORM INIT. ENDFORM.

"INIT.

*----------------------------------------------------------* * PBO of selection screen (processed always after ENTER) *----------------------------------------------------------* FORM PBO. ENDFORM.

"PBO.

*----------------------------------------------------------* * PAI of selection screen (processed always after ENTER) *----------------------------------------------------------* FORM PAI USING FNAME MARK. * CASE FNAME. * WHEN 'SLIFNR '. * WHEN 'SBUKRS '. * WHEN 'SBELNR '. * WHEN 'SGJAHR '. * WHEN '*'.

December 1999

1255


BC - ABAP Programming

SAP AG

Editing the Database Program * ENDCASE. ENDFORM.

"PAI

Include Program DBTEST_LDBSXXX ************************************************************* * !!! PLEASE DO NOT CHANGE MANUALLY (BEGIN OF BLOCK) !!!!!! * *----------------------------------------------------------* * Data structures for search pattern selection * * !!! PLEASE DO NOT CHANGE MANUALLY (END OF BLOCK) !!!!!!!! * ************************************************************* *----------------------------------------------------------* * PUT_TEST_LDB_SP. * Processed when search pattern selection is used, * i.e. user input into PARAMETERS p_sp AS SEARCH PATTERN * STRUCTURE. *----------------------------------------------------------* * FORM PUT_TEST_LDB_SP. * ENDFORM.

"PUT_EXAMPLE_SP

The function of most of the subroutines is described in the section Structure of Logical Databases [Page 1213]. The comment symbols (*) before the ABAP statements that are optional can be deleted, and the question marks replaced by appropriate expressions. When you check the syntax of the program, all of the include programs that conform to the naming convention and the selection include are also checked. In the subroutines PUT_<node>, SELECT statements are generated with conditions in their WHERE clauses for the primary key fields of the node. Note that these statements do not observe the performance rules [Page 1148] for Open SQL statements. In particular, the PUT_<node> subroutines for a subtree a structure form nested SELECTED loops, which you should avoid. Instead, you can buffer the data in internal tables, and pass it to the application program from there using the PUT statement. However, for technical reasons, the PUT <node> statement should always occur in a subroutine whose name begins PUT_<node>. If the selection contains dynamic selections or field selections for a node, the system generates the corresponding statements in the subroutine PUT_NODE, and adjusts the automaticallygenerated SELECT statements, as in the example for the node BKPF. The following sections explain how you can process user input in the dynamic selections and column specifications after GET statements.

Generated Data Objects and Subroutines Some internal tables and other subroutines are automatically generated, and can be used in the program.

1256

December 1999


SAP AG

BC - ABAP Programming Editing the Database Program

The internal table GET_EVENT contains the nodes of the logical database that are requested by the user in GET statements. The table is generated as follows: DATA: BEGIN OF GET_EVENTS OCCURS 10, NODE(10), KIND, END OF GET_EVENTS. Each line contains the name of a node of the logical database in the NODE field. The KIND field specifies whether and how the node is requested by the user.

KIND = 'X': Node is addressed in GET and GET LATE.

KIND = 'G': Node is addressed only in GET.

KIND = 'L': Node is addressed only in GET LATE.

KIND = 'P': Node is addressed neither in GET nor in GET LATE. However, a subordinate node is addressed in GET or GET LATE.

KIND = ' ': Node is addressed neither in GET nor in GET LATE. No subordinate node is addressed either.

The subroutines BEFORE_EVENT, AFTER_EVENT, and PUT_<ldb>_SP are generated as comments in the database program (see example above). You can modify them and activate them by deleting the comment characters (*). BEFORE_EVENT is called before the event specified in the parameter EVENT is processed. AFTER_EVENT is called after the event specified in the parameter EVENT is processed. PUT_<ldb>_SP is called for processing values instead of PUT_<root> if a search help is used for selection. <root> is the root node of the logical database.

Dynamic Selections in the Database Program [Page 1258] Field Selections in the Database Program [Page 1262] Search Helps in the Database Program [Page 1265] Independent Calls and the Database Program [Page 1269]

December 1999

1257


BC - ABAP Programming

SAP AG

Dynamic Selections in the Database Program

Dynamic Selections in the Database Program The statement SELECTION-SCREEN DYNAMIC SELECTIONS FOR NODE|TABLE <node>. declares a node <node> of a logical database for dynamic selections in the selection include. To use the dynamic selections in the SELECT statements of the subroutine PUT_<node>, you must use the data object DYN_SEL. The data object DYN_SEL is automatically generated in the logical database program as follows: TYPE-POOLS RSDS. DATA DYN_SEL TYPE RSDS_TYPE. You do not have to program these lines yourself. The data object DYN_SEL is available in the database program but not in a connected executable program. The type RSDS_TYPE of the data object is defined in the type group RSDS as follows: TYPE-POOL RSDS. * WHERE-clauses -----------------------------TYPES: RSDS_WHERE_TAB LIKE RSDSWHERE OCCURS 5. TYPES: BEGIN OF RSDS_WHERE, TABLENAME LIKE RSDSTABS-PRIM_TAB, WHERE_TAB TYPE RSDS_WHERE_TAB, END OF RSDS_WHERE. TYPES: RSDS_TWHERE TYPE RSDS_WHERE OCCURS 5. * Expressions Polish notation --------------TYPES: RSDS_EXPR_TAB LIKE RSDSEXPR OCCURS 10. TYPES: BEGIN OF RSDS_EXPR, TABLENAME LIKE RSDSTABS-PRIM_TAB, EXPR_TAB TYPE RSDS_EXPR_TAB, END OF RSDS_EXPR. TYPES: RSDS_TEXPR TYPE RSDS_EXPR OCCURS 10. * Selections as RANGES-tables ----------------TYPES: RSDS_SELOPT_T LIKE RSDSSELOPT OCCURS 10. TYPES: BEGIN OF RSDS_FRANGE, FIELDNAME LIKE RSDSTABS-PRIM_FNAME, SELOPT_T TYPE RSDS_SELOPT_T, END OF RSDS_FRANGE. TYPES: RSDS_FRANGE_T TYPE RSDS_FRANGE OCCURS 10. TYPES: BEGIN OF RSDS_RANGE, TABLENAME LIKE RSDSTABS-PRIM_TAB, FRANGE_T TYPE RSDS_FRANGE_T, END OF RSDS_RANGE. TYPES: RSDS_TRANGE TYPE RSDS_RANGE OCCURS 10.

1258

December 1999


SAP AG

BC - ABAP Programming Dynamic Selections in the Database

Program * Definition of RSDS_TYPE TYPES: BEGIN OF RSDS_TYPE, CLAUSES TYPE RSDS_TWHERE, TEXPR TYPE RSDS_TEXPR, TRANGE TYPE RSDS_TRANGE, END OF RSDS_TYPE. It is a deep structure with the following components:

CLAUSES CLAUSES contains the dynamic selections entered by the user (or possibly program-internal selection criteria) as internal tables, which you can use directly in dynamic WHERE clauses [Page 1108]. CLAUSES is an internal table that contains another internal table WHERE_TAB as a component. Each line of the CLAUSES-TABLENAME column contains the name of a node designated for dynamic selections. For each of these database tables, the WHERE_TAB tables contain the selection criteria of the dynamic selections. The WHERE_TAB tables have a format that allows you to use them directly in dynamic WHERE clauses. To use WHERE_TAB in the logical database, you must program the dynamic WHERE clause for each node <node> designated for dynamic selection in the corresponding subroutine PUT_<node>. For this, the corresponding internal table WHERE_TAB for <node> must be read from the data object DYN_SEL. The following example shows how you can use a local data object in the subroutine for this purpose:

Suppose the database table SCARR is the root node of the logical database ZHK and that SPFLI is its only subordinate node. The selection Include DBZHKSEL contains the following lines:

SELECT-OPTIONS S_CARRID FOR SCARR-CARRID. SELECT-OPTIONS S_CONNID FOR SPFLI-CONNID. SELECTION-SCREEN DYNAMIC SELECTIONS FOR TABLE SCARR. The subroutine PUT_SCARR of the database program SAPDBZHK uses the dynamic selection as follows:

FORM PUT_SCARR. STATICS: DYNAMIC_SELECTIONS TYPE RSDS_WHERE, FLAG_READ. IF FLAG_READ = SPACE. DYNAMIC_SELECTIONS-TABLENAME = 'SCARR'. READ TABLE DYN_SEL-CLAUSES WITH KEY DYNAMIC_SELECTIONS-TABLENAME INTO DYNAMIC_SELECTIONS. FLAG_READ = 'X'. ENDIF. SELECT * FROM SCARR WHERE CARRID IN S_CARRID AND (DYNAMIC_SELECTIONS-WHERE_TAB).

December 1999

1259


BC - ABAP Programming

SAP AG

Dynamic Selections in the Database Program

PUT SCARR. ENDSELECT. ENDFORM. The line of the internal table DYN_SEL-CLAUSES that contains the value SCARR in column DYN_SEL-CLAUSES-TABLENAME is read into the local structure DYNAMIC_SELECTIONS. The STATICS statements and the FLAG_READ field ensure that table DYN_SEL is only read once during each program execution. The table DYNAMIC_SELECTIONS-WHERE_TAB is used in the dynamic WHERE clause. Each executable program that uses ZHK as its logical database and contains a NODES or TABLES statement for SCARR or SPFLI now offers dynamic selections for the fields in table SCARR on its selection screen. The dynamic WHERE clause means that the logical database only reads the lines that satisfy the selection conditions on the selection screen and in the dynamic selections.

TEXPR TEXPR contains the selections of the dynamic selections in an internal format (Polish notation).You can use this format with function modules FREE_SELECTIONS_INIT and FREE_SELECTIONS_DIALOG in order to work with dynamic selections within a program (for more information, see the documentation of these function modules).

TRANGE TRANGE contains the selections from the dynamic selection as RANGES tables [Page 719] that you can use with the IN operator in a WHERE clause or logical expression. TRANGE is an internal table that contains another internal table FRANGE_T as a component. Each line in the column TRANGE-TABLENAME contains the name of a node that is designated for dynamic selections. For each of these nodes, the FRANGE_T tables contain the selection criteria of the dynamic selections in the format of RANGES tables. FRANGE_T contains a FIELDNAME column that contains the fields of the node for which the RANGES tables are defined. The other component of FRANGE_T, SELOPT_T, contains the actual RANGES tables. With TRANGE, you can access the selections of individual database columns directly . Furthermore, it is easier to modify selection criteria stored in the RANGES format than those stored in the WHERE clause format. The following example shows how you can use local data objects of the corresponding subroutine PUT_<node> to work with TRANGE:

Suppose the database table SCARR is the root node of the logical database ZHK and that SPFLI is its single branch. The selection Include DBZHKSEL contains the following lines:

SELECT-OPTIONS S_CARRID FOR SCARR-CARRID. SELECT-OPTIONS S_CONNID FOR SPFLI-CONNID. SELECTION-SCREEN DYNAMIC SELECTIONS FOR TABLE SCARR. The subroutine PUT_SCARR of the database program SAPDBZHK uses the dynamic selection as follows:

FORM PUT_SCARR.

1260

December 1999


SAP AG

BC - ABAP Programming Dynamic Selections in the Database

Program

STATICS: DYNAMIC_RANGES TYPE RSDS_RANGE, DYNAMIC_RANGE1 TYPE RSDS_FRANGE, DYNAMIC_RANGE2 TYPE RSDS_FRANGE, FLAG_READ. IF FLAG_READ = SPACE. DYNAMIC_RANGES-TABLENAME = 'SCARR'. READ TABLE DYN_SEL-TRANGE WITH KEY DYNAMIC_RANGES-TABLENAME INTO DYNAMIC_RANGES. DYNAMIC_RANGE1-FIELDNAME = 'CARRNAME'. READ TABLE DYNAMIC_RANGES-FRANGE_T WITH KEY DYNAMIC_RANGE1-FIELDNAME INTO DYNAMIC_RANGE1. DYNAMIC_RANGE2-FIELDNAME = 'CURRCODE'. READ TABLE DYNAMIC_RANGES-FRANGE_T WITH KEY DYNAMIC_RANGE2-FIELDNAME INTO DYNAMIC_RANGE2. FLAG_READ = 'X'. ENDIF. SELECT * FROM WHERE AND AND

SCARR CARRID IN S_CARRID CARRNAME IN DYNAMIC_RANGE1-SELOPT_T CURRCODE IN DYNAMIC_RANGE2-SELOPT_T.

PUT SCARR. ENDSELECT. ENDFORM. The line of the internal table DYN_SEL-TRANGE that contains the value 'SCARR' in column DYN_SEL-CLAUSES-TABLENAME is read into the local table DYNAMIC_RANGES. The nested tables DYNAMIC_RANGES-FRANGE_T are read into the local tables DYNAMIC-RANGE1 and DYNAMIC-RANGE2 according to the contents of DYNAMIC_RANGES-FIELDNAME. The STATICS statements and the FLAG_READ field assure that the tables are read only once each time the executable program is executed. After the READ statements, the nested tables SELOPT_T of the local tables contain the RANGES tables for the columns CARRNAME and CURRCODE of the database table SCARR. The tables SELOPT_T are used in the SELECT statement directly as selection tables. Besides CARRNAME, CURRCODE and the primary key, there are no further columns in the database table SCARR. Therefore, this logical database has the same function as the logical database in the above example using the CLAUSES component.

December 1999

1261


BC - ABAP Programming

SAP AG

Field Selections in the Database Program

Field Selections in the Database Program The statement SELECTION-SCREEN FIELD SELECTION FOR NODE|TABLE <node>. declares a node <node> of a logical database for field selections in the selection include. This means that you can list individual fields in the SELECT statements of the corresponding subroutine PUT_<node>, instead of having to use SELECT * to select all columns. This allows you to minimize the amount of data transferred from the database [Page 1153], which can often improve performance. For each node for which field selection is allowed, you can specify the columns that you want to read using the FIELD addition to the GET statement in the executable program or in the FIELD_SELECTION parameter of the function module LDB_PROCESS. The database program of the logical database can access the names of the columns in the data object SELECT_FIELDS. The data object SELECT_FIELDS is automatically generated in the logical database program as follows: TYPE-POOLS RSFS. DATA SELECT_FIELDS TYPE RSFS_FIELDS. You do not have to program these lines yourself. The data object SELECT_FIELDS is available in the database program and also in each connected executable program. The type RSDS_FIELDS of the data object is defined in the type group RSDS as follows: TYPE-POOL RSFS. * Fields to be selected per table TYPES: BEGIN OF RSFS_TAB_FIELDS, TABLENAME LIKE RSDSTABS-PRIM_TAB, FIELDS LIKE RSFS_STRUC OCCURS 10, END OF RSFS_TAB_FIELDS. * Fields to be selected for all tables TYPES: RSFS_FIELDS TYPE RSFS_TAB_FIELDS OCCURS 10. RSDS_FIELDS is a deep internal table with the components TABLENAME and FIELDS. Each line of the TABLENAME column contains the name of a node that is designated for field selection. The table FIELDS contains the columns specified in the GET statements in the application program for each of these nodes. The FIELDS table have a format that allows you to use them directly in dynamic SELECT lists in SELECT statements. To use the names of the columns in the logical database, you can specify the dynamic list FIELDS in the SELECT clause of the SELECT statements in the subroutine PUT_<node> for each node <node> for which field selections are allowed. To do this, you must read the corresponding internal table from the internal table SELECT_FIELDS. The following example shows how you can use a local data object of the subroutine for this purpose:

Suppose the database table SCARR is the root node of the logical database ZHK and that SPFLI is its only subordinate node.

1262

December 1999


SAP AG

BC - ABAP Programming Field Selections in the Database

Program The selection Include DBZHKSEL contains the following lines:

SELECT-OPTIONS S_CARRID FOR SCARR-CARRID. SELECT-OPTIONS S_CONNID FOR SPFLI-CONNID. SELECTION-SCREEN FIELD SELECTION FOR TABLE SPFLI. The subroutine PUT_SCARR of the database program SAPDBZHK uses the field selections as follows:

FORM PUT_SPFLI. STATICS: FIELDLISTS TYPE RSFS_TAB_FIELDS, FLAG_READ. IF FLAG_READ = SPACE. FIELDLISTS-TABLENAME = 'SPFLI'. READ TABLE SELECT_FIELDS WITH KEY FIELDLISTS-TABLENAME INTO FIELDLISTS. FLAG_READ = 'X'. ENDIF. SELECT (FIELDLISTS-FIELDS) INTO CORRESPONDING FIELDS OF SPFLI FROM SPFLI WHERE CARRID = SCARR-CARRID AND CONNID IN S_CONNID. PUT SPFLI. ENDSELECT. ENDFORM. The line of the internal table SELECT_FIELDS that contains the value 'SCARR' in column SELECT_FIELD-TABLENAME is read into the local structure FIELDLISTS. The STATICS statements and the FLAG_READ field assure that the table DYN_SEL is read only once each time the executable program is run. The table FIELDLISTSFIELDS is used in the dynamic SELECT clause. An executable program to which the logical database HKZ is linked could now, for example, contain the following lines:

TABLES SPFLI. GET SPFLI FIELDS CITYFROM CITYTO. ... The FIELDS option of the GET statement defines which fields besides the primary key the logical database should read from the database table. Internally, the system fills the table SELECT_FIELDS with the corresponding values. This can be demonstrated by adding the following lines to the program:

DATA: ITAB ITAB_L JTAB JTAB_L

LIKE LIKE LIKE LIKE

SELECT_FIELDS, LINE OF ITAB, ITAB_L-FIELDS, LINE OF JTAB.

START-OF-SELECTION.

December 1999

1263


BC - ABAP Programming

SAP AG

Field Selections in the Database Program

ITAB = SELECT_FIELDS. LOOP AT ITAB INTO ITAB_L. IF ITAB_L-TABLENAME = 'SPFLI'. JTAB = ITAB_L-FIELDS. LOOP AT JTAB INTO JTAB_L. WRITE / JTAB_L. ENDLOOP. ENDIF. ENDLOOP. These lines display the column names on the list as follows: CITYTO CITYFROM MANDT CARRID CONNID

The fields of the primary key (MANDT, CARRID, CONNID) have been added automatically to the specified columns.

1264

December 1999


SAP AG

BC - ABAP Programming Search Helps in the Database Program

Search Helps in the Database Program The statement PARAMETERS <p> AS SEARCH PATTERN FOR TABLE <node>. defines a framework in the selection include for a search help on the selection screen. The key fields returned by the search help are placed in the internal table <ldb>_SP, from where they can be used by the database program. The subroutine PUT_<ldb>_SP is then called instead of PUT_<root> (where <ldb> is the name of the logical database). In the subroutine PUT_<ldb>_SP, the logical database can use the information from the internal table to make the actual database access more efficient. It triggers the event GET <root> with the statement PUT_<root>, where <root> is the name of the root node. It is often useful to call the subroutine PUT_<root> from PUT_<ldb>_SP. PUT_<root> can then select the data and trigger the corresponding GET event in the PUT <root> statement. However, for technical reasons, the PUT <root> statement should always occur in a subroutine whose name begins PUT_<root>. The structure of the internal table <ldb>_SP and other automatically-generated tables is displayed as a comment in the generated source code of the database program. How the tables are used is also documented in the source code.

Let us look at a logical database ZZF with the root node KNA1 that is linked to the search help DEBI. Let the selection Include DBZHKSEL contain the following lines:

SELECT-OPTIONS SKUNNR FOR KNA1-KUNNR. PARAMETERS P_SP AS SEARCH PATTERN FOR NODE KNA1. The source code of the database program now includes more comment lines which indicate that the following tables and fields were created in addition to those listed under : Internal table ZZF_SP: This table has the following data type: DATA: BEGIN OF ZZF_SP OCCURS 1000, KUNNR LIKE KNA1-KUNNR, END OF ZZF_SP. The search help selections for the user generate a hit list in the output fields of the search help. The hit list is available to the database program through the table ZZF_SP. Internal table SP_FIELDS: If a collective search help is assigned to the logical database, an elementary search help will normally only fill a selection of the output fields of the collective search help. The program can find out from table SP_FIELDS which fields are filled. Its structure is: DATA: BEGIN OF SP_FIELDS OCCURS 10. INCLUDE STRUCTURE RSSPFIELDS. DATA: END OF SP_FIELDS. The field SP_FIELDS-SUPPLIED is not equal to SPACE if a value was assigned to the field in SP_FIELDS-FIELDNAME by the search help.

December 1999

1265


BC - ABAP Programming

SAP AG

Search Helps in the Database Program

– – – –

Internal table SP_TABLES: If the search help contains fields from different tables, the program can find out from the table SP_TABLES which ones are covered by the search help. The structure is: DATA: BEGIN OF SP_TABLES OCCURS 10. INCLUDE STRUCTURE RSSPTABS. DATA: END OF SP_TABLES. The field SP_TABLES-SUPPLIED is not equal to SPACE if a value was assigned to the table in SP_FIELDS-TABLENAME by the search help. Field SP_EVENTS: This is a field with length 200. Each byte in SP_EVENTS stands for a table in the logical database structure (for example, the first character stands for the root node). The contents of the individual positions have the following meaning for the corresponding node: 'X': The node is addressed in the application program using the GET statement. The search help has assigned values for the key fields to SP_<ldb>. 'R': The node is addressed in the application program using the GET statement. The search help has not assigned values for the key fields to SP_<ldb>. 'M': The node is not addressed in the application program using the GET statement, but the search help has assigned values for the key fields to SP_<ldb>. ' ': The node is not addressed in the application program using the GET statement, and the search help has not assigned values for the key fields to SP_<ldb>. If the user selects all suppliers in the search help on the selection screen whose sort field begins with ABC, and this applies to customer numbers 17, 125, and 230, the above tables will be filled as follows: ZZF_SP:

KUNNR 17 125 230 SP_FIELDS:

FIELDNAME

SUPPLIED

KUNNR

X

SP_TABLES:

TABLENAME

SUPPLIED

KNA1

X

The inactive subroutine PUT_ZZF_SP can, for example, be modified and activated as follows in order to use the entries from the internal table ZZF_SP:

FORM PUT_ZZF_SP.

1266

December 1999


SAP AG

BC - ABAP Programming Search Helps in the Database Program

CASE SP_EVENTS(1). WHEN 'X' OR 'M'. PERFORM PUT_KNA1_SP. WHEN OTHERS. PERFORM PUT_KNA1. ENDCASE. ENDFORM. FORM PUT_KNA1_SP. SELECT * FROM KNA1 FOR ALL ENTRIES IN ZZF_SP WHERE KUNNR = ZZF_SP_KUNNR. PUT KNA1. ENDSELECT. ENDFORM. The system uses the table GET_EVENTS to check whether the application program contains a GET statement for KNA1, or whether the search help has assigned values for the key fields. If this is true, the system calls PUT_KNA1_SP. This contains a SELECT loop for KNA1, in which the lines corresponding to the key fields in ZZF_SP are read. The SELECT loop contains the statement PUT KNA1. Another possibility would be:

FORM PUT_ZZF_SP. * Fill selection table from ZZF_SP IF SP_EVENTS(1) NE SPACE. CLEAR SKUNNR. REFRESH SKUNNR. MOVE: 'I' TO SKUNNR-SIGN, 'EQ' TO SKUNNR-OPTION. LOOP AT ZZF_SP. MOVE ZZF_SP-KUNNR TO SKUNNR-LOW. APPEND SKUNNR. ENDLOOP. ENDIF. * Select data and call GET KUNNR READ TABLE GET_EVENTS WITH KEY 'KNA1'. IF SY-SUBRC = 0 AND GET_EVENTS-KIND NE SPACE. PERFORM PUT_KUNNR. ENDIF. This deletes the selection table SKUNNR for KNA1 and fills it with the values from ZZF_SP. The program uses the table GET_EVENTS to check whether the application program contains a GET statement for KNA1. If so, it calls the subroutine PUT_KUNNR. Here, the data from KNA1 is read according to the selection table SKUNNR, and the PUT KNA1 statement is executed. If the database access uses a search help, you should of course, use dynamic selections and field selections. You can also use search helps to improve performance. You can program different database accesses depending on the tables and fields that are used and filled using the internal tables GET_EVENTS, SP_FIELDS, and SP_TABLES. For example, you can use a view or a join and

December 1999

1267


BC - ABAP Programming

SAP AG

Search Helps in the Database Program place the entries in internal tables, which you can process later and then trigger the corresponding GET events.

1268

December 1999


SAP AG

BC - ABAP Programming Independent Calls and the Database

Program

Independent Calls and the Database Program If you call logical databases independently using the function module LDB_PROCESS, you can call special subroutines in the database program:

LDB_PROCESS_INIT If you want to call a logical database more than once in succession, the database program must contain the following subroutine: FORM LDB_PROCESS_INIT CHANGING SUBRC LIKE SY-SUBRC. ... SUBRC = 0. ENDFORM. This is the first subroutine to be called in the database program. Once the parameter SUBRC has been set to 0, the logical database can perform the initialization routines required to allow it to be called more than once. If the parameter SUBRC is not set to 0, the function module LDB_PROCESS triggers the exception LDB_NOT_REENTRANT.

LDB_PROCESS_CHECK_SELECTIONS When you call a logical database using LDB_PROCESS, there is no selection screen processing. Instead, the selections are passed to the function module as interface parameters. The PAI subroutine is not called. However, if you still want to check the selections, you can define the following subroutine in the database program: FORM LDB_PROCESS_CHECK_SELECTIONS CHANGING SUBRC LIKE SY-SUBRC MSG ..LIKE SYMSG. ... SUBRC = ... ENDFORM. This subroutine is called after the parameters and selection tables of the selection screen have been filled from the interface parameters of LDB_PROCESS. If the parameter SUBRC is not set to 0, the function module LDB_PROCESS triggers the exception LDB_SELECTIONS_NOT_ACCEPTED. You can assign a message to the structured parameter MSG. This is available to the caller of the function module in the system fields SY-MSG... The eight components of MSG contain the message type, ID, and number, and up to four message variables.

December 1999

1269


BC - ABAP Programming

SAP AG

Editing Other Components

Editing Other Components This section describes other components of logical databases that you may want to change.

Selection Texts The selection texts, that is, the texts displayed with the input fields on the selection screen, are normally the names of the selection criteria and parameters. These texts are maintained separately from the logical database as text elements [Extern]. The user interface of a logical database is therefore independent of the language in which it was created. Instead, it always appears in the logon language of the current user.

Documentation Logical databases are reusable modules that can be used by a wide range of application programs. You should therefore ensure that they are adequately documented.

Authorization Objects To create a list of authorization objects that are checked in the database program, choose Extras → Authorization objects.

Checking Logical Databases To check whether a logical database is correct and complete, choose Check from the initial screen of the Logical Database Builder. The result of the check includes: •

Whether the logical database exists

Whether its short text exists

Whether the structure exists

Whether the selections exist

Whether the database program exists

Whether the database program is syntactically correct

Whether authorization objects have been maintained

Whether there is any documentation

1270

December 1999


SAP AG

BC - ABAP Programming Improving Performance

Improving Performance Changes to logical databases are immediately visible in all of the programs that use them. This allows you to tune the performance [Page 1148] of the Open SQL statements for all of these programs in one place. One way of improving performance is to allow the user to specify exactly what data should be read from the logical database. You can use the following techniques to improve performance: •

Static selection criteria and parameters on the selection screen, possibly with default values and value lists defined in the logical database.

Dynamic selections

Search helps

ABAP Dictionary views, or other methods that minimize the number of database reads •

Early authorization checks - during selection screen processing if possible, not during the data selection itself.

There are no hard and fast rules for how to optimize a logical database, since what you can do depends heavily on the data you want to read. The following are therefore only general points that you can nevertheless observe when optimizing logical databases: •

The numerical relationship between the table contents at different levels of the structure is very important. If, for example, one line of a database table at one level of the structure includes exactly one line of the database table at the next level (case A), other optimizations may make more sense for a 1:100 or 1:1000 ratio (case B). In case A, you can improve the response time by using database views. In case B, you can use internal tables. The data is read by the database into an internal table. The internal table can then be processed within the logical database. You could also use joins or cursor processing.

Some application programs only use part of the structure of the logical database, while other use all of its nodes. In this case, you have the following options for improving the performance of individual reports:

You can use the table GET_EVENTS in the logical database program. When you have generated an executable program that uses the logical database, this table contains information about each node in the structure, and whether the corresponding GET statement appears in the program or not.

In the selections of the logical database, you should use the statement SELECTION-SCREEN FIELD SELECTION FOR NODE|TABLE <node>. to allow field selections for all suitable nodes <node>. You can then use a field list in the corresponding SELECT statements instead of having to read the entire line.

December 1999

1271


BC - ABAP Programming

SAP AG

Improving Performance

1272

December 1999


SAP AG

BC - ABAP Programming Using Contexts

Using Contexts Contexts are objects within the ABAP Workbench that enable you to store details about the relationships between data. You use them in your ABAP programs to derive data which is dependent on a small number of key fields. Contexts allow you to •

store processing logic from application programs in context programs, reducing the complexity of the application.

make better use of recurring logic.

use buffering to improve system performance.

What are Contexts? [Page 1274] The Context Builder in the ABAP Workbench [Page 1275] Using Contexts in ABAP Programs [Page 1298] Working With Contexts - Hints [Page 1311]

December 1999

1273


BC - ABAP Programming

SAP AG

What are Contexts?

What are Contexts? Within the large quantities of data in the R/3 System database, there are always smaller sets of basic data that you can use to derive further information. In a relational database model, for example, these are the key fields of database tables. When an application program requires further information in order to continue, this is often found in these small amounts of basic data. The relational links in the database are often used to read further data on the basis of this basic data, or further values are calculated from it using ABAP statements. It is often the case that certain relationships between data are always used in the same form to get further data, either within a single program or in a whole range of programs. This means that a particular set of database accesses or calculations is repeatedly executed, despite the fact that the result already exists in the system. Contexts provide a way of avoiding this unnecessary system load. Contexts are objects within the ABAP Workbench, consisting of key input fields, the relationships between these fields, and other fields which can be derived from them. Contexts can link these derived fields by foreign key relationships between tables, by function modules, or by other contexts. You define contexts abstractly in the ABAP Workbench (Transaction SE33), and use instances of them as runtime objects in your ABAP programs. In the ABAP Workbench, contexts consist of fields and modules. Their fields are divided into key fields and derived fields. The modules describe the relationship between the fields. Technically, contexts are special ABAP programs. You can save them •

in a non-executable program, with the name CONTEXT_S_<context name>.For the example context DEMO_TRAVEL, this would be CONTEXT_S_DEMO_TRAVEL).

•

in a generated executable program, with the name CONTEXT_X_<context name>.For the example context DEMO_TRAVEL, this would be CONTEXT_X_DEMO_TRAVEL).

In application programs, you work with instances of a context. You can use more than one instance of the same context. The application program supplies input values for the key fields in the context using the SUPPLY statement, and can query the derived fields from the instance using the DEMAND statement. Each context has a cross-transaction buffer on the application server. When you query an instance for values, the context program searches first of all for a data record containing the corresponding key fields in the appropriate buffer. If one exists, the data is copied to the instance. If one does not exist, the context program derives the data from the key field values supplied and writes the resulting data record to the buffer. Whenever, in a program, new key fields are entered into an instance that has already been previously supplied with them, the system invalidates all affected values that have already been derived. These values are only re-supplied the next time they are queried.

1274

December 1999


SAP AG

BC - ABAP Programming The Context Builder in the ABAP

Workbench

The Context Builder in the ABAP Workbench Normally you will use existing contexts within your R/3 System, and only use the Context Builder to familiarize yourself with them and test them (see Finding and Displaying a Context [Page 1299]). However, if no suitable context already exists in the system, you can use the Context Builder to create your own. This section describes how to use the Context Builder (Transaction SE33) in the ABAP Workbench.

Creating and Editing a Context [Page 1276] Testing a Context [Page 1288] Buffering Contexts [Page 1290]

December 1999

1275


BC - ABAP Programming

SAP AG

Creating and Editing a Context

Creating and Editing a Context To create a context, call the Context Builder (Transaction SE33) and enter a name for your new context in the Context field. In the Sub-objects group box, select Fields and modules, then choose Create. On the next screen, you enter the attributes for your context: When you have saved the attributes, choose Fields and modules. The context maintenance screen is then displayed.

Name

Fields Ref. Field / type

Modules Name Typ Table/Module

Parameter

I/O Field name

There are three tables on this screen, in which you enter the Fields [Page 1293], Modules [Page 1295] and Interfaces [Page 1297] in your context. You can enlarge each of these tables by choosing Enlarge . The contents of the individual tables are interdependent, and are filled automatically to a certain extent. The next three sections use simple examples to demonstrate how you can create contexts using different modules.

Using Tables as Modules [Page 1278] Using Function Modules as Modules [Page 1281] Using Contexts as Modules [Page 1285]

1276

December 1999


SAP AG

BC - ABAP Programming Creating and Editing a Context

December 1999

1277


BC - ABAP Programming

SAP AG

Using Tables as Modules

Using Tables as Modules The following example demonstrates how to create a context called DOCU_TEST1, which has two modules with type table. The tables used are SPFLI and SFLIGHT from the data model BC_TRAVEL. 1. Enter SPFLI in the Name or Table/Module column of the Modules [Page 1295] table and choose Enter. The system then fills all of the tables of the context maintenance screen with unique entries as follows:

Fields Name Type CARRID SPFLI-CARRID CONNID SPFLI-CONNID CITYFROM SPFLI-CITYFROM AIRPFROM SPFLI-AIRPFROM CITYTO SPFLI-CITYTO AIRPTO SPFLI-AIRPTO FLTIME SPFLI-FLTIME DEPTIME SPFLI-DEPTIME ARRTIME SPFLI-ARRTIME DISTANCE SPFLI-DISTANCE DISTID SPFLI-DISTID FLTYPE SPFLI-FLTYPE

Modules Name Typ Table/module SPFLI SPFLI

Module SPFLI: Demo table Parameter I/O Field name CARRID CARRID CONNID CONNID CITYFROM CITYFROM AIRPFROM AIRPFROM CITYTO CITYTO AIRPTO AIRPTO FLTIME FLTIME DEPTIME DEPTIME ARRTIME ARRTIME DISTANCE DISTANCE DISTID DISTID FLTYPE FLTYPE

All of the columns of table SPFLI are used as fields in the context. The interface of module SPFLI shows that the key fields CARRID and CONNID are the input parameters. 2. Now enter SFLIGHT in the Name or Table/Module column of the Modules [Page 1295] table and choose Enter. The system now makes the following additional entries on the screen:

1278

December 1999


SAP AG

BC - ABAP Programming Using Tables as Modules

Fields Ref. Field/type Name SPFLI-CARRID CARRID SPFLI-CONNID CONNID SPFLI-CITYFR CITYFROM SPFLI-AIRPFROM AIRPFROM SPFLI-CITYTO CITYTO SPFLI-AIRPTO AIRPTO SPFLI-FLTIME FLTIME SPFLI-DEPTIME DEPTIME SPFLI-ARRTIM ARRTIME SPFLI-DISTANC DISTANCE SPFLI-DISTID DISTID SPFLI-FLTYPE FLTYPE SFLIGHT-CARR CARRID SFLIGHT- FLDAT FLDATE SFLIGHT-PRICE PRICE SFLIGHT-CURR CURRENCY PLANETYPE SFLIGHT-PLANE SFLIGHT- SEATS SEATSMAX SFLIGHT-SEATS SEATSOCC PAYMENTSUM SFLIGHT-PAYM

Modules Name Typ Table/module SPFLI SPFLI SFLIGHT SFLIGHT

Module SFLIGHT: Demo table Parameter I/O Field name CARRID CARRID CONNID CONNID FLDATE FLDATE PRICE PRICE CURRENCY CURRENCY PLANETYPE PLANETYPE SEATSMAX SEATSMAX SEATSOCC SEATSOCC PLAYMENTSU PLAYMENTS

All of the columns in SFLIGHT which are not already contained in SPFLI are now also used in the context. The interface for module SFLIGHT shows that the key fields CARRID, CONNID and FLDATE are the input parameters of the new module. 3. Choose Save. Save the context. 4. Choose Check. The system checks the context for errors. 5. Choose Network graphic. The system displays the following graphic showing how values are derived within the context.

December 1999

1279


BC - ABAP Programming

SAP AG

Using Tables as Modules

Display area CONN Flight number Date Airline

CONN FLDA CARR CARR

Connections for Flights demo table

6. Generate the context. The system checks and saves your context before generating it. The context is finished and can be tested (see Testing a Context [Page 1288] ) and used in programs (see Using Contexts in ABAP Programs [Page 1298]).

1280

December 1999


SAP AG

BC - ABAP Programming Using Function Modules as Modules

Using Function Modules as Modules The following example demonstrates how to create a context called DOCU_TEST2 which uses a function module as a module.

Function module The function module is called SUBTRACTION, and is part of the function group TESTCONTEXT. It has the following interface:

Ref. type Import parameter Ref. Field/structure SFLIGHT-SEATSMAX V1 V2 SFLIGHT-SEATSOCC

Export parameter RESULT

Reference field/structure SFLIGHT-SEATSOCC

and the following source code: FUNCTION SUBTRACTION. RESULT = V1 - V2. ENDFUNCTION. The function module subtracts import parameter V2 from the other import parameter V1, and returns the value in RESULT. To create the context: 1. Enter SUBTRACTION in the Name or Table/Module column of the Modules [Page 1295] table and choose Enter. The system fills the tables on the context maintenance screen as follows:

December 1999

1281


BC - ABAP Programming

SAP AG

Using Function Modules as Modules

Fields Name Type SEATSMAX SFLIGHT-SEATSM SEATSOCC SFLIGHT-SEATSO SEATSOCC_1 SFLIGHT-SEATSO

Modules Name Typ Table/module SUBTRAC SUBTRACTION

Parameter V1 V2 RESULT

I/O

Field name SEATSMAX SEATSOCC SEATSOCC_1

All of the interface parameters for the function module are used as fields in the context. The system generates the names of the context fields. The interface of the SUBTRACTION module shows that the import parameters V1 and V2 are assigned to the key fields SEATSMAX and SEATSOCC, and that the export parameter RESULT is assigned to the dependent field SEATSOCC_1. 2. You do not have to adopt these generated names. You can, instead, overwrite the context field names in the Fields [Page 1293] and Modules [Page 1295] table. For example, as follows:

1282

December 1999


SAP AG

BC - ABAP Programming Using Function Modules as Modules

Name MAX OCC FREE

Fields Ref. Field/type SFLIGHT-SEATSMA SFLIGHT-SEATSOC SFLIGHT-SEATSOC

Modules Name Typ Table/module SUBTRAC SUBTRACTION

Parameter V1 V2 RESULT

I/O

Field name MAX OCC FREE

3. Choose Save. Save the context. 4. Choose Check. The system checks the context for errors. 5. Choose Network graphic. The system displays the following graphic showing how values are derived within the context.

Display area

Occupancy Max. occupancy

OCC

Test Function Module for

MAX

6. Generate the context. The system checks and saves your context before generating it. The context is finished and can be tested (see Testing a Context [Page 1288] ) and used in programs (see Using Contexts in ABAP Programs [Page 1298]).

December 1999

1283


BC - ABAP Programming

SAP AG

Using Function Modules as Modules

1284

December 1999


SAP AG

BC - ABAP Programming Using Contexts as Modules

Using Contexts as Modules The following example demonstrates how to create a context called DOCU_TEST3, which uses two other contexts, DOCU_TEST1 and DOCU_TEST2, as modules. DOCU_TEST1 and DOCU_TEST2 have already been used in the preceding examples Using Tables as Modules [Page 1278] and Using Function Modules as Modules [Page 1281]. 1. Enter DOCU_TEST1 and DOCU_TEST2 in the Name or Table/Module column of the Modules [Page 1295] table and choose Enter. The system fills the tables on the context maintenance screen as follows:

Fields Name Type CITYFROM SPFLI-CITYFR AIRPFROM SPFLI-AIRFROM CITYTO SPFLI-CITYTO AIRPTO SPFLI-AIRTO FLTIME SPFLI-FLTIME DEPTIME SPFLI-DEPTIME ARRTIME SPFLI-ARRTIM DISTANCE SPFLI-DISTANC DISTID SPFLI-DISTID FLTYPE SPFLI-FLTYPE FLDATE SFLIGHT- FLDAT PRICE SFLIGHT-PRICE CURRENCY SFLIGHT-CURR PLANETYPE SFLIGHT-PLANE SEATSMAX SFLIGHT- SEATS SEATSOCC SFLIGHT-SEATS PAYMENTSUM SFLIGHT-PAYM SEATSMAX_1 SFLIGHT-SEATS SEATSOCC_1 SFLIGHT-SEATS SEATSOCC_2 SFLIGHT-SEATS

Modules Name TypTable/modu DOCU_TEST1 DOCU_TES DOCU_TEST2 DOCU_TES

Module DOCU_TEST2: Test for D Parameter I/O Field name MAX SEATSMAX_1 OCC SEATSOCC_1 FREE SEATSOCC_2

All fields from the two contexts are used as fields in this context. The system generates the names of the context fields. 2. You do not have to use all of the context fields. You can also change the context field names in the Fields [Page 1293] and Modules [Page 1295] tables:

December 1999

1285


BC - ABAP Programming

SAP AG

Using Contexts as Modules

Fields Name Ref. Field/type CARRID SPFLI-CARRID CONNID SPFLI-CONNID FLDATE SFLIGHT-FLDATE SEATSMAX SFLIGHT-SEATSM SEATSOCC SFLIGHT-SEATSO FREE_SEATS SFLIGHT-SEATSO

Modules Name TypTable/modu DOCU_TEST1 DOCU_TES DOCU_TEST2 DOCU_TES

Module DOCU_TEST1: Test for D Parameter I/O Field name CARRID CARRID CONNID CONNID FLDATE FLDATE SEATSMAX SEATSMAX SEATSOCC SEATSOCC

In this example, we have kept the three key fields CARRID, CONNID and FLDATE, and deleted all dependent fields apart from SEATSMAX, SEATSOCC and FREE_SEATS. The output fields from module DOCU_TEST1, SEATSMAX and SEATSOCC are used as input fields for module DOCU_TEST2. The dependent field FREE_SEATS is filled from the output field FREE in DOCU_TEST2. 3. Choose Save. Save the context. 4. Choose Check. The system checks the context for errors. 5. Choose Network graphic. The system displays the following graphic showing how values are derived within the context.

1286

December 1999


SAP AG

BC - ABAP Programming Using Contexts as Modules

Display area

Flight number CONNID CONNID FLDATE Flight date FLDATE CARRID Airline CARRID

SEATSMAX/SEATSOCC Test for Documentation DOCU TEST1

Test for Documentation DOCU TEST2

6. Generate the context. The system checks and saves your context before generating it. The context is finished and can be tested (see Testing a Context [Page 1288] ) and used in programs (see Using Contexts in ABAP Programs [Page 1298]).

December 1999

1287


BC - ABAP Programming

SAP AG

Testing a Context

Testing a Context This section describes how to test a context. It uses the context DOCU_TEST2 from the previous example Using Function Modules as Modules [Page 1281]. To test a context, call the Context Builder (Transaction SE33) and enter the name of the context you wish to test in the Context field. Choose Test. If texts appear in a language other than the logon language when you test the context, you must regenerate it once. Afterwards, the translated texts will appear. The Context Builder: Testing screen is then displayed. To display the meanings of the various icons, choose Legend. Fields

Values

Max. occupancy Occpancy Occupancy

Legend Icon Meaning in fields Value unknown Value calculable Value known

Modules Test Function Module for Cont

Meaning in modules Module cannot be activated Module can be activated Module activated

Module type Table Function module Context Actions per module Display buffer contents Network graphic

To test the context, enter values in the key fields of the context. Choose Enter to accept the input values. If you want to use a blank character (SPACE) as an input value for a field, click on the traffic light symbol on the left hand side of the field to change the status of the input field.

Fields

Values

Max. occupancy 500 Occupancy 345 Occupancy

1288

Modules Test Function Module for Cont

December 1999


SAP AG

BC - ABAP Programming Testing a Context

If you enter values in all of the input fields, the system will be able to calculate all output fields. To activate the context, select the output fields required and choose Calculate values.

Fields

Values

Max. occupancy 500 Occupancy 345 Occupancy 155

Modules Test Function Module for Cont

By choosing individual fields, you can use the Context Builder: Testing screen to display the relationships between fields and modules. For example, if you choose the Test Function Module for Context module, the following is displayed:

Fields Max. occupancy Occupancy ? Occupancy

December 1999

Modules N N

Test Function Modu

Test Function Module for Cont

1289


BC - ABAP Programming

SAP AG

Buffering Contexts

Buffering Contexts The principal aim of contexts is to avoid the repeated calculation of frequently-used data which is derived from other key data. This is achieved by storing the derived data in the context buffer. Data for each module is stored separately in the buffer. The main difference between the context buffer and the database buffers in the database interface or the SAP table buffer is that it is only periodically refreshed (every hour on the hour).The system makes no attempt to update it synchronously, or even nearly synchronously. For this reason, you cannot use the buffer for every context, or for every module within a context. Rather, you should only use it for data which does not often change. In the Buffer type column of the Modules [Page 1295] table, you can set the type of buffer you want to use. This can be the context buffer itself (P), a temporary buffer (T), or no buffer at all (N).

The Individual Buffering Types •

Permanent (P) This is the default buffer setting, in which the cross-transaction application buffer is used. For more information about this buffer, see the keyword documentation for EXPORT/IMPORT TO/FROM SHARED BUFFER. The cross-transaction application buffer can contain up to 128 context entries. These entries are structured using a process similar to LRU (Least Recently Used). To display the contents of the context buffer on the current application server, choose Goto → Display buffer in the Context Builder. The buffer is reset every hour on the hour. You can also reset it manually in the Context Builder by choosing Edit → Reset buffer. This resets the buffer on all application servers.

Temporary (T) If you choose this buffer type, the derived data is only buffered within a transaction. Within a transaction the buffer can contain up to 1024 entries. These entries are exported in bundles into the cross-transaction application buffer. The results of the various instances of a context are stored in the same buffer within the program.

No buffer (N) If you choose No buffer, the derived data is not buffered. If you use this buffering type for all modules in a context, using the context will not improve system performance, but is merely a way of re-using program logic.

Permanent buffering can lead to problems when you are testing your Customizing settings. The Context Builder therefore allows you to de-activate the context buffer (buffering type P) during the current terminal session. To do this, choose Settings → Buffering. The system displays a dialog box. Select Inactive, and choose Continue. You can activate or de-activate the context buffer for a particular user by setting the user parameter BUF to Y or SPACE (default) or N using the Maintain users transaction (SU01).

Construction of the Buffer The context buffer contains two buffer tables for each module: •

1290

The I buffer (internal buffer), which saves each combination of module input parameters queried during the lifetime of the buffer, along with their derived values.

December 1999


SAP AG

BC - ABAP Programming Buffering Contexts

The E buffer (external buffer), which assigns the derived values in the module to the key values in the context. The E buffer is filled each time a query is made. The first time a query is made using a particular combination of module input parameters, the results are written to the I buffer without any reference to the key values for the context. If, however, the same combination of module input parameters is queried more than once (so that the combination already exists in the I buffer), the system writes the results to the E buffer along with the context key values). It is therefore possible for the results of a particular combination of module input parameters to appear more than once in the E buffer, since different combinations of key fields can lead to the same set of module input parameters.

The various modules within a context are linked by the derivation schema. The input parameters of a module are either key fields or output parameters of another module. The entries in the E buffer for modules which depend on other, previous modules are the same as the I buffer entries for those previous modules. The buffering type of the E buffer for the dependent module is the same as the lowest buffering type of any of the modules on which it depends. Thus, if one of the previous modules has buffering type N, the system will not store any entries in the E buffer of the dependent module. When you access the context buffer, either during testing or using the DEMAND statement, the system first searches in the E buffer of each module, followed by the I buffer. Access to the E buffer is more direct, and quicker than using the I buffer, which usually needs to be accessed more often. The inclusion of entries in the E buffer which have been queried more than once is an acceptance of data redundancy as the price for quicker access. The I buffer is a filter for the E buffer, only allowing redundant data when absolutely necessary. Together, the I and E buffers provide a balance of quick access time and high probability of finding an appropriate entry.

When you create your own contexts, you should bear in mind the advantages of this buffering concept. Try to include as many relationships between data objects in a single context for each program, rather than using several contexts in the same program. You can also combine a group of contexts as modules of a single, larger context. Within a context, the system buffers all intermediate results in an optimal form. If you are using separate contexts, there is no link between any of the individual buffers.

Deleting a Buffer You can delete the contents of a context buffer as follows: •

in the Context Builder (Transaction SE33), choose Edit → Delete buffer → Local server to delete the buffer contents for a context on the current application server, or Edit → Delete buffer → All servers to delete the buffer contents for a context on all application servers. You can use these functions when testing or buffering contexts.

in ABAP programs, you can use the function modules CONTEXT_BUFFER_DELETE_LOCAL and CONTEXT_BUFFER_DELETE to delete the buffer contents for a context on the local server or all servers respectively. You can use these function modules in conjunction with changes to database contents to ensure that the contents of the context buffer are always current.

December 1999

1291


BC - ABAP Programming

SAP AG

Buffering Contexts The following is an example which you could use in asynchronous update: DATA CONTEXT_NAME LIKE RS33F-FRMID. CONTEXT_NAME = 'DOCU_TEST1'. ... CALL FUNCTION 'CONTEXT_BUFFER_DELETE' IN UPDATE TASK EXPORTING CONTEXT_ID = CONTEXT_NAME EXCEPTIONS OTHERS = 0. .... COMMIT WORK. In the example, the system calls CONTEXT_BUFFER_DELETE as an update module. You could use it as the last update call following the database changes before the COMMIT WORK statement. For more information about asynchronous update, see Programming Database Updates [Page 1312]

1292

December 1999


SAP AG

BC - ABAP Programming Fields

Fields The following illustration shows the Fields table for the sample context DEMO_TRAVEL:

Name CARRID CONNID CITYFROM COUNTRYFR AIRPFROM CITYTO AIRPTO FLTIME DEPTIME ARRTIME DISTID FLTYPE DISTANCE CARRNAME CURRCODE NAME_FROM NAME_TO

Fields Type SPFLI-CARRID SPFLI-CONNID SPFLI-CITYFROM SPFLI-COUNTRYFR SPFLI-AIRPFROM SPFLI-CITYTO SPFLI-AIRPTO SPFLI-FLTIME SPFLI-DEPTIME SPFLI-ARRTIME SPFLI-DISTID SPFLI-FLTYPE SPFLI-DISTANCE SCARR-CARRNAME SCARR-CURRCODE SAIRPORT-NAME SAIRPORT-NAME

Text Airline Flight number From Country Departure airport To Arrival airport Flight time Departure time Arrival time Distance in Charter Distance Airline Local currency Airport FROM Airport TO

Default

L/T L L L L L L L L L L L L L L L L L

These, in turn, can become input parameters for further modules. You can enter new modules in the table directly, or fill it automatically by creating fields in the Modules [Page 1295] table. You can delete all unneeded fields from the context.

All fields in a context must have a reference to the ABAP Dictionary. To edit the table, use the selection column and the pushbuttons on the left hand side of the table. The table columns have the following meanings: •

Name

The field names which you use to address the fields in the context. •

Type

The Dictionary reference for the field. This can be a column of a database table or structure or a type in a type group. •

Text

The short text for the field from the ABAP Dictionary. •

Default value

December 1999

1293


BC - ABAP Programming

SAP AG

Fields You can enter default values for key fields in this column. If you do this, the key fields of each instance of the context which you create in an application program will already be supplied with these values. •

Like

In this column, you specify the type of reference between the field and the ABAP Dictionary. Enter L if the field refers to a database table or structure (LIKE), or T if the field refers to a type in a type group (TYPE). The system will normally assign the correct value automatically.

1294

December 1999


SAP AG

BC - ABAP Programming Modules

Modules The following illustration shows the Modules table for the sample context DEMO_TRAVEL:

Modules Name Msg No. Variable 1 Messa P/T/N Typ Table/Module Text E DEMO_CITIES DEMO_CITIESContext: Geogra P E SAIRPORT Airports 1 SAIRPORT1 P E Airports 2 SAIRPORT2 P SAIRPORT Airline 33 800 CARRID E SCARR P SCARR E Schedule SPFLI P SPFLI

Modules have input and output parameters. Together, they form the Interfaces [Page 1297] of the module. Modules describe the relationship between key fields and their dependent fields. Between them, all of the modules in a context derive all of the dependent fields from the key fields. Each individual module carries out its own part of that task. For example, one module uses some of the key fields as its input parameters to derive some of the dependent fields. These, in turn, can become input parameters for further modules. You can enter new modules in the table directly, or fill it automatically by creating fields in the Fields [Page 1293] table. To edit the table, use the selection column and the pushbuttons on the left hand side of the table. The table columns have the following meanings: •

Name

The names of all modules. •

Type

The module type. A module can be −

a table: The primary key fields of the table are input parameters. All other table fields are output parameters.

a function module: The import parameters of the function module are input parameters. The export parameters of the function module are output parameters.

another context: The key fields of contexts are input parameters. The dependent fields of contexts are output fields. Different modules can have the same type. This allows you to establish the same relationships between different groups of fields.

Table/Module

The name of the table, function module or context establishing the link between the context fields.

December 1999

1295


BC - ABAP Programming

SAP AG

Modules •

Text

A short text describing each module. •

Message ID, Number, Variable 1, ... , Variable 4, Type

A message, specified by its class (Message ID), number and type (Type). In the columns Variable 1, ... , Variable 4, you can specify context fields whose contents will replace the placeholders (‘&’) in the message. If the module is unable to supply all of the values requested in a DEMAND statement (because, for example, there is no dependent data in the database for the key fields), the system sends this message. You can use message handling in your application program for this message (see Message Handling in Contexts [Page 1305]). •

Buffer type

The buffering type of each context. For more information about buffering, see Buffering Contexts [Page 1290]

1296

December 1999


SAP AG

BC - ABAP Programming Interfaces

Interfaces When you select an entry in the Modules [Page 1295] table, the system fills the Interface table with the corresponding input and output parameters for that module. When you select a dependent field in the Fields [Page 1293] table, the system finds the module which determines the field and fills the Interface table with the corresponding input and output parameters for that module. For example, the interface for the module SPFLI in the sample context DEMO_TRAVEL looks like this:

Module SPFLI: Flight Connections Parameter I/O Field name Text Airline CARRID CARRID Flight number CONNID CONNID CITYFROM From CITYFROM AIRPFROM Departure airport AIRPFROM To CITYTO CITYTO Arrival airport AIRPTO AIRPTO Flight time FLTIME FLTIME Departure time DEPTIME DEPTIME Arrival time ARRTIME ARRTIME DISTID DISTID Distance in Charter FLTYPE FLTYPE

Module SPFLI is a database table in the ABAP Dictionary. The Parameters column contains its input and output parameters, and the Field name column contains the associated fields in the context. The direction of the arrow in the I/O column shows which parameters are input parameters and which are output parameters.

December 1999

1297


BC - ABAP Programming

SAP AG

Using Contexts in ABAP Programs

Using Contexts in ABAP Programs The following sections explain how to use contexts in your ABAP programs. As with logical databases, you will normally only use contexts supplied by SAP.

Finding and Displaying a Context [Page 1299] Creating an Instance of a Context [Page 1301] Supplying Context Instances with Key Values [Page 1302] Querying Data from Context Instances [Page 1303]

1298

December 1999


SAP AG

BC - ABAP Programming Finding and Displaying a Context

Finding and Displaying a Context To find an existing context and to familiarize yourself with it, use the initial screen of the Context Builder (Transaction SE33). •

Use the possible entries help for the Context field to display a list of existing contexts.

Use Test to display the names of the key fields and dependent fields, and the function of the context (see Testing a Context [Page 1288]).

Use Network graphic to display the derivation schema for the context.

Use Display with the Fields [Page 1293], Modules [Page 1295] and Interfaces [Page 1297] tables to display further information about the context field dependencies.

Enter the name DEMO_TRAVEL in the Context field on the initial screen of the Context Builder and choose Test.

Fields Airline Flight number From Country Departure airport To Country Arrival airport Flight time Departure time Arrival time Distance in Charter Distance Airline Local currency Airport FROM Airport TO

W e Values

Modules Airline Timetable Context: Geographical distance 2Airports 1 Airports 2

You will see that the context has two key fields, from which the other fields are derived, and that a total of five modules are used to define the relationships between the fields. Four of these modules are database tables, and one is another context. If you choose Network graphic, you will see the names of the key fields (CARRID and CONNID) and their relationships to the modules.

December 1999

1299


BC - ABAP Programming

SAP AG

Finding and Displaying a Context

Display area

Flight number CONNID CONNID Airline CARRID

CARRID

Connections for SPFLI

CARRID

Airline SCARR

AIRPTO

Airports 2 SAIRPORT2

AIRPFROM

Airports 2 SAIRPORT2

CITIFROM/CITYTO CONTEXT: Geographical DEMO CITIES

To see the names of all context fields, display the Fields [Page 1293] table in the Context Builder. You now have the most important information which you need to work with the context. Further information such as message texts and the buffering types for the modules are contained in the modules [Page 1295] table.

1300

December 1999


SAP AG

BC - ABAP Programming Creating an Instance of a Context

Creating an Instance of a Context As objects within the ABAP Workbench, contexts store the relationships between data, but no data itself. In your ABAP programs, you work with instances of contexts. These are runtime instances of contexts containing the actual data. To create a context instance, you must first declare the context in the program. You do this using the CONTEXTS statement:

Syntax CONTEXTS <c>. The context <c> must already exist as an object in the ABAP Workbench. The statement implicitly generates the special data type CONTEXT_<c>, which you can use to create context instances in a DATA statement:

Syntax DATA <inst> TYPE CONTEXT_<c>. This statement generates an instance <inst> of context <c>. You can create as many instances of a context as you like. Once you have created an instance, you can supply it with keywords (see Supplying Context Instances with Key Values [Page 1302]).

REPORT RSGCON01. CONTEXTS DEMO_TRAVEL. DATA: DEMO_TRAVEL_INST1 TYPE CONTEXT_DEMO_TRAVEL, DEMO_TRAVEL_INST2 TYPE CONTEXT_DEMO_TRAVEL. This program extract generates two instances of the context DEMO_TRAVEL.

December 1999

1301


BC - ABAP Programming

SAP AG

Supplying Context Instances with Key Values

Supplying Context Instances with Key Values Once you have created a context instance, you can supply values for its key fields. You do this using the SUPPLY statement:

Syntax SUPPLY <key1> = <f1> ... <keyn> = <fn> TO CONTEXT <inst>. This statement supplies the values <fn> to key fields <keyn> of a context instance <inst>. The fields of the context are contained in the Fields [Page 1293] table. When you have specified values for the key fields, you can derive the dependent fields of the context instance (see Querying Data from Context Instances [Page 1303]). If you assign new key fields to a context instance after deriving the dependent fields, the derived values are automatically invalidated, and will be re-calculated the next time you derive dependent values.

REPORT RSGCON01. CONTEXTS DEMO_TRAVEL. DATA: DEMO_TRAVEL_INST1 TYPE CONTEXT_DEMO_TRAVEL, DEMO_TRAVEL_INST2 TYPE CONTEXT_DEMO_TRAVEL. SUPPLY CARRID = 'LH' CONNID = '400' TO CONTEXT DEMO_TRAVEL_INST1. SUPPLY CARRID = 'AA' CONNID = '017' TO CONTEXT DEMO_TRAVEL_INST2. This program extract generates two instances of the context DEMO_TRAVEL and supplies both with key values.

1302

December 1999


SAP AG

BC - ABAP Programming Querying Data from Context Instances

Querying Data from Context Instances Once you have supplied a context instance with key values, you can query its dependent values. You do this using the DEMAND statement:

Syntax DEMAND <val1> = <f1> ... <valn> = <fn> FROM CONTEXT <inst> [MESSAGES INTO <itab>]. This statement fills the fields <fn> with the derived values <valn> from context instance <inst>. The fields of the context are contained in the Fields [Page 1293] table. In doing this, the system carries out the following steps: 1. It checks to see whether the context instance already contains valid derived values. This is the case if the values have already been calculated in a previous DEMAND statement and the instance has not since been supplied with new key field values using the SUPPLY statement. In this case, these values are assigned to fields <fn>. 2. If the context instance does not contain valid values, the system calculates new ones. It looks first in the context buffer (see Buffering Contexts [Page 1290]) for data records with the right key field values for the current context instance. If it finds the corresponding values, the system copies them as valid values into the context instance and assigns them to fields <fn>. 3. If there are no appropriate values in the context buffer, the system derives the values according to the context definition. The system also searches the context buffer during the derivation for intermediate results, which it uses if they are valid. When it has derived the values, the system saves all results in the context buffer, copies the values to the context instance and assigns them to fields <fn>. 4. If the system cannot determine the dependent values, it terminates the process, sets fields <fn> to their initial values and outputs the user message stored in the Modules [Page 1295] table. You can handle these messages in your programs by using the MESSAGES option (see Message Handling In Contexts [Page 1305] ).

REPORT RSGCON01. DATA: C_FROM LIKE SPFLI-CITYFROM, C_TO LIKE SPFLI-CITYTO, C_TIME LIKE SPFLI-FLTIME. CONTEXTS DEMO_TRAVEL. DATA: DEMO_TRAVEL_INST1 TYPE CONTEXT_DEMO_TRAVEL, DEMO_TRAVEL_INST2 TYPE CONTEXT_DEMO_TRAVEL. SUPPLY CARRID = 'LH' CONNID = '400' TO CONTEXT DEMO_TRAVEL_INST1. SUPPLY CARRID = 'AA' CONNID = '017' TO CONTEXT DEMO_TRAVEL_INST2. DEMAND CITYFROM = C_FROM CITYTO = C_TO FLTIME = C_TIME FROM CONTEXT DEMO_TRAVEL_INST1.

December 1999

1303


BC - ABAP Programming

SAP AG

Querying Data from Context Instances

WRITE: / C_FROM, C_TO, C_TIME. DEMAND CITYFROM = C_FROM CITYTO = C_TO FLTIME = C_TIME FROM CONTEXT DEMO_TRAVEL_INST2. WRITE: / C_FROM, C_TO, C_TIME. This program generates two instances of context DEMO_TRAVEL, supplies them both with key values and reads three dependent values from each of them.

1304

December 1999


SAP AG

BC - ABAP Programming Message Handling in Contexts

Message Handling in Contexts If a context cannot derive dependent data when you test it or execute the DEMAND statement, it can send a message to the user. The way in which messages are handled in contexts depends on the type of module in which the context could not determine data. Table and function module modules handle messages differently. Other contexts used as modules can be broken down to table and function module level.

Message Handling in Table Modules [Page 1306] Message Handling in Function Module Modules [Page 1308]

December 1999

1305


BC - ABAP Programming

SAP AG

Message Handling in Table Modules

Message Handling in Table Modules If you want to send user messages from table modules, you must first have defined messages for the individual modules in the Modules [Page 1295] table. The system cannot output a message for a table module where none is defined, but will simply reset the corresponding dependent values. When you query dependent data from context instances using the DEMAND statement, you can decide whether the system should handle the user message or whether you want to handle it yourself in the program.

Message Handling - System If you want the system to handle the message, use the basic form of the DEMAND statement without the MESSAGES option. The system will then behave as though the following statement occurred after the DEMAND statement: MESSAGE ID 'Message Id' TYPE 'T' NUMBER 'Number' WITH 'Variable 1' .... 'Variable 4'. The system takes the arguments for the MESSAGE statement from the corresponding entries in the Modules [Page 1295] table. Note that the system reaction to the various message types depends on the current user dialog (dialog screen, selection screen or list).

Message Handling - Program If you want to catch the message in your program, use the DEMAND statement using the option MESSAGES INTO <itab>. To do this, you need to define an internal table <itab> with the structure SYMSG. The system deletes the contents of <itab> table at the beginning of the DEMAND statement. Whilst it is processing the context, the system does not output or react to any messages, but writes their ID to <itab>. If there are messages in <itab> following the DEMAND statement, the system sets the return code SY-SUBRC to a value unequal to zero. This enables you to prevent automatic message handling with contexts and allows you to program your own using the entries in <itab>. This is important, for example, if you want to make particular fields on an entry screen ready for input again. In this case, you must base your message handling on the fields (using the FIELDS statement in screen flow logic, or the ABAP statement AT SELECTION-SCREEN for selection screens), and not on fields in the context.

Suppose the Modules [Page 1295] table in context DOCU_TEST1 (see Using Tables as Modules [Page 1278]) contained the following entries for module SPFLI:

Name Message ID SPFLI BCTRAIN

No. Variable 1 Variable 2 Variable 3 Variable 4 Messa P/T/ E 170 CARRID CONNID P

To demonstrate system message handling, execute the following program:

REPORT

RSGCON02.

DATA: C_FROM LIKE SPFLI-CITYFROM, C_TO LIKE SPFLI-CITYTO.

1306

December 1999


SAP AG

BC - ABAP Programming Message Handling in Table Modules

CONTEXTS DOCU_TEST1. DATA: CONTEXT_INST TYPE CONTEXT_DOCU_TEST1. SUPPLY CARRID = 'XX' CONNID = '400' TO CONTEXT CONTEXT_INST. DEMAND CITYFROM = C_FROM CITYTO = C_TO FROM CONTEXT CONTEXT_INST. WRITE: / C_FROM, C_TO. The program terminates with the following error message: No entries found for key XX 0400

To demonstrate program message handling, execute the following program:

REPORT

RSGCON03.

DATA: C_FROM LIKE SPFLI-CITYFROM, C_TO LIKE SPFLI-CITYTO. DATA ITAB LIKE SYMSG OCCURS 0 WITH HEADER LINE. CONTEXTS DOCU_TEST1. DATA: CONTEXT_INST TYPE CONTEXT_DOCU_TEST1. SUPPLY CARRID = 'XX' CONNID = '400' TO CONTEXT CONTEXT_INST. DEMAND CITYFROM = C_FROM CITYTO = C_TO FROM CONTEXT CONTEXT_INST MESSAGES INTO ITAB. WRITE: / C_FROM, C_TO. LOOP AT ITAB. WRITE: / ITAB-MSGTY, ITAB-MSGID, ITAB-MSGNO, ITAB-MSGV1, ITAB-MSGV2. ENDLOOP. The program outputs the following: E

AT

107

XX

0400

Instead of terminating with an error message, the program stores the message in the internal table ITAB, where it is available for you to process further.

December 1999

1307


BC - ABAP Programming

SAP AG

Message Handling in Function Module Modules

Message Handling in Function Module Modules In order for a message to be sent from a function module context module, the function module must contain the necessary exception handling. In other words, the function module must send the message using the MESSAGE ... RAISING statement. If the exception handling in the function module is programmed using the RAISE statement, the system reacts with a runtime error. For more information about exception handling in function modules, see Function Modules [Page 483]. The system sends the message specified in the MESSAGE... RAISING statement. Messages specified for function modules in the Modules [Page 1295] table are ignored. When you query dependent data from context instances using the DEMAND statement, you can decide whether the system should handle the user message or whether you want to handle it yourself in the program.

Message Handling - System If you want the system to handle the message, use the basic form of the DEMAND statement without the MESSAGES option. The system will then behave as though the MESSAGE statement in the function module occurred after the DEMAND statement. Note that the system reaction to the various message types depends on the current user dialog (dialog screen, selection screen or list).

Message Handling - Program If you want to catch the message in your program, use the DEMAND statement using the option MESSAGES INTO <itab>. To do this, you need to define an internal table <itab> with the structure SYMSG. The system deletes the contents of <itab> table at the beginning of the DEMAND statement. Whilst it is processing the context, the system does not output or react to any messages, but writes their ID to <itab>. If there are messages in <itab> following the DEMAND statement, the system sets the return code SY-SUBRC to a value unequal to zero. This enables you to prevent automatic message handling with contexts and allows you to program your own using the entries in <itab>. This is important, for example, if you want to make particular fields on an entry screen ready for input again. In this case, you must base your message handling on the fields (using the FIELDS statement in screen flow logic, or the ABAP statement AT SELECTION-SCREEN for selection screens), and not on fields in the context.

The function module PERCENT has the following source code:

FUNCTION PERCENT. RESULT = V1 - V2. IF V1 = 0. MESSAGE ID 'AT' TYPE 'E' NUMBER '012' RAISING DIV_ZERO. ELSE. RESULT = RESULT * 100 / V1. ENDIF. ENDFUNCTION.

1308

December 1999


SAP AG

BC - ABAP Programming Message Handling in Function Module

Modules Context DOCU_TEST4 uses this function module as its only module, with key fields MAX and OCC for input parameters V1 and V2 and the dependent field PERCENT for the output parameter RESULT. To demonstrate system message handling, execute the following program:

REPORT

RSGCON04.

DATA: INPUT_1 TYPE I, INPUT_2 TYPE I, PERCENTAGE TYPE I. CONTEXTS DOCU_TEST4. DATA: CONTEXT_INST TYPE CONTEXT_DOCU_TEST4. SUPPLY MAX = 00 OCC = 20 TO CONTEXT CONTEXT_INST. DEMAND PERCENT = PERCENTAGE FROM CONTEXT CONTEXT_INST. WRITE: / 'Percentage: ', PERCENTAGE. The program terminates with the following error message: This is an error message

To demonstrate program message handling, execute the following program:

REPORT

RSGCON05.

DATA: INPUT_1 TYPE I, INPUT_2 TYPE I, PERCENTAGE TYPE I. CONTEXTS DOCU_TEST4. DATA: CONTEXT_INST TYPE CONTEXT_DOCU_TEST4. DATA ITAB LIKE SYMSG OCCURS 0 WITH HEADER LINE. SUPPLY MAX = 00 OCC = 20 TO CONTEXT CONTEXT_INST. DEMAND PERCENT = PERCENTAGE FROM CONTEXT CONTEXT_INST MESSAGES INTO ITAB. WRITE: / 'Percentage: ', PERCENTAGE. LOOP AT ITAB. WRITE: / ITAB-MSGTY, ITAB-MSGID, ITAB-MSGNO, ITAB-MSGV1, ITAB-MSGV2. ENDLOOP. The program outputs the following: PERCENTAGE: E

AT

December 1999

0

012

1309


BC - ABAP Programming

SAP AG

Message Handling in Function Module Modules Instead of terminating with an error message, the program stores the message in the internal table ITAB, where it is available for you to process further.

1310

December 1999


SAP AG

BC - ABAP Programming Working With Contexts - Hints

Working With Contexts - Hints Creating Contexts •

You should include only a small number of key fields in your contexts.

The context graphic should not contain any isolated, unattached fields. In other words, all of the input parameters should be derived hierarchically from the key fields or output parameters of other modules. If this is not the case, you should split the context into two or more smaller contexts. Refer also to the hint in Buffering Contexts [Page 1290]

You should restrict the number of derived fields to those you really need, because:

Reading fewer fields reduces the load on the database

Fewer fields means that the buffer requires less space

The system can then read the buffer more quickly

You can always add more fields later if required. •

If you use a table, a function module or a context more than once as a module within a context, the module name should be made up as follows:<object name>_<suffix>. When you test your context, the suffix is automatically displayed after the long text.

Using Contexts •

Since the SUPPLY and DEMAND statements are not runtime-intensive, using them repeatedly causes no problems. In particular,

You should always use the SUPPLY command as soon as the key values are assigned. This reduces the risk of deriving obsolete values in the DEMAND statement. You do not need to make a preliminary query to see if the contents of the key fields have changed, since the system does this itself in the SUPPLY command.

You should always use the DEMAND statement immediately before using the derived values. This is to ensure that you always use up-to-date values. •

You should use local data objects as target fields for the DEMAND statement. This reduces the risk of obsolete values being used in error.

December 1999

1311


BC - ABAP Programming

SAP AG

Programming Database Updates

Programming Database Updates Open SQL [Page 1082] Transaktionen und Logical Units of Work [Page 1313] Das R/3-Sperrkonzept [Page 1322] Techniken der Verbuchung [Page 1328] Verbuchungsfunktionsbausteine anlegen [Page 1335] Verbuchungsfunktionsbausteine aufrufen [Page 1336] Spezielle Überlegungen zu LUWs [Page 1339] Fehlerbehandlung bei gebündelten Aktualisierungen [Page 1342] This section describes how to program database updates in the R/3 System.

See also the descriptions in the ABAP Editor under Utilities → Help on → ABAP Overview → Description of Syntax and Concepts → Transaction processing. For detailed information about the statements that you use for database updates, see the keyword documentation in the ABAP Editor.

1312

December 1999


SAP AG

BC - ABAP Programming Transactions and Logical Units of Work

Transactions and Logical Units of Work In everyday language, a transaction is a sequence of actions that logically belong together in a business sense and which either procure or process data. It covers a self-contained procedure, for example, generating a list of customers, creating a flight booking, or sending reminders to customers. From the point of view of the user, it forms a logical unit. The completeness and correctness of data must be assured within this unit. In the middle of a transaction, the data will usually be inconsistent. For example, when you transfer an amount in financial accounting, this must first be deducted from one account before being credited to another. In between the two postings, the data is inconsistent, since the amount that you are posting does not exist in either account. It is essential for application programmers to know that their data is consistent at the end of the transaction. If an error occurs, it must be possible to undo the changes made within a logical process. In the R/3 System, there are three terms frequently used in this connection:

Database Logical Unit of Work (LUW) A database LUW is the mechanism used by the database to ensure that its data is always consistent.

SAP LUW An SAP LUW is a logical unit consisting of dialog steps, whose changes are written to the database in a single database LUW.

SAP Transaction An SAP transaction is an application program that you start using a transaction code. It may contain one or more SAP LUWs. The following sections of this documentation explain these three terms in more detail.

December 1999

1313


BC - ABAP Programming

SAP AG

Database Logical Unit of Work (LUW)

Database Logical Unit of Work (LUW) From the point of view of database programming, a database LUW is an inseparable sequence of database operations that ends with a database commit. The database LUW is either fully executed by the database system or not at all. Once a database LUW has been successfully executed, the database will be in a consistent state. If an error occurs within a database LUW, all of the database changes since the beginning of the database LUW are reversed. This leaves the database in the state it had before the transaction started.

State changes Insert, Update, Delete Consistent State

COMMIT

Intermediate State

Consistent State

ROLLBACK or error

The database changes that occur within a database LUW are not actually written to the database until after the database commit. Until this happens, you can use a database rollback to reverse the changes. In the R/3 System, database commits and rollbacks can be triggered either implicitly or using explicit commands.

Implicit Database Commits in the R/3 System A work process can only execute a single database LUW. The consequence of this is that a work process must always end a database LUW when it finishes its work for a user or an external call. There are four cases in which work processes trigger an implicit database commit:

When a dialog step is completed Control changes from the work process back to the SAPgui.

When a function module is called in another work process (RFC). Control passes to the other work process.

When the called function module (RFC) in the other work process ends. Control returns to the calling work process.

Error dialogs (information, warning, or error messages) in dialog steps.

1314

December 1999


SAP AG

BC - ABAP Programming Database Logical Unit of Work (LUW)

Control passes from the work process to the SAPgui.

Explicit Database Commits in the R/3 System There are two ways to trigger an explicit database commit in your application programs:

Call the function module DB_COMMIT The sole task of this function module is to start a database commit.

Use the ABAP statement COMMIT WORK This statement starts a database commit, but also performs other tasks (refer to the keyword documentation for COMMIT WORK).

Implicit Database Rollbacks in the R/3 System The following cases lead to an implicit database rollback:

Runtime error in an application program This occurs whenever an application program has to terminate because of an unforeseen situation (for example, trying to divide by zero).

Termination message Termination messages are generated using the ABAP statement MESSAGE with the message type A or X. In certain cases (updates), they are also generated with message types I, W, and E. These messages end the current application program.

Explicit Database Rollbacks in the R/3 System You can trigger a database rollback explicitly using the ABAP statement ROLLBACK WORK. This statement starts a database rollback, but also performs other tasks (refer to the keyword documentation for COMMIT WORK). From the above, we can draw up the following list of points at which database LUWs begin and end.

A Database LUW Begins

Each time a dialog step starts (when the dialog step is sent to the work process).

Whenever the previous database LUW ends in a database commit.

Whenever the previous database LUW ends in a database rollback.

A Database LUW Ends

Each time a database commit occurs. This writes all of the changes to the database.

Each time a database rollback occurs. This reverses all of the changes made during the LUW.

Database LUWs and Database Locks As well as the database changes made within it, a database LUW also consists of database locks. The database system uses locks to ensure that two or more users cannot change the same data simultaneously, since this could lead to inconsistent data being written to the

December 1999

1315


BC - ABAP Programming

SAP AG

Database Logical Unit of Work (LUW) database. A database lock can only be active for the duration of a database LUW. They are automatically released when the database LUW ends. In order to program SAP LUWs, we need a lock mechanism within the R/3 System that allows us to create locks with a longer lifetime (refer to The R/3 Locking Concept [Page 1322].)

1316

December 1999


SAP AG

BC - ABAP Programming SAP LUW

SAP LUW Die Verbuchungsverwaltung [Extern] The Open SQL statements INSERT, UPDATE, MODIFY, and DELETE allow you to program database changes that extend over several dialog steps. Even if you have not explicitly programmed a database commit, the implicit database commit that occurs after a screen has been processed concludes the database LUW. The following diagram shows the individual database LUWs in a typical screen sequence:

Input

PBO

Screen 100 PAI

DB LUW

PBO

DB LUW

Save

Screen 200 PAI

PBO

DB LUW

Screen 300 PAI

DB LUW

Under this procedure, you cannot roll back the database changes from previous dialog steps. It is therefore only suitable for programs in which there is no logical relationship between the individual dialog steps. However, the database changes in individual dialog steps normally depend on those in other dialog steps, and must therefore all be executed or rolled back together. These dependent database changes form logical units, and can be grouped into a single database LUW using the bundling techniques listed below. A logical unit consisting of dialog steps, whose changes are written to the database in a single database LUW is called an SAP LUW. Unlike a database LUW, an SAP LUW can span several dialog steps, and be executed using a series of different work processes. If an SAP LUW contains database changes, you should either write all of them or none at all to the database. To ensure that this happens, you must include a database commit when your transaction has ended successfully, and a database rollback in case the program detects an error. However, since database changes from a database LUW cannot be reversed in a subsequent database LUW, you must make all of the database changes for the SAP LUW in a single database LUW. To maintain data integrity, you must bundle all of you database changes in the final database LUW of the SAP LUW. The following diagram illustrates this principle:

December 1999

1317


BC - ABAP Programming

SAP AG

SAP LUW

Input

PBO

DB LUW

Screen 100 PAI

PBO

DB LUW

Save

Screen 200 PAI

PBO

Screen 300 PAI

DB LUW

DB LUW

Bundling

The bundling technique for database changes within an SAP LUW ensures that you can still reverse them. It also means that you can distribute a transaction across more than one work process, and even across more than one R/3 System. The possibilities for bundling database changes within an SAP LUW are listed below: The simplest form of bundling would be to process a whole application within a single dialog step. Here, the system checks the user’s input and updates the database without a database commit occurring within the dialog step itself. Of course, this is not suitable for complex business processes. Instead, the R/3 Basis system contains the following bundling techniques.

Bundling using Function Modules for Updates If you call a function module using the CALL FUNCTION... IN UPDATE TASK statement, the function module is flagged for execution using a special update work process. This means that you can write the Open SQL statements for the database changes in the function module instead of in your program, and call the function module at the point in the program where you would otherwise have included the statements. When you call a function module using the IN UPDATE TASK addition, it and its interface parameters are stored as a log entry in a special database table called VBLOG. The function module is executed using an update work process when the program reaches the COMMIT WORK statement. After the COMMIT WORK statement, the dialog work process is free to receive further user input. The dialog part of the transaction finishes with the COMMIT WORK statement. The update part of the SAP LUW then begins, and this is the responsibility of the update work process. The SAP LUW is complete once the update process has committed or rolled back all of the database changes.

1318

December 1999


SAP AG

BC - ABAP Programming SAP LUW

For further information about how to create function modules for use in update, refer to Creating Function Modules for Database Updates [Page 1335] During the update, errors only occur in exceptional cases, since the system checks for all logical errors, such as incorrect entries, in the dialog phase of the SAP LUW. If a logical error occurs, the program can terminate the update using the ROLLBACK WORK statement. Then, the function modules are not called, and the log entry is deleted from table VBLOG. Errors during the update itself are usually technical, for example, memory shortage. If a technical error occurs, the update work process triggers a database rollback, and places the log entry back into VBLOG. It then sends a mail to the user whose dialog originally generated the VBLOG entry with details of the termination. These errors must be corrected by the system administrator. After this, the returned VBLOG entries can be processed again. For further information about update administration, see Update Administration This technique of bundling database changes in the last database LUW of the SAP LUW allows you to update the database asynchronously, reducing the response times in the dialog work process. You can, for example, decouple the update entirely from the dialog work process and use a central update work process on a remote database server.

Bundling Using Subroutines The statement PERFORM ON COMMIT calls a subroutine in the dialog work process. However, it is not executed until the system reaches the next COMMIT WORK statement. Here, as well, the ABAP statement COMMIT WORK defines the end of the SAP LUW, since all statements in a subroutine called with PERFORM ON COMMIT that make database changes are executed in the database LUW of the corresponding dialog step.

COMMIT WORK

FORM x

FORM y

DB COMMIT

PERFORM y ON COMMIT

DB COMMIT

PERFORM x ON COMMIT

DB COMMIT

Update in Dialog Work Process

FORM x FORM y

The advantage of this bundling technique against CALL FUNCTION... IN UPDATE TASK is better performance, since the update data does not have to be written into an extra table. The disadvantage, however, is that you cannot pass parameters in a PERFORM... ON COMMIT statement. Data is passed using global variables and ABAP memory. There is a considerable danger of data inconsistency when you use this method to pass data.

December 1999

1319


BC - ABAP Programming

SAP AG

SAP LUW Bundling Using Function Modules in Other R/3 Systems Function modules that you call using CALL FUNCTION... IN BACKGROUND TASK DESTINATION... are registered for background execution in another R/3 System when the program reaches the next COMMIT WORK statement (using Remote Function Call). After the COMMIT WORK, the dialog process does not wait for these function modules to be executed (asynchronous update). All of the function modules that you register in this way are executed together in a single database LUW. These updates are useful, for example, when you need to maintain identical data in more than one database. For further details, refer to the keyword documentation. For more details of RFC processing, refer to the Remote Communications section of the Basis Services documentation.

1320

December 1999


SAP AG

BC - ABAP Programming SAP Transactions

SAP Transactions An SAP LUW is a logical unit consisting of dialog steps, whose changes are written to the database in a single database LUW. In an application program, you end an SAP LUW with either the COMMIT WORK or ROLLBACK WORK statement. An SAP transaction is an application program that you start using a transaction code. It may contain one or more SAP LUWs. Whenever the system reaches a COMMIT WORK or ROLLBACK WORK statement that is not at the end of the last dialog step of the SAP transaction, it opens a new SAP LUW. If a particular application requires you to write a complex transaction, it can often be useful to arrange logical processes within the SAP transaction into a sequence of individual SAP LUWs. You can structure SAP transactions as follows:

With one or more SAP LUWs. Transactions in this form consist entirely of processing blocks (dialog modules, event blocks, function module calls, and subroutines). You should be careful to ensure that external subroutines or function modules do not lead to COMMIT WORK or ROLLBACK WORK statements accidentally being executed.

By inserting an SAP LUW The ABAP statements CALL TRANSACTION (start a new transaction), SUBMIT (start an executable program), and CALL FUNCTION... DESTINATION (call a function module using RFC) open a new SAP LUW. When you call a program, it always opens its own SAP LUW. However, it does not end the LUW of the SAP transaction that called it. This means that a COMMIT WORK or ROLLBACK WORK statement only applies to the SAP LUW of the called program. When the new LUW is complete, the system carries on processing the first SAP LUW.

By running two SAP LUWs in parallel The CALL FUNCTION... STARTING NEW TASK statement calls a function module asynchronously in a new session. Unlike normal function module calls, the calling transaction carries on with its own processing as soon as the function module has started, and does not wait for it to finish processing. The function call is asynchronous. The called function module can now call its own screens and interact with the user.

December 1999

1321


BC - ABAP Programming

SAP AG

The R/3 Lock Concept

The R/3 Lock Concept Das R/3 Sperrkonzept [Extern] Reasons for Setting Locks Suppose a travel agent want to book a flight. The customer wants to fly to a particular city with a certain airline on a certain day. The booking must only be possible if there are still free places on the flight. To avoid the possibility of overbooking, the database entry corresponding to the flight must be locked against access from other transactions. This ensures that one user can find out the number of free places, make the booking, and change the number of free places without the data being changed in the meantime by another transaction.

Lock Mechanisms in the Database System The database system automatically sets database locks when it receives change statements (INSERT, UPDATE, MODIFY, DELETE) from a program. Database locks are physical locks on the database entries affected by these statements. You can only set a lock for an existing database entry, since the lock mechanism uses a lock flag in the entry. These flags are automatically deleted in each database commit. This means that database locks can never be set for longer than a single database LUW; in other words, a single dialog step in an R/3 application program. Physical locks in the database system are therefore insufficient for the requirements of an R/3 transaction. Locks in the R/3 System must remain set for the duration of a whole SAP LUW, that is, over several dialog steps. They must also be capable of being handled by different work processes and even different application servers. Consequently, each lock must apply on all servers in that R/3 System.

SAP Locks To complement the SAP LUW concept, in which bundled database changes are made in a single database LUW, the R/3 System also contains a lock mechanism, fully independent of database locks, that allows you to set a lock that spans several dialog steps. These locks are known as SAP locks. The SAP lock concept is based on lock objects. Lock objects allow you to set an SAP lock for an entire application object. An application object consists of one or more entries in a database table, or entries from more than one database table that are linked using foreign key relationships. Before you can set an SAP lock in an ABAP program, you must first create a lock object in the ABAP Dictionary. A lock object definition contains the database tables and their key fields on the basis of which you want to set a lock. When you create a lock object, the system automatically generates two function modules with the names ENQUEUE_<lock object name> and DEQUEUE_<lock object name>. You can then set and release SAP locks in your ABAP program by calling these function modules in a CALL FUNCTION statement.

1322

December 1999


SAP AG

BC - ABAP Programming The R/3 Lock Concept

Save

CALL FUNCTION 'ENQUEUE…'

COMMIT WORK

Screen 100

Screen 200

Screen 300

SAP LUW

Screen x

Database Updates

See also: Example Transaction: SAP Locking [Page 1326]. These function modules are executed in a special enqueue work process. Within an R/3 System, enqueue work processes run on a single application server. This server maintains a central lock table for the entire R/3 System in its shared memory.

SAPgui

SAPgui

Dispatcher

Dialog WP

Message Server

Dispatcher

Enqueue WP

Dialog WP

Enqueue Table

Database Management System Application Data The enqueue function module sets an SAP lock by writing entries in the central lock table. If the lock cannot be set because the application object (or a part of it) is already locked, this is

December 1999

1323


BC - ABAP Programming

SAP AG

The R/3 Lock Concept reflected in the return code sy-subrc. The following diagram shows the components of the R/3 System that are involved in setting a lock. Unlike the database, which sets physical locks, the SAP lock mechanism sets logical locks. This means that

A locked database entry is not physically locked in the database table. The lock entry is merely entered as a lock argument in the central R/3 lock table. The lock argument is made up of the primary key field values for the tables in the lock object. These are import parameters of the enqueue function module. The lock is independent of database LUWs. It is released either implicitly when the database update or the SAP transaction ends, or explicitly, using the corresponding dequeue function module. You can use a special parameter in the update function module to set the exact point at which the lock is released during the database update.

A locked entry does not necessarily have to exist in a database table. You can, for example, set a lock as a precaution for a database entry that is not written to the database until the update at the end of the SAP LUW.

The effectiveness of the locks depends on cooperative application programming. Since there are no physical locks in the database tables themselves, all programs that use the same application objects must look in the central table themselves for any locks. There is no mechanism that automatically prevents a program from ignoring the locks in the lock table.

Lock Types There are two types of lock in the R/3 System:

Shared lock Shared locks (or read locks) allow you to prevent data from being changed while you are reading it. They prevent other programs from setting an exclusive lock (write lock) to change the object. It does not, however, prevent other programs from setting further read locks.

Exclusive lock Exclusive locks (or write locks) allow you to prevent data from being changed while you are changing it yourself. An exclusive lock, as its name suggests, locks an application object for exclusive use by the program that sets it. No other program can then set either a shared lock or an exclusive lock for the same application object.

Lock Duration When you set a lock, you should bear in mind that if it remains set for a long time, the availability of the object to other transactions is reduced. Whether or not this is acceptable depends on the nature of the task your program is performing. Remember in particular that setting too many shared locks without good reason can have a considerable effect on programs that work with database tables. If several programs running concurrently all set a shared lock for the same application object in the system, it can make it almost impossible to set an exclusive lock, since the program that needs to set that lock will be unable to find any time when there are no locks at all set for that object. Conversely, a single exclusive lock prevents all other programs from reading the locked object.

1324

December 1999


SAP AG

BC - ABAP Programming The R/3 Lock Concept

At the end of an SAP LUW, you should release all locks. This either happens automatically during the database update, or explicitly, when you call the corresponding dequeue function module. Locks that are not linked to a database update are released at the end of the SAP transaction.

December 1999

1325


BC - ABAP Programming

SAP AG

Example Transaction: SAP Locking

Example Transaction: SAP Locking Ãœbernahme [Extern] The following example transaction shows how you can lock and unlock database entries using a lock object. It lets the user request a given flight (on screen 100) and display or update it (on screen 200). If the user chooses Change, the table entry is locked; if he or she chooses Display, it is not.

The example uses the lock object ESFLIGHT and its function modules ENQUEUE_ESFLIGHT and DEQUEUE_ESFLIGHT to lock and unlock the object. For more information about creating lock objects and the corresponding function modules, refer to the Lock objects section of the ABAP Dictionary documentation. The PAI processing for screen 100 in this transaction processes the user input and prepares for the requested action (Change or Display). If the user chooses Change, the program locks the relevant database object by calling the corresponding ENQUEUE function.

MODULE USER_COMMAND_0100 INPUT. CASE OK_CODE. WHEN 'SHOW'.... WHEN 'CHNG'. * <...Authority-check and other code...> CALL FUNCTION 'ENQUEUE_ESFLIGHT' EXPORTING MANDT = SY-MANDT CARRID = SPFLI-CARRID CONNID = SPFLI-CONNID EXCEPTIONS FOREIGN_LOCK = 1 SYSTEM_FAILURE = 2 OTHERS = 3. IF SY-SUBRC NE 0. MESSAGE ID SY-MSGID TYPE 'E' NUMBER SY-MSGNO WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

1326

December 1999


SAP AG

BC - ABAP Programming Example Transaction: SAP Locking

ENDIF. ... The ENQUEUE function module can trigger the following exceptions: FOREIGN_LOCK determines whether a conflicting lock already exists. The system variable SYMSGV1 contains the name of the user that owns the lock. The SYSTEM_FAILURE exception is triggered if the enqueue server is unable to set the lock for technical reasons. At the end of a transaction, the locks are released automatically. However, there are exceptions if you have called update routines within the transaction. You can release a lock explicitly by calling the corresponding DEQUEUE module. As the programmer, you must decide for yourself the point at which it makes most sense to release the locks (for example, to make the data available to other transactions). If you need to use the DEQUEUE function module call several times in a program, it makes good sense to write it in a subroutine, which you then call as required. The subroutine UNLOCK_FLIGHT calls the DEQUEUE function module for the lock object ESFLIGHT:

FORM UNLOCK_FLIGHT. CALL FUNCTION 'DEQUEUE_ESFLIGHT' EXPORTING MANDT = SY-MANDT CARRID = SPFLI-CARRID CONNID = SPFLI-CONNID EXCEPTIONS OTHERS = 1. SET SCREEN 100. ENDFORM. You might use this for the BACK and EXIT functions in a PAI module for screen 200 in this example transaction. In the program, the system checks whether the user leaves the screen without having saved his or her changes. If so, the PROMPT_AND_SAVE routine sends a reminder, and gives the user the opportunity to save the changes. The flight can be unlocked by calling the UNLOCK_FLIGHT subroutine.

MODULE USER_COMMAND_0200 INPUT. CASE OK_CODE. WHEN 'SAVE'.... WHEN 'EXIT'. CLEAR OK_CODE. IF OLD_SPFLI NE SPFLI. PERFORM PROMPT_AND_SAVE. ENDIF. PERFORM UNLOCK_FLIGHT. LEAVE TO SCREEN 0. WHEN 'BACK'....

December 1999

1327


BC - ABAP Programming

SAP AG

Update Techniques

Update Techniques The main update technique for bundling database changes in a single database LUW is to use CALL FUNCTION... IN UPDATE TASK. This section describes various ways of updating the database. A program can send an update request using COMMIT WORK

To the update work process, where it is processed asynchronously. The program does not wait for the work process to finish the update (Asynchronous Update [Page 1329]).

For asynchronous processing in two steps (Updating Asynchronously in Steps [Page 1332].)

To the update work process, where it is processed synchronously. The program waits for the work process to finish the update (Synchronous Update [Page 1333]).

To its own work process locally. In this case, of course, the program has to wait until the update is finished (Local Update [Page 1334].)

1328

December 1999


SAP AG

BC - ABAP Programming Asynchronous Update

Asynchronous Update A typical R/3 installation contains dialog work processes and at least one update work process. The update work processes are responsible for updating the database. When an ABAP program reaches a COMMIT WORK statement, any function modules from CALL FUNCTION... IN UPDATE TASK statements are released for processing in an update work process. The dialog process does not wait for the update to finish. This kind of update is called asynchronous update.

Save

CALL FUNCTION 'ENQUEUE…'

COMMIT WORK

Screen 100

Screen 200

Screen 300

Screen x

Update part of SAPLUW

Dialog part of SAP LUW CALL FUNCTION IN UPDATE TASK

Database Updates

The following diagram shows a typical asynchronous update:

December 1999

1329


BC - ABAP Programming

SAP AG

Asynchronous Update

SAPgui

SAPgui Message Server

Dispatcher Application Server 1

Dialog WP

Dispatcher Application Server 2

1

Dialog WP 2

Update WP

4

Enqueue WP 7

3

6

5

Database Management System Application Data

Data (VBLOG)

For example, suppose a user wants to change an entry in a database table, or add a new one. He or she enters the necessary data, and then starts the update process by choosing Save. This starts the following procedure in the ABAP program: 1. Firstly, the program locks the database entry against other users, using the enqueue work process (or the message server in the case of a distributed system). This generates an entry in the lock table. The user is informed whether the update was successful, or whether the lock could not be set because of other users. 2. If the lock is set, the program reads the entry that is to be changed and modifies it. If the user has created a new entry, the program checks whether a record with the same key values already exists. 3. In the current dialog work process, the program calls a function module using CALL FUNCTION... IN UPDATE TASK, and this writes the change details as an entry in table VBLOG. 4. When the program is finished (maybe after further dialog steps), a COMMIT WORK statement starts the final part of the SAP LUW. The work process that is processing the current dialog step starts an update work process. 5. Based on the information passed to it from the dialog work process, the update work process reads the log entries belonging to the SAP LUW from table VBLOG. 6. The update work process passes this data to the database for updating, and analyzes the return message from the database. If the update was successful, the update work process triggers a database commit after the last database change and deletes the log entries from table VBLOG. If an error occurred, the update work process triggers a database rollback, leaves the log entries in table VBLOG, flags them as containing errors, and sends a SAPoffice message to the user, who should then inform the system administrator. 7. The corresponding entries in the lock table are reset by the update work process.

1330

December 1999


SAP AG

BC - ABAP Programming Asynchronous Update

Asynchronous update is useful when response time from the transaction is critical, and the database updates themselves are so complex that they justify the extra system load of logging them in VBLOG. If you are running a transaction in a background work process, asynchronous update offers no advantages.

December 1999

1331


BC - ABAP Programming

SAP AG

Updating Asynchronously in Steps

Updating Asynchronously in Steps When you process a VBLOG entry asynchronously, you can do it in two update steps. This allows you to divide the contents of the update into primary and secondary steps. The primary step is called V1, the secondary step V2. The V1 and V2 steps of a log entry are processed in separate database LUWs. The entries in the lock table are usually deleted once the V1 step has been processed. There is no locking for the V2 step. Dividing up the update process allows you to separate time-critical updates that require database locks from less critical data updates that do not need locks. V2 steps receive lower priority from the dispatcher than V1 steps. This ensures that the time- and lock-critical updates are processed quickly, even when the system is busy. If an error occurs during the V1 processing, the database rollback applies to all V1 steps in the log entry. The entire entry is replaced in table VBLOG. If an error occurs during V2 processing, all of the V2 steps in the log entry are replaced in table VBLOG, but the V1 updates are not reversed. The system marks rolled-back function modules as error functions in the update task log. The error can then be corrected and the function restarted later. To access the update task log, choose Tools → Administration → Monitoring → Update. For further information about update administration, see the Managing Updating section of the BC System Services documentation.

1332

December 1999


SAP AG

BC - ABAP Programming Synchronous Update

Synchronous Update In synchronous update, you do not submit an update request using CALL FUNCTION... IN UPDATE TASK. Instead, you use the ABAP statement COMMIT WORK AND WAIT. When the update is finished, control passes back to the program. Synchronous update works in the same way as bundling update requests in a subroutine (PERFORM ON COMMIT). This kind of update is useful when you want to use both asynchronous and synchronous processing without having to program the bundles in two separate ways. The following diagram illustrates the synchronous update process:

Save

CALL FUNCTION 'ENQUEUE…'

COMMIT WORK AND WAIT

Screen 100

Screen 200

Screen 300

Dialog part of SAP LUW CALL FUNCTION IN UPDATE TASK

Screen x

Update part of SAPLUW

Database Updates

Use this type of update whenever the changed data is required immediately. For example, you may want to link SAP LUWs together where one LUW depends on the results of the previous one.

December 1999

1333


BC - ABAP Programming

SAP AG

Local Update

Local Update In a local update, the update program is run by the same work process that processed the request. The dialog user has to wait for the update to finish before entering further data. This kind of update is useful when you want to reduce the amount of access to the database. The disadvantage of local updates is their parallel nature. The updates can be processed by many different work processes, unlike asynchronous or synchronous update, where the update is serialized due to the fact that there are fewer update work processes (and maybe only one). You switch to local update using the ABAP statement SET UPDATE TASK LOCAL. This statement sets a “local update switch�. When it is set, the system interprets CALL FUNCTION IN UPDATE TASK as a request for local update. The update is processed in the same work process as the dialog step containing the COMMIT WORK. The transaction waits for the update to finish before continuing. As an example, suppose you have a program that uses asynchronous update that you normally run in dialog mode. However, this time you want to run it in the background. Since the system response time is irrelevant when you are running the program in the background, and you only want the program to continue processing when the update has actually finished, you can set the SET UPDATE TASK LOCAL switch in the program. You can then use a system variable to check at runtime whether the program is currently running in the background. By default, the local update switch is not set, and it is reset after each COMMIT WORK or ROLLBACK WORK. You therefore need to include a SET UPDATE TASK LOCAL statement at the beginning of each SAP LUW. If you reset data within the local update, the ROLLBACK WORK statement applies to both the dialog and the update part of the transaction, since no new SAP LUW is started for the update.

1334

December 1999


SAP AG

BC - ABAP Programming Creating Update Function Modules

Creating Update Function Modules To create a function module, you first need to start the Function Builder. Choose Tools → ABAP Workbench, Function Builder. For more information about creating function modules, refer to the ABAP Workbench Tools [Extern] documentation. To be able to call a function module in an update work process, you must flag it in the Function Builder. When you create the function module, set the Process Type attribute to one of the following values:

Update with immediate start

Set this option for high priority (“V1”) functions that run in a shared (SAP LUW). These functions can be restarted by the update task in case of errors.

Update w. imm. start, no restart

Set this option for high priority (“V1”) functions that run in a shared (SAP LUW). These functions may not be restarted by the update task.

Update with delayed start

Set this option for low priority (“V2”) functions that run in their own update transactions. These functions can be restarted by the update task in case of errors. To display the attributes screen in the Function Builder, choose Goto → Administration.

Defining the Interface Function modules that run in the update task have a limited interface:

Result parameters or exceptions are not allowed since update-task function modules cannot report on their results.

You must specify input parameters and tables with reference fields or reference structures defined in the ABAP Dictionary.

December 1999

1335


BC - ABAP Programming

SAP AG

Calling Update Functions

Calling Update Functions Synchronous or Asynchronous Processing? Function modules that run in the update task can run synchronously or asynchronously. You determine this by the form of the commit statement you use:

•

COMMIT WORK This is the standard form, which specifies asynchronous processing. Your program does not wait for the requested functions to finish processing.

•

COMMIT WORK AND WAIT This form specifies synchronous processing. The commit statement waits for the requested functions to finish processing. Control returns to your program after all high priority (V1) function modules have run successfully. The AND WAIT form is convenient for switching old programs to synchronous processing without having to re-write the code. Functionally, using AND WAIT for update-task updates is just the same as dialog-task updates with PERFORM ON COMMIT.

Parameter Values at Execution In ABAP, you can call update-task function modules in two different ways. The way you choose determines what parameter values are used when the function module is actually executed. Parameter values can be set either at the time of the CALL FUNCTION statement, or at the time of the COMMIT WORK. The following sections explain. Calling Update Functions Directly [Page 1337] Adding Update Task Calls to a Subroutine [Page 1338].

The examples in these sections show asynchronous commits with COMMIT WORK.

1336

December 1999


SAP AG

BC - ABAP Programming Calling Update Functions Directly

Calling Update Functions Directly To call a function module directly, use CALL FUNCTION IN UPDATE TASK directly in your code.

CALL FUNCTION 'FUNCTMOD' IN UPDATE TASK EXPORTING... The system then logs your request and executes the function module when the next COMMIT WORK statement is reached. The parameter values used to execute the function module are those current at the time of the call.

a = 1. CALL FUNCTION 'UPD_FM' IN UPDATE TASK EXPORTING PAR = A... a = 2. CALL FUNCTION 'UPD_FM' IN UPDATE TASK EXPORTING PAR = A... a = 3. COMMIT WORK. Here, the function module UPD_FM is performed twice in the update task: the first time, with value 1 in PAR, the second time with value 2 in PAR.

December 1999

1337


BC - ABAP Programming

SAP AG

Adding Update Task Calls to a Subroutine

Adding Update Task Calls to a Subroutine You can also put the CALL FUNCTION IN UPDATE TASK into a subroutine and call the subroutine with:

PERFORM SUBROUT ON COMMIT. If you choose this method, the subroutine is executed at the commit. Thus the request to run the function in the update task is also logged during commit processing. As a result, the parameter values logged with the request are those current at the time of the commit.

a = 1. PERFORM F ON COMMIT. a = 2. PERFORM F ON COMMIT. a = 3. COMMIT WORK. FORM f. CALL FUNCTION 'UPD_FM' IN UPDATE TASK EXPORTING PAR = A. ENDFORM. In this example, the function module UPD_FM is carried out with the value 3 in PAR. The update task executes the function module only once, despite the two PERFORM ON COMMIT statements. This is because a given function module, logged with the same parameter values, can never be executed more than once in the update task. The subroutine itself, containing the function module call, may not have parameters.

The method described here is not suitable for use inside dialog module code. However, if you do need to use a dialog module, refer to Dialog Modules That Call Update Modules.

1338

December 1999


SAP AG

BC - ABAP Programming Special LUW Considerations

Special LUW Considerations In the update task queue, the system identifies all function modules belonging to the same transaction [Page 1313] (SAP LUW) by assigning them a common update key. At the next COMMIT WORK, the update task reads the queue and processes all requests with the predefined update key. If your program calls an update-task function module, the request to execute the module (or the subroutine calling it) is provided with the update key of the current LUW and placed in the queue. The following sections explain what happens to LUWs when update function modules are included in other modules (transactions or dialog modules) that are called by other programs.

Transactions That Call Update Task Functions [Page 1340] Dialog Modules That Call Update Task Functions [Page 1341]

December 1999

1339


BC - ABAP Programming

SAP AG

Transactions That Call Update Function Modules

Transactions That Call Update Function Modules If your program calls another program that itself calls an update function module, you should be aware of the following: When the new program is called, a new SAP LUW begins, and a new update key is generated. This key is used to identify all update-task operations requested during the called program. When returning from the program, the LUW of the calling program is restored together with the old update key. If the called program does not contain its own COMMIT WORK, the database update requests are not processed, and the update function modules are not called. In the following example, F1, F2, and F3 are update function modules:

ABAP/4 Programm CALL FUNCTION ´F1´ IN UPDATE TASK ... CALL TRANSACTION ZABC ... CALL FUNCTION ´F3´ IN UPDATE TASK ... COMMIT WORK.

Transaktion ZABC . . .

CALL FUNCTION ´F2´ IN UPDATE TASK ... . . . LEAVE.

Here, F1 and F3 are executed in the update task, because the COMMIT WORK for the main program triggers their execution. However, since transaction ZABC contains no COMMIT WORK statement, the function F2 is never executed by the update task.

1340

December 1999


SAP AG

BC - ABAP Programming Dialog Modules that Call Update

Function Modules

Dialog Modules that Call Update Function Modules Unlike transactions and executable programs (reports), dialog modules do not start a new SAP LUW. Calls to update-task function modules from a dialog module use the same update key as the ones in the calling program. The result is that calls to update function modules from a dialog module are executed only if a COMMIT WORK statement occurs in the calling program.

If you place a COMMIT WORK in a dialog module, it does commit changes to the database (for example, with UPDATE).However, it does not start the update task. The function modules are not actually executed until a COMMIT WORK statement occurs in the calling program.

If you use dialog modules, try to avoid including calls to update function modules in subroutines called with PERFORM ON COMMIT. In general, any occurrence of PERFORM ON COMMIT (with or without update-task function calls) in a dialog module can cause problems. This is because dialog modules have their own roll area, which disappears when the module finishes. Consequently, all local data (including data used for parameter values when calling an update function module) disappears as soon as the commit in the main program is reached. If you must call an update function module in a subroutine in a dialog module, you must ensure that the values of the actual parameters still exist when the update-task function actually runs. To do this, you can store the required values with EXPORT TO MEMORY and then import them back into the main program (IMPORT FROM MEMORY) before the COMMIT WORK statement.

December 1999

1341


BC - ABAP Programming

SAP AG

Error Handling for Bundled Updates

Error Handling for Bundled Updates Runtime errors can occur during execution of bundled updates. How are they handled? In general, COMMIT WORK processing occurs in the following order: 1. All dialog-task FORM routines logged with PERFORM ON COMMIT are executed. 2. All high-priority (V1) update-task function modules are executed. The end of V1-update processing marks the end of the . If you used COMMIT WORK AND WAIT to trigger commit processing, control returns to the dialog-task program. 3. All low-priority (V2) update-task function modules are triggered. All background-task function modules are triggered. Runtime errors can occur either in the system itself, or because your program issues an termination message (MESSAGE type ‘A’). Also, the ROLLBACK WORK statement automatically signals a runtime error. The system handles errors according to where they occur: •

in a FORM routine (called with PERFORM ON COMMIT)

Updates already executed for the current update transaction are rolled back.

No other FORM routines will be started.

No further update-task or background-task functions will be started.

An error message appears on the screen.

in a V1 update-task function module (requested IN UPDATE TASK)

Updates already executed for V1 functions are rolled back.

All further update-task requests (V1 or V2) are thrown away.

All background-task requests are thrown away.

Updates already executed for FORM routines called with PERFORM ON COMMIT are not rolled back.

An error message appears on the screen, if your system is set up to send them

in a V2 update-task function module (requested IN UPDATE TASK)

Updates already executed for the current V2 function are rolled back.

All update-task requests (V2) still to be executed are carried out.

All background-task requests still to be executed are carried out.

No updates for previously executed V1 or V2 function are rolled back.

No updates previously executed for FORM routines (called with ON COMMIT) are rolled back.

An error message appears on the screen, if your system is set up to send them

in a background-task function module (requested IN BACKGROUND TASK DESTINATION)

Background-task updates already executed for the current DESTINATION are not rolled back.

1342

December 1999


SAP AG

BC - ABAP Programming Error Handling for Bundled Updates

All further background-task requests for the same DESTINATION are thrown away.

No other previously-executed updates are not rolled back.

No error message appears on the screen. If your program detects that an error in remote processing has occurred, it can decide whether to resubmit the requests at a later time. For further information about RFC processing, refer to the Remote Communications [Extern] documentation.

December 1999

1343


BC - ABAP Programming

SAP AG

ABAP Objects

ABAP Objects Vererbung [Page 1380] Class- und Interface-Pools [Page 1411]

General What are ABAP Objects? [Page 1348] What is Object Orientation? [Page 1345]

Object Orientation in ABAP From Function Groups to Objects [Page 1349] Classes [Page 1353] Object Handling [Page 1360] Interfaces [Page 1390]

Using ABAP Objects Declaring and Calling Methods [Page 1365] Triggering and Handling Events [Page 1397]

1344

December 1999


SAP AG

BC - ABAP Programming What is Object Orientation?

What is Object Orientation? Object orientation (OO), or to be more precise, object-oriented programming, is a problemsolving method in which the software solution reflects objects in the real world. A comprehensive introduction to object orientation as a whole would go far beyond the limits of this introduction to ABAP Objects. This documentation introduces a selection of terms that are used universally in object orientation and also occur in ABAP Objects. In subsequent sections, it goes on to discuss in more detail how these terms are used in ABAP Objects. The end of this section contains a list of further reading, with a selection of titles about object orientation.

Objects An object is a section of source code that contains data and provides services. The data forms the attributes of the object. The services are known as methods (also known as operations or functions). Typically, methods operate on private data (the attributes, or state of the object), which is only visible to the methods of the object. Thus the attributes of an object cannot be changed directly by the user, but only by the methods of the object. This guarantees the internal consistency of the object.

Classes Classes describe objects. From a technical point of view, objects are runtime instances of a class. In theory, you can create any number of objects based on a single class. Each instance (object) of a class has a unique identity and its own set of values for its attributes.

Object References In a program, you identify and address objects using unique object references. Object references allow you to access the attributes and methods of an object. In object-oriented programming, objects usually have the following properties:

Encapsulation Objects restrict the visibility of their resources (attributes and methods) to other users. Every object has an interface, which determines how other objects can interact with it. The implementation of the object is encapsulated, that is, invisible outside the object itself.

Polymorphism Identical (identically-named) methods behave differently in different classes. Objectoriented programming contains constructions called interfaces. They enable you to address methods with the same name in different objects. Although the form of address is always the same, the implementation of the method is specific to a particular class.

Inheritance You can use an existing class to derive a new class. Derived classes inherit the data and methods of the superclass. However, they can overwrite existing methods, and also add new ones.

Uses of Object Orientation Below are some of the advantages of object-oriented programming:

December 1999

1345


BC - ABAP Programming

SAP AG

What is Object Orientation? •

Complex software systems become easier to understand, since object-oriented structuring provides a closer representation of reality than other programming techniques.

In a well-designed object-oriented system, it should be possible to implement changes at class level, without having to make alterations at other points in the system. This reduces the overall amount of maintenance required.

Through polymorphism and inheritance, object-oriented programming allows you to reuse individual components.

In an object-oriented system, the amount of work involved in revising and maintaining the system is reduced, since many problems can be detected and corrected in the design phase.

Achieving these goals requires: •

Object-oriented programming languages Object-oriented programming techniques do not necessarily depend on object-oriented programming languages. However, the efficiency of object-oriented programming depends directly on how object-oriented language techniques are implemented in the system kernel.

Object-oriented tools Object-oriented tools allow you to create object-oriented programs in object-oriented languages. They allow you to model and store development objects and the relationships between them.

Object-oriented modeling The object-orientation modeling of a software system is the most important, most timeconsuming, and most difficult requirement for attaining the above goals. Object-oriented design involves more than just object-oriented programming, and provides logical advantages that are independent of the actual implementation.

This section of the ABAP User’s Guide provides an overview of the object-oriented extension of the ABAP language. We have used simple examples to demonstrate how to use the new features. However, these are not intended to be a model for object-oriented design. More detailed information about each of the ABAP Objects statements is contained in the keyword documentation in the ABAP Editor. For a comprehensive introduction to object-oriented software development, you should read one or more of the titles listed below.

Further Reading There are many books about object orientation, object-oriented programming languages, object-oriented analysis and design, project management for OO projects, patterns and frameworks, and so on. This is a small selection of good books covering the most important topics: •

Scott Ambler, The Object Primer, SIGS Books & Multimedia (1996), ISBN: 1884842178 A very good introduction to object orientation for programmers. It provides comprehensive explanations of all essential OO concepts, and contains a procedure model for learning OO quickly and thoroughly. It is easy to read and practical, but still theoretically-founded.

1346

December 1999


SAP AG

BC - ABAP Programming What is Object Orientation?

Grady Booch, Object Solutions: Managing the Object-Oriented Project, AddisonWesley Pub Co (1995), ISBN: 0805305947 A good book about all of the non-technical aspects of OO that are equally important for effective object-oriented programming. Easy to read and full of practical tips.

Martin Fowler, UML Distilled: Applying the Standard Object Modeling Language, Addison-Wesley Pub Co (1997), ISBN: 0201325632 An excellent book about UML (Unified Modeling Language - the new standardized OO language and notation for modeling). Assumes knowledge and experience of object orientation.

Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns. Elements of Reusable Object-Oriented Software, Addison-Wesley Pub Co (1998), ISBN: 0201634988 Provides a pattern, showing how recurring design problems can be solved using objects. This is the first big pattern book, containing many examples of good OO design.

James Rumbaugh, OMT Insights: Perspectives on Modeling from the Journal of Object-Oriented Programming, Prentice Hall (1996), ISBN: 0138469652 A collection of articles addressing the many questions and problems of OO analysis and design, implementation, dependency management, and so on. Highly recommended.

Notes If you are new to object-orientation, you should read Scott Ambler’s ‘The Object Primer’ and then acquire some practical experience of your own. You should definitely use the CRC techniques described by Ambler and Fowler for object-oriented analysis and design. After this, you should learn UML, since this is the universal OO analysis and design notation. Finally, you should read at least one book about patterns. At the beginning of a large OO project, the question immediately arises as to the sequence in which things should be done, which phases should be finished at what time, how to divide up and organize the development work, how to minimize risks, how to assemble a good team, and so on and so forth. Many of the best practices of project management have had to be redefined for the object-oriented world, and the opportunities that this has produced are significant. For further information about how to use OO in project management, see Grady Brooch’s book ‘Object solutions’, or the chapter entitles ‘An outline development process’ from Martin Fowler’s book. There are, of course, many other good books about object orientation. The above list does not claim either to be complete, or necessarily to recommend the best books available.

December 1999

1347


BC - ABAP Programming

SAP AG

What are ABAP Objects?

What are ABAP Objects? ABAP Objects is a new concept in R/3 Release 4.0. The term has two meanings. On the one hand, it stands for the entire ABAP runtime environment. On the other hand, it represents the object-oriented extension of the ABAP language.

The Runtime Environment The new name ABAP Objects for the entire ABAP runtime environment is an indication of the way in which SAP has, for some time, been moving towards object orientation, and of its commitment to pursuing this line further. The ABAP Workbench allows you to create R/3 Repository objects such as programs, authorization objects, lock objects, Customizing objects, and so on. Using function modules, you can encapsulate functions in separate programs with a defined interface. The Business Object Repository (BOR) allows you to create SAP Business Objects for internal and external use (DCOM/CORBA). Until now, object-oriented techniques have been used exclusively in system design, and have not been supported by the ABAP language.

The Object-oriented Language Extension ABAP Objects is a complete set of object-oriented statements that has been introduced into the ABAP language. This object-oriented extension of ABAP builds on the existing language, and is fully compatible with it. You can use ABAP Objects in existing programs, and can also use “conventional� ABAP in new ABAP Objects programs. ABAP Objects supports object-oriented programming. Object orientation (OO), also know as the object-oriented paradigm, is a programming model that unites data and functions in objects. The rest of the ABAP language is primarily intended for structured programming, where data is stored in a structured form in database tables and function-oriented programs access and work with it. The object-oriented enhancement of ABAP is based on the models of Java and C++. It is compatible with external object interfaces such as DCOM and CORBA. The implementation of object-oriented elements in the kernel of the ABAP language has considerably increased response times when you work with ABAP Objects. SAP Business Objects and GUI objects already object-oriented themselves - will also profit from being incorporated in ABAP Objects.

1348

December 1999


SAP AG

BC - ABAP Programming From Function Groups to Objects

From Function Groups to Objects At the center of any object-oriented model are objects, which contain attributes (data) and methods (functions). Objects should enable programmers to map a real problem and its proposed software solution on a one-to-one basis. Typical objects in a business environment are, for example, ‘customer’, ‘Order’, or ‘Invoice’. From Release 3.1 onwards, the Business Object Repository (BOR) has contained examples of such objects. The object model of ABAP Objects, the object-oriented extension of ABAP, is compatible with the object model of the BOR. Before R/3 Release 4.0, the nearest equivalent of objects in ABAP were function modules and function groups. Suppose we have a function group for processing orders. The attributes of an order correspond to the global data of the function group, while the individual function modules represent actions that manipulate that data (methods). This means that the actual order data is encapsulated in the function group, and is never directly addressed, but instead only through the function modules. In this way, the function modules can ensure that the data is consistent. When you run an ABAP program, the system starts a new internal session. The internal session has a memory area that contains the ABAP program and its associated data. When you call a function module, an instance of its function group plus its data, is loaded into the memory area of the internal session. An ABAP program can load several instances by calling function modules from different function groups.

Funktionsgruppe 1 Funktionsbausteine …

Daten ...

Funktionsgruppe n Funktionsbausteine …

Daten ...

ABAP-Programm

Interner Modus eines ABAP-Programms Hauptmodus eines GUI-Fensters

December 1999

1349


BC - ABAP Programming

SAP AG

From Function Groups to Objects The instance of a function group in the memory area of the internal session almost represents an object in the sense of object orientation. (See also the definition in the section What is Object Orientation? [Page 1345].. When you call a function module, the calling program uses the instance of a function group, based on its description in the Function Builder. The program cannot access the data in the function group directly, but only through the function module. The function modules and their parameters are the interface between the function group and the user. The main difference between real object orientation and function groups is that although a program can work with the instances of several function groups at the same time, it cannot work with several instances of a single function group. Suppose a program wanted to use several independent counters, or process several orders at the same time. In this case, you would have to adapt the function group to include instance administration, for example, by using numbers to differentiate between the instances. In practice, this is very awkward. Consequently, the data is usually stored in the calling program, and the function modules are called to work with it (structured programming). One problem is, for example, that all users of the function module must use the same data structures as the function group itself. Changing the internal data structure of a function group affects many users, and it is often difficult to predict the implications. The only way to avoid this is to rely heavily on interfaces and a technique that guarantees that the internal structures of instances will remain hidden, allowing you to change them later without causing any problems. This requirement is met by object orientation. ABAP Objects allows you to define data and functions in classes instead of function groups. Using classes, an ABAP program can work with any number of instances (objects) based on the same template.

n. Instanz, Klasse 1 1. Instanz, Klasse 1 Schnittstelle …

Schnittstelle …

Daten ...

Daten ...

n. Instanz, Klasse n 1. Instanz, Klasse n Schnittstelle …

Schnittstelle …

Daten ...

Daten ...

ABAP-Programm

Interner Modus eines ABAP-Programms Hauptmodus eines GUI-Fensters

1350

December 1999


SAP AG

BC - ABAP Programming From Function Groups to Objects

Instead of loading a single instance of a function group into memory implicitly when a function module is called, the ABAP program can now generate the instances of classes explicitly using the new ABAP statement CREATE OBJECT. The individual instances represent unique objects. You address these using object references. The object references allow the ABAP program to access the interfaces of the instances. The following sections contain more information about classes, objects, interfaces, and object references in ABAP Objects.

December 1999

1351


BC - ABAP Programming

SAP AG

Example

Example The following example shows the object-oriented aspect of function groups in the simple case of a counter.

Suppose we have a function group called COUNTER: FUNCTION-POOL COUNTER. DATA COUNT TYPE I. FUNCTION SET_COUNTER. * Local Interface IMPORTING VALUE(SET_VALUE) COUNT = SET_VALUE. ENDFUNCTION. FUNCTION INCREMENT_COUNTER. ADD 1 TO COUNT. ENDFUNCTION. FUNCTION GET_COUNTER. * Local Interface: EXPORTING VALUE(GET_VALUE) GET_VALUE = COUNT. ENDFUNCTION. The function group has a global integer field COUNT, and three function modules, SET_COUNTER, INCREMENT_COUNTER, and GET_COUNTER, that work with the field. Two of the function modules have input and output parameters. These form the data interface of the function group. Any ABAP program can then work with this function group. For example: DATA NUMBER TYPE I VALUE 5. CALL FUNCTION 'SET_COUNTER' EXPORTING SET_VALUE = NUMBER. DO 3 TIMES. CALL FUNCTION 'INCREMENT_COUNTER'. ENDDO. CALL FUNCTION 'GET_COUNTER' IMPORTING GET_VALUE = NUMBER. After this section of the program has been processed, the program variable NUMBER will have the value 8. The program itself cannot access the COUNT field in the function group. Operations on this field are fully encapsulated in the function module. The program can only communicate with the function group by calling its function modules.

1352

December 1999


SAP AG

BC - ABAP Programming Classes

Classes LIKE-Zusatz [Page 117] Classes are templates for objects. Conversely, you can say that the type of an object is the same as its class. A class is an abstract description of an object. You could say that it is a set of instructions for building an object. The attributes of objects are defined by the components of the class, which describe the state and behavior of objects.

Local and Global Classes Classes in ABAP Objects can be declared either globally or locally. You define global classes and interfaces in the Class Builder (Transaction SE24) in the ABAP Workbench. They are stored centrally in class pools [Page 1411] in the class library in the R/3 Repository. All of the ABAP programs in an R/3 System can access the global classes. Local classes are defined within an ABAP program. Local classes and interfaces can only be used in the program in which they are defined. When you use a class in an ABAP program, the system first searches for a local class with the specified name. If it does not find one, it then looks for a global class. Apart from the visibility question, there is no difference between using a global class and using a local class. There is, however, a significant difference in the way that local and global classes are designed. If you are defining a local class that is only used in a single program, it is usually sufficient to define the outwardly visible components so that it fits into that program. Global classes, on the other hand, must be able to be used anywhere. This means that certain restrictions apply when you define the interface of a global class, since the system must be able to guarantee that any program using an object of a global class can recognize the data type of each interface parameter. The following sections describe how to define local classes and interfaces in an ABAP program. For information about how to define local classes and interfaces, refer to the Class Builder [Extern] section of the ABAP Workbench Tools documentation.

Defining Local Classes Local classes consist of ABAP source code, enclosed in the ABAP statements CLASS ... ENDCLASS. A complete class definition consists of a declaration part and, if required, an implementation part. The declaration part of a class <class> is a statement block: CLASS <class> DEFINITION. ... ENDCLASS. It contains the declaration for all components (attributes, methods, events) of the class. When you define local classes, the declaration part belongs to the global program data. You should therefore place it at the beginning of the program. If you declare methods in the declaration part of a class, you must also write an implementation part for it. This consists of a further statement block: CLASS <class> IMPLEMENTATION. ... ENDCLASS. The implementation part of a class contains the implementation of all methods of the class. The implementation part of a local class is a processing block. Subsequent coding that is not itself part of a processing block is therefore not accessible.

December 1999

1353


BC - ABAP Programming

SAP AG

Classes

Structure of a Class The following statements define the structure of a class: •

A class contains components

•

Each component is assigned to a visibility section

•

Classes implement methods

The following sections describe the structure of classes in more detail.

Class Components The components of a class make up its contents. All components are declared in the declaration part of the class. The components define the attributes of the objects in a class. When you define the class, each component is assigned to one of the three visibility sections, which define the external interface of the class. All of the components of a class are visible within the class. All components are in the same namespace. This means that all components of the class must have names that are unique within the class. There are two kinds of components in a class - those that exist separately for each object in the class, and those that exist only once for the whole class, regardless of the number of instances. Instance-specific components are known as instance components. Components that are not instance-specific are called static components. In ABAP Objects, classes can define the following components. Since all components that you can declare in classes can also be declared in interfaces, the following descriptions apply equally to interfaces.

Attributes Attributes are internal data fields within a class that can have any ABAP data type. The state of an object is determined by the contents of its attributes. One kind of attribute is the reference variable. Reference variables allow you to create and address objects. Reference variables can be defined in classes, allowing you to access objects from within a class.

Instance Attributes The contents of instance attributes define the instance-specific state of an object. You declare them using the DATA statement.

Static Attributes The contents of static attributes define the state of the class that is valid for all instances of the class. Static attributes exist once for each class. You declare them using the CLASS-DATA statement. They are accessible for the entire runtime of the class. All of the objects in a class can access its static attributes. If you change a static attribute in an object, the change is visible in all other objects in the class.

Methods Methods are internal procedures in a class that define the behavior of an object. They can access all of the attributes of a class. This allows them to change the data content of an object. They also have a parameter interface, with which users can supply them with values when calling them, and receive values back from them The private attributes of a class can only be changed by methods in the same class.

1354

December 1999


SAP AG

BC - ABAP Programming Classes

The definition and parameter interface of a method is similar to that of function modules. You define a method <met> in the definition part of a class and implement it in the implementation part using the following processing block: METHOD <meth>. ... ENDMETHOD. You can declare local data types and objects in methods in the same way as in other ABAP procedures (subroutines and function modules). You call methods using the CALL METHOD statement.

Instance Methods You declare instance methods using the METHODS statement. They can access all of the attributes of a class, and can trigger all of the events of the class.

Static Methods You declare static methods using the CLASS-METHODS statement. They can only access static attributes and trigger static events.

Special Methods As well as normal methods, which you call using CALL METHOD, there are two special methods called CONSTRUCTOR and CLASS_CONSTRUCTOR, which are automatically called when you create an object (CONSTRUCTOR) or when you first access the components of a class (CLASS_CONSTRUCTOR).

Events Objects or classes can use events to trigger event handler methods in other objects or classes. In a normal method call, one method can be called by any number of users. When an event is triggered, any number of event handler methods can be called. The link between the trigger and the handler is not established until runtime. In a normal method call, the calling program determines the methods that it wants to call. These methods must exist. With events, the handler determines the events to which it wants to react. There does not have to be a handler method registered for every event. The events of a class can be triggered in the methods of the same class using the RAISE EVENT statement. You can declare a method of the same or a different class as an event handler method for the event <evt> of class <class> using the addition FOR EVENT <evt> OF <class>. Events have a similar parameter interface to methods, but only have output parameters. These parameters are passed by the trigger (RAISE EVENT statement) to the event handler method, which receives them as input parameters. The link between trigger and handler is established dynamically in a program using the SET HANDLER statement. The trigger and handlers can be objects or classes, depending on whether you have instance or static events and event handler methods. When an event is triggered, the corresponding event handler methods are executed in all registered handling classes.

Instance Events You declare instance events using the EVENTS statement. An instance event can only be triggered in an instance method.

December 1999

1355


BC - ABAP Programming

SAP AG

Classes Static Events You declare static events using the CLASS-EVENTS statement. All methods (instance and static methods) can trigger static events. Static events are the only type of event that can be triggered in a static method. See also Triggering and Handling Events [Page 1397].

Types You can define your own ABAP data types within a class using the TYPES statement. Types are not instance-specific, and exist once only for all of the objects in a class.

Constants Constants are special static attributes. You set their values when you declare them, and they can then no longer be changed. You declare them using the CONSTANTS statement. Constants are not instance-specific, and exist once only for all of the objects in a class.

Visibility Sections You can divide the declaration part of a class into up to three visibility areas: CLASS <class> DEFINITION. PUBLIC SECTION. ... PROTECTED SECTION. ... PRIVATE SECTION. ... ENDCLASS. These areas define the external visibility of the class components, that is, the interface between the class and its users. Each component of a class must be assigned to one of the visibility sections.

Public Section All of the components declared in the public section are accessible to all users of the class, and to the methods of the class and any classes that inherit from it. The public components of the class form the interface between the class and its users.

Protected Section All of the components declared in the protected section are accessible to all methods of the class and of classes that inherit from it. Protected components form a special interface between a class and its subclasses. Since inheritance is not active in Release 4.5B, the protected section currently has the same effect as the private section.

Private Section Components that you declare in the private section are only visible in the methods of the same class. The private components are not part of the external interface of the class.

Encapsulation The three visibility areas are the basis for one of the important features of object orientation encapsulation. When you define a class, you should take great care in designing the public

1356

December 1999


SAP AG

BC - ABAP Programming Classes

components, and try to declare as few public components as possible. The public components of global classes may not be changed once you have released the class. For example, public attributes are visible externally, and form a part of the interface between an object and its users. If you want to encapsulate the state of an object fully, you cannot declare any public attributes. As well as defining the visibility of an attribute, you can also protect it from changes using the READ-ONLY addition.

See also: Overview Graphic [Page 1358] Example [Page 1359]

December 1999

1357


BC - ABAP Programming

SAP AG

Overview Graphic

Overview Graphic Classes CLASS C1 DEFINITION. PUBLIC SECTION. DATA: A1 … METHODS: M1 … EVENTS: E1 … PROTECTED SECTION. DATA: A2 … METHODS: M2 … EVENTS: E2 … PRIVATE SECTION. DATA: A3 … METHODS: M3 … EVENTS: E3 … ENDCLASS.

Klasse C1 Public components

Private components

A1, M1, E1, …

A2, M2, E2, … Method implementations

Protected components A3, M3, E3, …

CLASS C1 IMPLEMENTATION. METHOD M1. … ENDMETHOD. METHOD M2. … ENDMETHOD.

Subclasses of C1 METHOD M3. … ENDMETHOD.

All users ENDCLASS. The left-hand side of the illustration shows the declaration and implementation parts of a local class C1. The right-hand side illustrates the structure of the class with the components in their respective visibility areas, and the implementation of the methods. The public components of the class form the interface between the class and its users. The protected components are an interface to the subclasses of C1. The private components are not visible externally, and are fully encapsulated in the class. The methods in the implementation part have unrestricted access to all components of the class.

1358

December 1999


SAP AG

BC - ABAP Programming Classes - Introductory Example

Classes - Introductory Example Von Funktionsgruppen zu Objekten [Page 1349] The following simple example uses ABAP Objects to program a counter. For comparison, see also the example [Page 1352] in From Function Groups to Objects

CLASS C_COUNTER DEFINITION. PUBLIC SECTION. METHODS: SET_COUNTER IMPORTING VALUE(SET_VALUE) TYPE I, INCREMENT_COUNTER, GET_COUNTER EXPORTING VALUE(GET_VALUE) TYPE I. PRIVATE SECTION. DATA COUNT TYPE I. ENDCLASS. CLASS C_COUNTER IMPLEMENTATION. METHOD SET_COUNTER. COUNT = SET_VALUE. ENDMETHOD. METHOD INCREMENT_COUNTER. ADD 1 TO COUNT. ENDMETHOD. METHOD GET_COUNTER. GET_VALUE = COUNT. ENDMETHOD. ENDCLASS. The class C_COUNTER contains three public methods - SET_COUNTER, INCREMENT_COUNTER, and GET_COUNTER. Each of these works with the private integer field COUNT. Two of the methods have input and output parameters. These form the data interface of the class. The field COUNT is not outwardly visible. The example in the section Working with Objects [Page 1360] shows how you can create instances of the class C_COUNTER.

December 1999

1359


BC - ABAP Programming

SAP AG

Object Handling

Object Handling Datenreferenzen [Page 220] Interfaces [Page 1390] Vererbung [Page 1380] Interfaces [Page 1390] LIKE-Zusatz [Page 117]

Objects Objects are instances of classes. Each object has a unique identity and its own attributes. All transient objects reside in the context of an internal session (memory area of an ABAP program). Persistent objects in the database are not yet available. A class can have any number of objects (instances).

Object References To access an object from an ABAP program, you use object references. Object references are pointers to objects. In ABAP, they are always contained in reference variables.

Reference variables Reference variables contain references. A reference variable is either initial or contains a reference to an existing object. The identity of an object depends on its reference. A reference variable that points to an object knows the identity of that object. Users cannot access the identity of the object directly. Reference variables in ABAP are treated like other elementary data objects. This means that a reference variable can occur as a component of a structure or internal table as well as on its own.

Data Types for References ABAP contains a predefined data type for references, comparable to the data types for structures or internal tables. The full data type is not defined until the declaration in the ABAP program. The data type of a reference variable determines how the program handles its value (that is, the object reference). There are two principal types of references: Class references and interface references (see Interfaces [Page 1390]). You define class references using the ... TYPE REF TO <class> addition in the TYPES or DATA statement, where <class> refers to a class. A reference variable with the type class reference is called a class reference variable, or class reference for short. A class reference <cref> allows a user to create an instance (object) of the corresponding class, and to address a visible component <comp> within it using the form cref->comp

1360

December 1999


SAP AG

BC - ABAP Programming Object Handling

Creating Objects Before you can create an object for a class, you need to declare a reference variable with reference to that class. Once you have declared a class reference variable <obj> for a class <class>, you can create an object using the statement CREATE OBJECT <cref>. This statement creates an instance of the class <class>, and the reference variable <cref> contains a reference to the object.

Addressing the Components of Objects Programs can only access the instance components of an object using references in reference variables. The syntax is as follows (where <ref> is a reference variable): •

To access an attribute <attr>:

<ref>-><attr>

To call a method <meth>:

CALL METHOD <ref>-><meth>

You can access static components using the class name as well as the reference variable. It is also possible to address the static components of a class before an object has been created. •

Addressing a static attribute <attr>:

Calling a static method <meth>: CALL METHOD <class>=><meth>

<class>=><attr>

Within a class, you can use the self-reference ME to access the individual components: •

To access an attribute <attr> in the same class: ME-><attr>

To call a method <meth> in the same class:

CALL METHOD ME-><meth>

Self references allow an object to give other objects a reference to it. You can also access attributes in methods from within an object even if they are obscured by local attributes of the method.

Creating More Than One Instance of a Class In a program, you can create any number of objects from the same class. The objects are fully independent of each other. Each one has its own identity within the program and its own attributes. Each CREATE OBJECT statement generates a new object, whose identity is defined by its unique object reference.

Assigning References You can assign references to different reference variables using the MOVE statement. In this way, you can make the references in several reference variables point to the same object. When you assign a reference to a different reference variable, their types must be either compatible or convertible. When you use the MOVE statement or the assignment operator (=) to assign reference variables, the system must be able to recognize in the syntax check whether an assignment is possible. The same applies when you pass reference variables to procedures as parameters. If you write the statement <cref1> = <cref2> the two class references <cref1> and <cref2> must have the same type, that is, they must either refer to the same class, or the class of <cref1> must be the predefined empty class OBJECT.

December 1999

1361


BC - ABAP Programming

SAP AG

Object Handling The class OBJECT has no components, and has the same function for reference variables as the data type ANY has for normal variables. Reference variables with the type OBJECT can function as containers for passing references. However, you cannot use them to address objects.

Object Lifetime An object exists for as long as it is being used in the program. An object is in use by a program for as long as at least one reference points to it, or at least one method of the object is registered as an event handler. As soon as there are no more references to an object, and so long as none of its methods are registered as event handlers, it is deleted by the automatic memory management (garbage collection). The ID of the object then becomes free, and can be used by a new object.

See also: Overview Graphic [Page 1363] Example [Page 1364]

1362

December 1999


SAP AG

BC - ABAP Programming Overview Graphic

Overview Graphic Objects as Instances of a Class

C1<1>

Schnittstelle …

Class C1 Public components

Private components

… Method implementations

C1<2>

Schnittstelle …

C1<3>

Schnittstelle …

Protected components …

Internal session of an ABAP program

Class

Instances of the class

The above illustration shows a class C1 on the left, with its instances represented in the internal session of an ABAP program on the right. To distinguish them from classes, instances are drawn with rounded corners. The instance names above use the same notation as is used for reference variables in the Debugger.

December 1999

1363


BC - ABAP Programming

SAP AG

Objects - Introductory Example

Objects - Introductory Example Klassen [Page 1353]

The following example shows how to create and use an instance of the class C_COUNTER that we created in the previous section (see the example [Page 1359] under Classes and Class Components):

[Extern]

1364

December 1999


SAP AG

BC - ABAP Programming Declaring and Calling Methods

Declaring and Calling Methods GET REFERENCE [Page 223] This section contains explains how to work with methods in ABAP Objects. For precise details of the relevant ABAP statements, refer to the corresponding keyword documentation in the ABAP Editor. The example [Page 1368] shows how to declare, implement, and call methods.

Declaring Methods You can declare methods in the declaration part of a class or in an interface. To declare instance methods, use the following statement: METHODS <meth> IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL].. EXPORTING.. [VALUE(]<ei>[)] TYPE type [OPTIONAL].. CHANGING.. [VALUE(]<ci>[)] TYPE type [OPTIONAL].. RETURNING VALUE(<r>) EXCEPTIONS.. <ei>.. and the appropriate additions. To declare static methods, use the following statement: CLASS-METHODS <meth>... Both statements have the same syntax. When you declare a method, you also define its parameter interface using the additions IMPORTING, EXPORTING, CHANGING, and RETURNING. The additions define the input, output, and input/output parameters, and the return code. They also define the attributes of the interface parameters, namely whether a parameter is to be passed by reference or value (VALUE), its type (TYPE), and whether it is optional (OPTIONAL, DEFAULT). Unlike in function modules, the default way of passing a parameter in a method is by reference. To pass a parameter by value, you must do so explicitly using the VALUE addition. The return value (RETURNING parameter) must always be passed explicitly as a value. This is suitable for methods that return a single output value. If you use it, you cannot use EXPORTING or CHANGING parameters. As in function modules, you can use exception parameters (EXCEPTIONS) to allow the user to react to error situations when the method is executed.

Implementing Methods You must implement all of the methods in a class in the implementation part of the class in a METHOD <meth>. ... ENDMETHOD. block. When you implement the method, you do not have to specify any interface parameters, since these are defined in the method declaration. The interface parameters of a method behave like local variables within the method implementation. You can define additional local variables within a method using the DATA statement. As in function modules, you can use the RAISE <exception> and MESSAGE RAISING statements to handle error situations.

December 1999

1365


BC - ABAP Programming

SAP AG

Declaring and Calling Methods When you implement a static method, remember that it can only work with the static attributes of your class. Instance methods can work with both static and instance attributes.

Calling Methods To call a method, use the following statement: CALL METHOD <meth> EXPORTING... <ii> =.<fi>... IMPORTING... <ei> =.<gi>... CHANGING ... <ci> =.<fi>... RECEIVING r=h EXCEPTIONS... <ei> = rci... The way in which you address the method <method> depends on the method itself and from where you are calling it. Within the implementation part of a class, you can call the methods of the same class directly using their name <meth>. CALL METHOD <meth>... Outside the class, the visibility of the method depends on whether you can call it at all. Visible instance methods can be called from outside the class using CALL METHOD <ref>-><meth>... where <ref> is a reference variable whose value points to an instance of the class. Visible instance methods can be called from outside the class using CALL METHOD <class>=><meth>... where <class> is the name of the relevant class. When you call a method, you must pass all non-optional input parameters using the EXPORTING or CHANGING addition in the CALL METHOD statement. You can (but do not have to) import the output parameters into your program using the IMPORTING or RECEIVING addition. Equally, you can (but do not have to) handle any exceptions triggered by the exceptions using the EXCEPTIONS addition. However, this is recommended. You pass and receive values to and from methods in the same way as with function modules, that is, with the syntax: ... <Formal parameter> = <Actual parameter> after the corresponding addition. The interface parameters (formal parameters) are always on the left-hand side of the equals sign. The actual parameters are always on the right. The equals sign is not an assignment operator in this context; it merely serves to assign program variables to the interface parameters of the method. If the interface of a method consists only of a single IMPORTING parameter, you can use the following shortened form of the method call: CALL METHOD <method>( f). The actual parameter <f> is passed to the input parameters of the method. If the interface of a method consists only of IMPORTING parameters, you can use the following shortened form of the method call: CALL METHOD <method>(....<ii> =.<fi>...). Each actual parameter <fi> is passed to the corresponding formal parameter <ii>.

1366

December 1999


SAP AG

BC - ABAP Programming Declaring and Calling Methods

Event Handler Methods Event handler methods are special methods that cannot all be called using the CALL METHOD statement. Instead, they are triggered using events. You define a method as an event handler method using the addition ... FOR EVENT <evt> OF <cif>... in the METHODS or CLASS-METHODS statement. The following special rules apply to the interface of an event handler method: •

The interface may only consist of IMPORTING parameters.

Each IMPORTING parameter must be an EXPORTING parameter of the event <evt>.

The attributes of the parameters are defined in the declaration of the event <evt> (EVENTS statement) and are adopted by the event handler method.

See also Triggering and Handling Events [Page 1397]

Constructors Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class. The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows: METHODS CONSTRUCTOR IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL].. EXCEPTIONS.. <ei>. and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement. The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows: CLASS-METHODS CLASS_CONSTRUCTOR. and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class. The methods example [Page 1368] shows how to use instance and static constructors.

December 1999

1367


BC - ABAP Programming

SAP AG

Methods in ABAP Objects - Example

Methods in ABAP Objects - Example The following example shows how to declare, implement, and use methods in ABAP Objects.

Overview This example uses three classes called C_TEAM, C_BIKER, and C_BICYCLE. A user (a program) can create objects of the class C_TEAM. On a selection screen, the class C_TEAM asks for the number of members of each team. Each object in the class C_TEAM can create as many instances of the class C_BIKER as there are members in the team. Each instance of the class C_BIKER creates an instances of the class C_BICYCLE. Each instance of the class C_TEAM can communicate with the program user through an interactive list. The program user can choose individual team members for actions. The instances of the class C_BIKER allow the program user to choose the action on a further selection screen.

1368

December 1999


SAP AG

BC - ABAP Programming Methods in ABAP Objects - Example

Referenzvariablen und Instanzen:

... ... C_ BIKER<4> C_ BICYCLE <4>

...

C_ BIKER<3> C_ BICYCLE<3>

C_TEAM<3> C_BIKER<2>

C_ BICYCLE<2>

C_TEAM<2> C_BIKER<1> C_TEAM<1>

C_BICYCLE<1>

Benutzerinteraktion:

December 1999

1369


BC - ABAP Programming

SAP AG

Methods in ABAP Objects - Example

Constraints The ABAP statements used for list processing are not yet fully available in ABAP Objects. However, to produce a simple test output, you can use the following statements: •

WRITE [AT] /<offset>(<length>) <f>

ULINE

SKIP

NEW-LINE

Note: The behavior of formatting and interactive list functions in their current state are not guaranteed. Incompatible changes could occur in a future release.

Declarations This example is implemented using local classes, since selection screens belong to an ABAP program, and cannot be defined or called in global classes. Below are the definitions of the two selection screens and three classes:

******************************************************************* * Global Selection Screens ******************************************************************* SELECTION-SCREEN BEGIN OF: SCREEN 100 TITLE TIT1, LINE. PARAMETERS MEMBERS TYPE I DEFAULT 10. SELECTION-SCREEN END OF: LINE, SCREEN 100. *-----------------------------------------------------------------SELECTION-SCREEN BEGIN OF SCREEN 200 TITLE TIT2. PARAMETERS: DRIVE RADIOBUTTON GROUP ACTN, STOP RADIOBUTTON GROUP ACTN, GEARUP RADIOBUTTON GROUP ACTN, GEARDOWN RADIOBUTTON GROUP ACTN. SELECTION-SCREEN END OF SCREEN 200. ******************************************************************* * Class Definitions ******************************************************************* CLASS: C_BIKER DEFINITION DEFERRED, C_BICYCLE DEFINITION DEFERRED. *-----------------------------------------------------------------CLASS C_TEAM DEFINITION. PUBLIC SECTION.

1370

December 1999


SAP AG

BC - ABAP Programming Methods in ABAP Objects - Example

TYPES: BIKER_REF TYPE REF TO C_BIKER, BIKER_REF_TAB TYPE STANDARD TABLE OF BIKER_REF WITH DEFAULT KEY, BEGIN OF STATUS_LINE_TYPE, FLAG(1) TYPE C, TEXT1(5) TYPE C, ID TYPE I, TEXT2(7) TYPE C, TEXT3(6) TYPE C, GEAR TYPE I, TEXT4(7) TYPE C, SPEED TYPE I, END OF STATUS_LINE_TYPE. CLASS-METHODS: CLASS_CONSTRUCTOR. METHODS: CONSTRUCTOR, CREATE_TEAM, SELECTION, EXECUTION. PRIVATE SECTION. CLASS-DATA: TEAM_MEMBERS TYPE I, COUNTER TYPE I. DATA: ID TYPE I, STATUS_LINE TYPE STATUS_LINE_TYPE, STATUS_LIST TYPE SORTED TABLE OF STATUS_LINE_TYPE WITH UNIQUE KEY ID, BIKER_TAB TYPE BIKER_REF_TAB, BIKER_SELECTION LIKE BIKER_TAB, BIKER LIKE LINE OF BIKER_TAB. METHODS: WRITE_LIST. ENDCLASS. *-----------------------------------------------------------------CLASS C_BIKER DEFINITION. PUBLIC SECTION. METHODS: CONSTRUCTOR IMPORTING TEAM_ID TYPE I MEMBERS TYPE I, SELECT_ACTION, STATUS_LINE EXPORTING LINE TYPE C_TEAM=>STATUS_LINE_TYPE. PRIVATE SECTION. CLASS-DATA COUNTER TYPE I. DATA: ID TYPE I, BIKE TYPE REF TO C_BICYCLE, GEAR_STATUS TYPE I VALUE 1, SPEED_STATUS TYPE I VALUE 0. METHODS BIKER_ACTION IMPORTING ACTION TYPE I.

December 1999

1371


BC - ABAP Programming

SAP AG

Methods in ABAP Objects - Example

ENDCLASS. *-----------------------------------------------------------------CLASS C_BICYCLE DEFINITION. PUBLIC SECTION. METHODS: DRIVE EXPORTING VELOCITY TYPE I, STOP EXPORTING VELOCITY TYPE I, CHANGE_GEAR IMPORTING CHANGE TYPE I RETURNING VALUE(GEAR) TYPE I EXCEPTIONS GEAR_MIN GEAR_MAX. PRIVATE SECTION. DATA: SPEED TYPE I, GEAR TYPE I VALUE 1. CONSTANTS: MAX_GEAR TYPE I VALUE 18, MIN_GEAR TYPE I VALUE 1. ENDCLASS. ******************************************************************* Note that none of the three classes has any public attributes. The states of the classes can only be changed by their methods. The class C_TEAM contains a static constructor CLASS_CONSTRUCTOR. C_TEAM and C_BIKER both contain instance constructors.

Implementations The implementation parts of the classes contain the implementations of all of the methods declared in the corresponding declaration parts. The interfaces of the methods have already been defined in the declarations. In the implementations, the interface parameters behave like local data.

Methods of Class C_TEAM The following methods are implemented in the section

CLASS C_TEAM IMPLEMENTATION. ...

ENDCLASS. CLASS_CONSTRUCTOR

METHOD CLASS_CONSTRUCTOR. TIT1 = 'Team members ?'. CALL SELECTION-SCREEN 100 STARTING AT 5 3. IF SY-SUBRC NE 0. LEAVE PROGRAM. ELSE. TEAM_MEMBERS = MEMBERS. ENDIF. ENDMETHOD.

1372

December 1999


SAP AG

BC - ABAP Programming Methods in ABAP Objects - Example

The static constructor is executed before the class C_TEAM is used for the first time in a program. It calls the selection screen 100 and sets the static attribute TEAM_MEMBERS to the value entered by the program user. This attribute has the same value for all instances of the class C_TEAM.

CONSTRUCTOR

METHOD CONSTRUCTOR. COUNTER = COUNTER + 1. ID = COUNTER. ENDMETHOD. The instance constructor is executed directly after each instance of the class C_TEAM is created. It is used to count the number of instance of C_TEAM in the static attribute COUNTER, and assigns the corresponding number to the instance attribute ID of each instance of the class.

CREATE_TEAM

METHOD CREATE_TEAM. DO TEAM_MEMBERS TIMES. CREATE OBJECT BIKER EXPORTING TEAM_ID = ID MEMBERS = TEAM_MEMBERS. APPEND BIKER TO BIKER_TAB. CALL METHOD BIKER->STATUS_LINE IMPORTING LINE = STATUS_LINE. APPEND STATUS_LINE TO STATUS_LIST. ENDDO. ENDMETHOD. The public instance method CREATE_TEAM can be called by any user of the class containing a reference variable with a reference to an instance of the class. It is used to create instances of the class C_BIKER, using the private reference variable BIKER in the class C_TEAM. You must pass both input parameters for the instance constructor of class C_BIKER in the CREATE OBJECT statement. The references to the newly-created instances are inserted into the private internal table BIKER_TAB. After the method has been executed, each line of the internal table contains a reference to an instance of the class C_BIKER. These references are only visible within the class C_TEAM. External users cannot address the objects of class C_BIKER. CREATE_TEAM also calls the method STATUS_LINE for each newly-created object, and uses the work area STATUS_LINE to append its output parameter LINE to the private internal table STATUS_LIST.

SELECTION

METHOD SELECTION. CLEAR BIKER_SELECTION. DO. READ LINE SY-INDEX. IF SY-SUBRC <> 0. EXIT. ENDIF. IF SY-LISEL+0(1) = 'X'. READ TABLE BIKER_TAB INTO BIKER INDEX SY-INDEX. APPEND BIKER TO BIKER_SELECTION. ENDIF. ENDDO. CALL METHOD WRITE_LIST. ENDMETHOD.

December 1999

1373


BC - ABAP Programming

SAP AG

Methods in ABAP Objects - Example The public instance method SELECTION can be called by any user of the class containing a reference variable with a reference to an instance of the class. It selects all of the lines in the current list in which the checkbox in the first column is selected. For these lines, the system copies the corresponding reference variables from the table BIKER_TAB into an additional private internal table BIKER_SELECTION. SELECTION then calls the private method WRITE_LIST, which displays the list.

EXECUTION

METHOD EXECUTION. CHECK NOT BIKER_SELECTION IS INITIAL. LOOP AT BIKER_SELECTION INTO BIKER. CALL METHOD BIKER->SELECT_ACTION. CALL METHOD BIKER->STATUS_LINE IMPORTING LINE = STATUS_LINE. MODIFY TABLE STATUS_LIST FROM STATUS_LINE. ENDLOOP. CALL METHOD WRITE_LIST. ENDMETHOD. The public instance method EXECUTION can be called by any user of the class containing a reference variable with a reference to an instance of the class. The method calls the two methods SELECT_ACTION and STATUS_LINE for each instance of the class C_BIKER for which there is a reference in the table BIKER_SELECTION. The line of the table STATUS_LIST with the same key as the component ID in the work area STATUS_LINE is overwritten and displayed by the private method WRITE_LIST.

WRITE_LIST

METHOD WRITE_LIST. SET TITLEBAR 'TIT'. SY-LSIND = 0. SKIP TO LINE 1. POSITION 1. LOOP AT STATUS_LIST INTO STATUS_LINE. WRITE: / STATUS_LINE-FLAG AS CHECKBOX, STATUS_LINE-TEXT1, STATUS_LINE-ID, STATUS_LINE-TEXT2, STATUS_LINE-TEXT3, STATUS_LINE-GEAR, STATUS_LINE-TEXT4, STATUS_LINE-SPEED. ENDLOOP. ENDMETHOD. The private instance method WRITE_LIST can only be called from the methods of the class C_TEAM. It is used to display the private internal table STATUS_LIST on the basic list (SYLSIND = 0) of the program.

Methods of Class C_BIKER The following methods are implemented in the section

CLASS C_BIKER IMPLEMENTATION. ...

1374

December 1999


SAP AG

BC - ABAP Programming Methods in ABAP Objects - Example

ENDCLASS. CONSTRUCTOR

METHOD CONSTRUCTOR. COUNTER = COUNTER + 1. ID = COUNTER - MEMBERS * ( TEAM_ID - 1). CREATE OBJECT BIKE. ENDMETHOD. The instance constructor is executed directly after each instance of the class C_BIKER is created. It is used to count the number of instance of C_BIKER in the static attribute COUNTER, and assigns the corresponding number to the instance attribute ID of each instance of the class. The constructor has two input parameters - TEAM_ID and MEMBERS - which you must pass in the CREATE OBJECT statement when you create an instance of C_BIKER. The instance constructor also creates an instance of the class C_BICYCLE for each new instance of the class C_BIKER. The reference in the private reference variable BIKE of each instance of C_BIKER points to a corresponding instance of the class C_BICYCLE. No external user can address these instances of the class C_BICYCLE.

SELECT_ACTION

METHOD SELECT_ACTION. DATA ACTIVITY TYPE I. TIT2 = 'Select action for BIKE'. TIT2+24(3) = ID. CALL SELECTION-SCREEN 200 STARTING AT 5 15. CHECK NOT SY-SUBRC GT 0. IF GEARUP = 'X' OR GEARDOWN = 'X'. IF GEARUP = 'X'. ACTIVITY = 1. ELSEIF GEARDOWN = 'X'. ACTIVITY = -1. ENDIF. ELSEIF DRIVE = 'X'. ACTIVITY = 2. ELSEIF STOP = 'X'. ACTIVITY = 3. ENDIF. CALL METHOD BIKER_ACTION( ACTIVITY). ENDMETHOD. The public instance method SELECT_ACTION can be called by any user of the class containing a reference variable with a reference to an instance of the class. The method calls the selection screen 200 and analyzes the user input. After this, it calls the private method BIKER_ACTION of the same class. The method call uses the shortened form to pass the actual parameter ACTIVITY to the formal parameter ACTION.

BIKER_ACTION

METHOD BIKER_ACTION. CASE ACTION. WHEN -1 OR 1. CALL METHOD BIKE->CHANGE_GEAR EXPORTING CHANGE = ACTION RECEIVING GEAR = GEAR_STATUS

December 1999

1375


BC - ABAP Programming

SAP AG

Methods in ABAP Objects - Example

EXCEPTIONS GEAR_MAX = 1 GEAR_MIN = 2. CASE SY-SUBRC. WHEN 1. MESSAGE I315(AT) WITH 'BIKE' ID ' is already at maximal gear!'. WHEN 2. MESSAGE I315(AT) WITH 'BIKE' ID ' is already at minimal gear!'. ENDCASE. WHEN 2. CALL METHOD BIKE->DRIVE IMPORTING VELOCITY = SPEED_STATUS. WHEN 3. CALL METHOD BIKE->STOP IMPORTING VELOCITY = SPEED_STATUS. ENDCASE. ENDMETHOD. The private instance method BIKER_ACTION can only be called from the methods of the class C_BIKER. The method calls other methods in the instance of the class C_BICYCLE to which the reference in the reference variable BIKE is pointing, depending on the value in the input parameter ACTION.

STATUS_LINE

METHOD STATUS_LINE. LINE-FLAG = SPACE. LINE-TEXT1 = 'Biker'. LINE-ID = ID. LINE-TEXT2 = 'Status:'. LINE-TEXT3 = 'Gear = '. LINE-GEAR = GEAR_STATUS. LINE-TEXT4 = 'Speed = '. LINE-SPEED = SPEED_STATUS. ENDMETHOD. The public instance method STATUS_LINE can be called by any user of the class containing a reference variable with a reference to an instance of the class. It fills the structured output parameter LINE with the current attribute values of the corresponding instance.

Methods of Class C_BICYCLE The following methods are implemented in the section

CLASS C_BICYCLE IMPLEMENTATION. ...

ENDCLASS. DRIVE

METHOD DRIVE. SPEED = SPEED + GEAR * 10. VELOCITY = SPEED. ENDMETHOD.

1376

December 1999


SAP AG

BC - ABAP Programming Methods in ABAP Objects - Example

The public instance method DRIVE can be called by any user of the class containing a reference variable with a reference to an instance of the class. The method changes the value of the private attribute SPEED and passes it to the caller using the output parameter VELOCITY.

STOP

METHOD STOP. SPEED = 0. VELOCITY = SPEED. ENDMETHOD. The public instance method STOP can be called by any user of the class containing a reference variable with a reference to an instance of the class. The method changes the value of the private attribute SPEED and passes it to the caller using the output parameter VELOCITY.

CHANGE_GEAR

METHOD CHANGE_GEAR. GEAR = ME->GEAR. GEAR = GEAR + CHANGE. IF GEAR GT MAX_GEAR. GEAR = MAX_GEAR. RAISE GEAR_MAX. ELSEIF GEAR LT MIN_GEAR. GEAR = MIN_GEAR. RAISE GEAR_MIN. ENDIF. ME->GEAR = GEAR. ENDMETHOD. The public instance method CHANGE_GEAR can be called by any user of the class containing a reference variable with a reference to an instance of the class. The method changes the value of the private attribute GEAR. Since the formal parameter with the same name obscures the attribute in the method, the attribute has to be addressed using the self-reference ME->GEAR.

Using the Classes in a Program The following program shows how the above classes can be used in a program. The declarations of the selection screens and local classes, and the implementations of the methods must also be a part of the program.

REPORT OO_METHODS_DEMO NO STANDARD PAGE HEADING. ******************************************************************* * Declarations and Implementations ******************************************************************* ...

******************************************************************* * Global Program Data ******************************************************************* TYPES TEAM TYPE REF TO C_TEAM.

December 1999

1377


BC - ABAP Programming

SAP AG

Methods in ABAP Objects - Example

DATA: TEAM_BLUE TYPE TEAM, TEAM_GREEN TYPE TEAM, TEAM_RED TYPE TEAM. DATA

COLOR(5).

******************************************************************* * Program events ******************************************************************* START-OF-SELECTION. CREATE OBJECT: TEAM_BLUE, TEAM_GREEN, TEAM_RED. CALL METHOD: TEAM_BLUE->CREATE_TEAM, TEAM_GREEN->CREATE_TEAM, TEAM_RED->CREATE_TEAM. SET PF-STATUS 'TEAMLIST'. WRITE '

Select a team!

' COLOR = 2.

*-----------------------------------------------------------------AT USER-COMMAND. CASE SY-UCOMM. WHEN 'TEAM_BLUE'. COLOR = 'BLUE '. FORMAT COLOR = 1 INTENSIFIED ON INVERSE ON. CALL METHOD TEAM_BLUE->SELECTION. WHEN 'TEAM_GREEN'. COLOR = 'GREEN'. FORMAT COLOR = 5 INTENSIFIED ON INVERSE ON. CALL METHOD TEAM_GREEN->SELECTION. WHEN 'TEAM_RED'. COLOR = 'RED '. FORMAT COLOR = 6 INTENSIFIED ON INVERSE ON. CALL METHOD TEAM_RED->SELECTION. WHEN 'EXECUTION'. CASE COLOR. WHEN 'BLUE '. FORMAT COLOR = 1 INTENSIFIED ON INVERSE ON. CALL METHOD TEAM_BLUE->SELECTION. CALL METHOD TEAM_BLUE->EXECUTION. WHEN 'GREEN'. FORMAT COLOR = 5 INTENSIFIED ON INVERSE ON. CALL METHOD TEAM_GREEN->SELECTION. CALL METHOD TEAM_GREEN->EXECUTION. WHEN 'RED '. FORMAT COLOR = 6 INTENSIFIED ON INVERSE ON. CALL METHOD TEAM_RED->SELECTION. CALL METHOD TEAM_RED->EXECUTION. ENDCASE. ENDCASE. *******************************************************************

1378

December 1999


SAP AG

BC - ABAP Programming Methods in ABAP Objects - Example

The program contains three class reference variables that refer to the class C_TEAM. It creates three objects from the class, to which the references in the reference variables then point. In each object, it calls the method CREATE_TEAM. The method CLASS_CONSTRUCTOR of class C_TEAM is executed before the first of the objects is created. The status TEAMLIST for the basic list allows the user to choose one of four functions:

When the user chooses a function, the event AT USER-COMMAND is triggered and public methods are called in one of the three instances of C_TEAM, depending on the user’s choice. The user can change the state of an object by selecting the corresponding line in the status list.

December 1999

1379


BC - ABAP Programming

SAP AG

Inheritance

Inheritance Inheritance allows you to derive a new class from an existing class. You do this using the INHERITING FROM addition in the CLASS <subclass> DEFINITION INHERITING FROM <superclass>. statement. The new class <subclass> inherits all of the components of the existing class <superclass>. The new class is called the subclass of the class from which it is derived. The original class is called the superclass of the new class. If you do not add any new declarations to the subclass, it contains the same components as the superclass. However, only the public and protected components of the superclass are visible in the subclass. Although the private components of the superclass exist in the subclass, they are not visible. You can declare private components in a subclass that have the same names as private components of the superclass. Each class works with its own private components. Methods that a subclass inherits from a superclass use the private attributes of the superclass, and not any private components of the subclass with the same names. If the superclass does not have a private visibility section, the subclass is an exact replica of the superclass. However, you can add new components to the subclass. This allows you to turn the subclass into a specialized version of the superclass. If a subclass is itself the superclass of further classes, you introduce a new level of specialization. A class can have more than one direct subclass, but it may only have one direct superclass. This is called single inheritance. When subclasses inherit from superclasses and the superclass is itself the subclass of another class, all of the classes involved form an inheritance tree, whose degree of specialization increases with each new hierarchical level you add. Conversely, the classes become more generalized until you reach the root node of the inheritance tree. The root node of all inheritance trees in ABAP Objects is the predefined empty class OBJECT. This is the most generalized class possible, since it contains neither attributes nor methods. When you define a new class, you do not have to specify it explicitly as the superclass - the relationship is always implicitly defined. Within an inheritance tree, two adjacent nodes are the direct superclass or direct subclass of one another. Other related nodes are referred to as superclasses and subclasses. The component declarations in a subclass are distributed across all levels of the inheritance tree.

Redefining Methods All subclasses contain the components of all classes between themselves and the root node in an inheritance tree. The visibility of a component cannot be changed. However, you can use the REDEFINITION addition in the METHODS statement to redefine an inherited public or protected instance method in a subclass and make its function more specialized. When you redefine a method, you cannot change its interface. The method retains the same name and interface, but has a new implementation. The method declaration and implementation in the superclass is not affected when you redefine the method in a subclass. The implementation of the redefinition in the subclass obscures the original implementation in the superclass. Any reference that points to an object of the subclass uses the redefined method, even if the reference was defined with reference to the superclass. This particularly applies to the selfreference ME->. If, for example, a superclass method M1 contains a call CALL METHOD [ME>]M2, and M2 is redefined in a subclass, calling M1 from an instance of the subclass will cause

1380

December 1999


SAP AG

BC - ABAP Programming Inheritance

the original method M2 to be called, and calling M1 from an instance of the subclass will cause the redefined method M2 to be called. Within a redefine method, you can use the pseudoreference SUPER-> to access the obscured method. This enables you to use the existing function of the method in the superclass without having to recode it in the subclass.

Abstract and Final Methods and Classes The ABSTRACT and FINAL additions to the METHODS and CLASS statements allow you to define abstract and final methods or classes. An abstract method is defined in an abstract class and cannot be implemented in that class. Instead, it is implemented in a subclass of the class. Abstract classes cannot be instantiated. A final method cannot be redefined in a subclass. Final classes cannot have subclasses. They conclude an inheritance tree.

References to Subclasses and Polymorphism Reference variables defined with reference to a superclass or an interface defined with reference to it can also contain references to any of its subclasses. Since subclasses contain all of the components of all of their superclasses, and given that the interfaces of methods cannot be changed, a reference variable defined with reference to a superclass or an interface implemented by a superclass can contain references to instances of any of its subclasses. In particular, you can define the target variable with reference to the generic class OBJECT. When you create an object using the CREATE OBJECT statement and a reference variable typed with reference to a subclass, you can use the TYPE addition to create an instance of a subclass, to which the reference in the reference variable will then point. A static user can use a reference variable to address the components visible to it in the superclass to which the reference variable refers. However, it cannot address any specialization implemented in the subclass. If you use a dynamic method call, you can address all components of the class. If you redefine an instance method in one or more subclasses, you can use a single reference variable to call different implementations of the method, depending on the position in the inheritance tree at which the referenced object occurs. This concept that different classes can have the same interface and therefore be addressed using reference variables with a single type is called polymorphism.

Namespace for Components Subclasses contain all of the components of all of their superclasses within the inheritance tree. Of these components, only the public and protected ones are visible. All public and protected components within an inheritance tree belong to the same namespace, and consequently must have unique names. The names of private components, on the other hand, must only be unique within their class. When you redefine methods, the new implementation of the method obscures the method of the superclass with the same name. However, the new definition replaces the previous method implementation, so the name is still unique. You can use the pseudoreference SUPER-> to access a method definition in a superclass that has been obscured by a redefinition in a subclass.

December 1999

1381


BC - ABAP Programming

SAP AG

Inheritance

Inheritance and Static Attributes Like all components, static attributes only exist once in each inheritance tree. A subclass can access the public and protected static attributes of all of its superclasses. Conversely, a superclass shares its public and protected static attributes with all of its subclasses. In terms of inheritance, static attributes are not assigned to a single class, but to a part of the inheritance tree. You can change them from outside the class using the class component selector with any class name, or within any class in which they are shared. They are visible in all classes in the inheritance tree. When you address a static attribute that belongs to part of an inheritance tree, you always address the class in which the attribute is declared, irrespective of the class you specify in the class selector. This is particularly important when you call the static constructors of classes in inheritance. Static constructors are executed the first time you address a class. If you address a static attribute declared in a superclass using the class name of a subclass, only the static constructor of the superclass is executed.

Inheritance and Constructors There are special rules governing constructors in inheritance.

Instance Constructors Every class has an instance constructor called CONSTRUCTOR. This is an exception to the rule that states that component names within an inheritance tree must be unique. However, the instance constructors of the various classes in an inheritance tree are fully independent of one another. You cannot redefine the instance constructor of a superclass in a subclass, neither can you call one specifically using the statement CALL METHOD CONSTRUCTOR. Consequently, no naming conflicts can occur. The instance constructor of a class is called by the system when you instantiate the class using CREATE OBJECT. Since a subclass contains all of the visible attributes of its superclasses, which can also be set by instance constructors, the instance constructor of a subclass has to ensure that the instance constructors of all of its superclasses are also called. To do this, the instance constructor of each subclass must contain a CALL METHOD SUPER>CONSTRUCTOR statement. The only exception to this rule are direct subclasses of the root node OBJECT. In superclasses without an explicitly-defined instance constructor, the implicit instance constructor is called. This automatically ensures that the instance constructor of the immediate superclass is called. When you call an instance constructor, you must supply values for all of its non-optional interface parameters. There are various ways of doing this: •

Using CREATE OBJECT If the class that you are instantiating has an instance constructor with an interface, you must pass values to it using EXPORTING. If the class that you are instantiating has an instance constructor without an interface, you do not pass any parameters. If the class you are instantiating does not have an explicit instance constructor, you must look in the inheritance tree for the next-highest superclass with an explicit instance constructor. If this has an interface, you must supply values using EXPORTING. Otherwise, you do not have to pass any values.

1382

December 1999


SAP AG

BC - ABAP Programming Inheritance

•

Using CALL METHOD SUPER->CONSTRUCTOR If the direct superclass has an instance constructor with an interface, you must pass values to it using EXPORTING. If the direct superclass has an instance constructor without an interface, you do not pass any parameters. If the direct superclass does not have an explicit instance constructor, you must look in the inheritance tree for the next-highest superclass with an explicit instance constructor. If this has an interface, you must supply values using EXPORTING. Otherwise, you do not have to pass any values.

In both CREATE OBJECT and CALL METHOD SUPER->CONSTRUCTOR, you must look at the next-available explicit instance constructor and, if it has an interface, pass values to it. The same applies to exception handling for instance constructors. When you work with inheritance, you need an precise knowledge of the entire inheritance tree. When you instantiate a class at the bottom of the inheritance tree, you may need to pass parameters to the constructor of a class that is much nearer the root node. The instance constructor of a subclass is divided into two parts by the CALL METHOD SUPER>CONSTRUCTOR statement. In the statements before the call, the constructor behaves like a static method, that is, it cannot access the instance attributes of its class. You cannot address instance attributes until after the call. Use the statements before the call to determine the actual parameters for the interface of the instance constructor of the superclass. You can only use static attributes or local data to do this. When you instantiate a subclass, the instance constructors are called hierarchically. The first nesting level in which you can address instance attributes is the highest-level superclass. When you return to the constructors of the lower-level classes, you can also successively address their instance attributes. In a constructor method, the methods of the subclasses of the class are not visible. If an instance constructor calls an instance method of the same class using the implicit self-reference ME->, the method is called as it is implemented in the class of the instance constructor, and not in any redefined form that may occur in the subclass you want to instantiate. This is an exception to the rule that states that when you call instance methods, the system always calls the method as it is implemented in the class to whose instance the reference is pointing.

Static Constructors Every class has a static constructor called CLASS_CONSTRUCTOR. As far as the namespace within an inheritance tree, the same applies to static constructors as to instance constructors. The first time you address a subclass in a program, its static constructor is executed. However, before it can be executed, the static constructors of all of its superclasses must already have been executed. A static constructor may only be called once per program. Therefore, when you first address a subclass, the system looks for the next-highest superclass whose static constructor has not yet been executed. It executes the static constructor of that class, followed by those of all classes between that class and the subclass you addressed.

See also: Overview Graphics [Page 1385]

December 1999

1383


BC - ABAP Programming

SAP AG

Inheritance Inheritance: Introductory Example [Page 1388]

1384

December 1999


SAP AG

BC - ABAP Programming Inheritance: Overview Graphic

Inheritance: Overview Graphic Inheritance: Overview Class OBJECT ... CLASS c1 DEFINITION INHERITING FROM ... ... ENDCLASS.

Class c1

CLASS c1 IMPLEMENTATION. ... ENDCLASS.

Class c2 CLASS c2 DEFINITION INHERITING FROM c1. ... ENDCLASS. CLASS c2 IMPLEMENTATION. ... ENDCLASS.

Class ... ...

The left-hand part of the graphic shows how you can derive a subclass c2 from a superclass c1 using the INHERTING FROM addition in the CLASS statement. The right-hand part of the graphic shows the distribution of the subclass in the inheritance tree, which stretches back to the default empty class OBJECT. A subclass contains all of the components declared above it in the inheritance tree, and can address all of them that are declared public or protected.

December 1999

1385


BC - ABAP Programming

SAP AG

Inheritance: Overview Graphic

Single Inheritance OBJECT

...

C1

...

C2

...

This graphic illustrates single inheritance. A class may only have one direct superclass, but it can have more than one direct subclass. The empty class OBJECT is the root node of every inheritance tree in ABAP Objects.

Inheritance and Reference Variables

n<class3> class1 CREF1 class2 CREF2 class3 CREF3

This graphic shows how reference variables defined with reference to a superclass can point to objects of subclasses. The object on the right is an instance of the class class3. The class reference variables CREF1, CREF2, and CREF3 are typed with reference to class1, class2, and

1386

December 1999


SAP AG

BC - ABAP Programming Inheritance: Overview Graphic

class3. All three can point to the object. However, CREF1 can only address the public components of class1. CREF2 can address the public components of class1 and class2. CREF3 can address the public components of all of the classes. If you redefine a method of a superclass in a subclass, you can use a reference variable defined with reference to the superclass to address objects with different method implementations. When you address the superclass, the method has the original implementation, but when you address the subclass, the method has the new implementation. Using a single reference variable to call identically-named methods that behave differently is called polymorphism.

December 1999

1387


BC - ABAP Programming

SAP AG

Inheritance: Introductory Example

Inheritance: Introductory Example The following simple example shows the principle of inheritance within ABAP Objects. It is based on the Simple Introduction to Classes [Page 1359]. A new class counter_ten inherits from the existing class counter.

REPORT demo_inheritance. CLASS counter DEFINITION. PUBLIC SECTION. METHODS: set IMPORTING value(set_value) TYPE i, increment, get EXPORTING value(get_value) TYPE i. PROTECTED SECTION. DATA count TYPE i. ENDCLASS. CLASS counter IMPLEMENTATION. METHOD set. count = set_value. ENDMETHOD. METHOD increment. ADD 1 TO count. ENDMETHOD. METHOD get. get_value = count. ENDMETHOD. ENDCLASS. CLASS counter_ten DEFINITION INHERITING FROM counter. PUBLIC SECTION. METHODS increment REDEFINITION. DATA count_ten. ENDCLASS. CLASS counter_ten IMPLEMENTATION. METHOD increment. DATA modulo TYPE I. CALL METHOD super->increment. write / count. modulo = count mod 10. IF modulo = 0. count_ten = count_ten + 1. write count_ten. ENDIF. ENDMETHOD. ENDCLASS. DATA: count TYPE REF TO counter, number TYPE i VALUE 5. START-OF-SELECTION. CREATE OBJECT count TYPE counter_ten.

1388

December 1999


SAP AG

BC - ABAP Programming Inheritance: Introductory Example

CALL METHOD count->set EXPORTING set_value = number. DO 20 TIMES. CALL METHOD count->increment. ENDDO. The class COUNTER_TEN is derived from COUNTER. It redefines the method INCREMENT. To do this, you must change the visibility of the COUNT attribute from PRIVATE to PROTECTED. The redefined method calls the obscured method of the superclass using the pseudoreference SUPER->. The redefined method is a specialization of the inherited method. The example instantiates the subclass. The reference variable pointing to it has the type of the superclass. When the INCREMENT method is called using the superclass reference, the system executes the redefined method from the subclass.

December 1999

1389


BC - ABAP Programming

SAP AG

Interfaces

Interfaces EinfĂźhrendes Beispiel zu Interfaces [Page 1395] Classes, their instances (objects), and access to objects using reference variables form the basics of ABAP Objects. These means already allow you to model typical business applications, such as customers, orders, order items, invoices, and so on, using objects, and to implement solutions using ABAP Objects. However, it is often necessary for similar classes to provide similar functions that are coded differently in each class but which should provide a uniform point of contact for the user. For example, you might have two similar classes, savings account and check account, both of which have a method for calculating end of year charges. The interfaces and names of the methods are the same, but the actual implementation is different. The user of the classes and their instances must also be able to run the end of year method for all accounts, without having to worry about the actual type of each individual account. ABAP Objects makes this possible by using interfaces. Interfaces are independent structures that you can implement in a class to extend the scope of that class. The class-specific scope of a class is defined by its components and visibility sections. For example, the public components of a class define its public scope, since all of its attributes and method parameters can be addressed by all users. The protected components of a class define its scope with regard to its subclasses. (However, inheritance is not supported in Release 4.5B). Interfaces extend the scope of a class by adding their own components to its public section. This allows users to address different classes via a universal point of contact. Interfaces, along with inheritance, provide one of the pillars of polymorphism, since they allow a single method within an interface to behave differently in different classes.

Defining Interfaces Like classes, you can define interfaces either globally in the R/3 Repository or locally in an ABAP program. For information about how to define local interfaces, refer to the Class Builder [Extern] section of the ABAP Workbench Tools documentation. The definition of a local interface <intf> is enclosed in the statements: INTERFACE <intf>. ... ENDINTERFACE. The definition contains the declaration for all components (attributes, methods, events) of the interface. You can define the same components in an interface as in a class. The components of interfaces do not have to be assigned individually to a visibility section, since they automatically belong to the public section of the class in which the interface is implemented. Interfaces do not have an implementation part, since their methods are implemented in the class that implements the interface.

Implementing Interfaces Unlike classes, interfaces do not have instances. Instead, interfaces are implemented by classes. To implement an interface in a class, use the statement INTERFACES <intf>.

1390

December 1999


SAP AG

BC - ABAP Programming Interfaces

in the declaration part of the class. This statement may only appear in the public section of the class. When you implement an interface in a class, the components of the interface are added to the other components in the public section. A component <icomp> of an interface <intf> can be addressed as though it were a member of the class under the name <intf~icomp>. The class must implement the methods of all interfaces implemented in it. The implementation part of the class must contain a method implementation for each interface method <imeth>: METHOD <intf~imeth>. ... ENDMETHOD. Interfaces can be implemented by different classes. Each of these classes is extended by the same set of components. However, the methods of the interface can be implemented differently in each class. Interfaces allow you to use different classes in a uniform way using interface references (polymorphism). For example, interfaces that are implemented in different classes extend the public scope of each class by the same set of components. If a class does not have any classspecific public components, the interfaces define the entire public face of the class.

Interface References Reference variables allow you to access objects (refer to Working with Objects [Page 1360]). Instead of creating reference variables with reference to a class, you can also define them with reference to an interface. This kind of reference variable can contain references to objects of classes that implement the corresponding interface. To define an interface reference, use the addition TYPE REF TO <intf> in the TYPES or DATA statement. <intf> must be an interface that has been declared to the program before the actual reference declaration occurs. A reference variable with the type interface reference is called a interface reference variable, or interface reference for short. An interface reference <iref> allows a user to use the form <iref>-><icomp> to address all visible interface components <icomp> of the object to which the object reference is pointing. It allows the user to access all of the components of the object that were added to its definition by the implementation of the interface.

Addressing Objects Using Interface References To create an object of the class <class>, you must first have declared a reference variable <cref> with reference to the class. If the class <class> implements an interface <intf>, you can use the following assignment between the class reference variable <cref> and an interface reference <iref> to make the interface reference in <iref> point to the same object as the class reference in <cref>: <iref> = <cref> If the interface <intf> contains an instance attribute <attr> and an instance method <meth>, you can address the interface components as follows: Using the class reference variable <cref>: •

To access an attribute <attr>:

<cref>-><intf~attr>

•

To call a method <meth>:

CALL METHOD <cref>-><intf~meth>

December 1999

1391


BC - ABAP Programming

SAP AG

Interfaces Using the interface reference variable <iref>: •

To access an attribute <attr>:

<iref>-><attr>

To call a method <meth>:

CALL METHOD <iref>-><meth>

As far as the static components of interfaces are concerned, you can only use the interface name to access constants: Addressing a constant <const>:

<intf>=><const>

For all other static components of an interface, you can only use object references or the class <class> that implements the interface: Addressing a static attribute <attr>:

<class>=><intf~attr>

Calling a static method <meth>: CALL METHOD <class>=><intf~meth>

Assignment Using Interface References - Casting Like class references, you can assign interface references to different reference variables. You can also make assignments between class reference variables and interface reference variables. When you use the MOVE statement or the assignment operator (=) to assign reference variables, the system must be able to recognize in the syntax check whether an assignment is possible. Suppose we have a class reference <cref> and interface references <iref>, <iref1>, and <iref2>. The following assignments with interface references can be checked statically: •

<iref1> = <iref2> Both interface references must refer to the same interface, or the interface of <iref1> must contain the interface <iref2> as a component.

<iref> = <cref> The class of the class reference <cref> must implement the interface of the interface reference <iref>.

<cref> = <iref> The class of <cref> must be the predefined empty class OBJECT.

In all other cases, you would have to work with the statement MOVE ...? TO or the casting operator (?=). The casting operator replaces the assignment operator (=). In the MOVE... ? TO statement, or when you use the casting operator, there is no static type check. Instead, the system checks at runtime whether the object reference in the source variable points to an object to which the object reference in the target variable can also point. If the assignment is possible, the system makes it, otherwise, the catchable runtime error MOVE_CAST_ERROR occurs. You must always use casting for assigning an interface reference to a class reference if <cref> does not refer to the predefined empty class OBJECT: <cref> ?= <iref> For the casting to be successful, the object to which <iref> points must be an object of the same class as the type of the class variable <cref>.

See also: Overview Graphics [Page 1394]

1392

December 1999


SAP AG

BC - ABAP Programming Interfaces

December 1999

1393


BC - ABAP Programming

SAP AG

Overview Graphics

Overview Graphics Interfaces INTERFACE I1. DATA: A1 … METHODS: M1 … EVENTS: E1 … ENDINTERFACE.

Class C1 Public components A1, ...

CLASS C1 DEFINITION. PUBLIC SECTION. INTERFACES I1. DATA: A1 … … PROTECTED SECTION. … PRIVATE SECTION. … ENDCLASS.

I1~A1, I1~M1, I1~E1 ...

Private components …

Method implementations

Protected components …

CLASS C1 IMPLEMENTATION. METHOD I1~M1. … ENDMETHOD. …

Subclasses of C1

All users

ENDCLASS.

[Extern] [Extern] The left-hand side of the diagram shows the definition of a local interface I1 and the declaration and implementation parts of a local class C1 that implements the interface I1 in its public section. The interface method I1~M1 is implemented in the class. You cannot implement interfaces in the other visibility sections. The right-hand side illustrates the structure of the class with the components in their respective visibility areas, and the implementation of the methods. The interface components extend the public scope of the class. All users can access the public components specific to the class and those of the interface.

1394

December 1999


SAP AG

BC - ABAP Programming Interfaces - Introductory Example

Interfaces - Introductory Example The following simple example shows how you can use an interface to implement two counters that are different, but can be addressed in the same way. See also the example in the Classes section.

INTERFACE I_COUNTER. METHODS: SET_COUNTER IMPORTING VALUE(SET_VALUE) TYPE I, INCREMENT_COUNTER, GET_COUNTER EXPORTING VALUE(GET_VALUE) TYPE I. ENDINTERFACE. CLASS C_COUNTER1 DEFINITION. PUBLIC SECTION. INTERFACES I_COUNTER. PRIVATE SECTION. DATA COUNT TYPE I. ENDCLASS. CLASS C_COUNTER1 IMPLEMENTATION. METHOD I_COUNTER~SET_COUNTER. COUNT = SET_VALUE. ENDMETHOD. METHOD I_COUNTER~INCREMENT_COUNTER. ADD 1 TO COUNT. ENDMETHOD. METHOD I_COUNTER~GET_COUNTER. GET_VALUE = COUNT. ENDMETHOD. ENDCLASS. CLASS C_COUNTER2 DEFINITION. PUBLIC SECTION. INTERFACES I_COUNTER. PRIVATE SECTION. DATA COUNT TYPE I. ENDCLASS. CLASS C_COUNTER2 IMPLEMENTATION. METHOD I_COUNTER~SET_COUNTER. COUNT = ( SET_VALUE / 10) * 10. ENDMETHOD. METHOD I_COUNTER~INCREMENT_COUNTER. IF COUNT GE 100. MESSAGE I042(00). COUNT = 0. ELSE. ADD 10 TO COUNT. ENDIF. ENDMETHOD. METHOD I_COUNTER~GET_COUNTER. GET_VALUE = COUNT.

December 1999

1395


BC - ABAP Programming

SAP AG

Interfaces - Introductory Example ENDMETHOD. ENDCLASS. The interface I_COUNTER contains three methods SET_COUNTER, INCREMENT_COUNTER, and GET_COUNTER. The classes C_COUNTER1 and C_COUNTER2 implement the interface in the public section. Both classes must implement the three interface methods in their implementation part. C_COUNTER1 is a class for counters that can have any starting value and are then increased by one. C_COUNTER2 is a class for counters that can only be increased in steps of 10. Both classes have an identical outward face. It is fully defined by the interface in both cases. The following sections explain how a user can use an interface reference to address the objects of both classes: [Extern]

1396

December 1999


SAP AG

BC - ABAP Programming Triggering and Handling Events

Triggering and Handling Events Übersichtsgrafiken zu Ereignissen [Page 1400] Einführendes Beispiel zu Ereignissen [Page 1403] Komplexes Beispiel zu Ereignissen [Page 1405] In ABAP Objects, triggering and handling an event means that certain methods act as triggers and trigger events, to which other methods - the handlers - react. This means that the handler methods are executed when the event occurs. This section contains explains how to work with events in ABAP Objects. For precise details of the relevant ABAP statements, refer to the corresponding keyword documentation in the ABAP Editor.

Triggering Events To trigger an event, a class must •

Declare the event in its declaration part

Trigger the event in one of its methods

Declaring Events You declare events in the declaration part of a class or in an interface. To declare instance events, use the following statement: EVENTS <evt> EXPORTING... VALUE(<ei>) TYPE type [OPTIONAL].. To declare static events, use the following statement: CLASS-EVENTS <evt>... Both statements have the same syntax. When you declare an event, you can use the EXPORTING addition to specify parameters that are passed to the event handler. The parameters are always passed by value. Instance events always contain the implicit parameter SENDER, which has the type of a reference to the type or the interface in which the event is declared.

Triggering Events An instance event in a class can be triggered by any method in the class. Static events can be triggered by any static method. To trigger an event in a method, use the following statement: RAISE EVENT <evt> EXPORTING... <ei> = <fi>... For each formal parameter <ei> that is not defined as optional, you must pass a corresponding actual parameter <fi> in the EXPORTING addition. The self-reference ME is automatically passed to the implicit parameter SENDER.

Handling Events Events are handled using special methods. To handle an event, a method must •

be defined as an event handler method for that event

be registered at runtime for the event.

December 1999

1397


BC - ABAP Programming

SAP AG

Triggering and Handling Events

Declaring Event Handler Methods Any class can contain event handler methods for events from other classes. You can, of course, also define event handler methods in the same class as the event itself. To declare an event handler method, use the following statement: METHODS <meth> FOR EVENT <evt> OF <cif> IMPORTING.. <ei>.. for an instance method. For a static method, use CLASS-METHODS instead of METHODS. <evt> is an event declared in the class or interface <cif>. The interface of an event handler method may only contain formal parameters defined in the declaration of the event <evt>. The attributes of the parameter are also adopted by the event. The event handler method does not have to use all of the parameters passed in the RAISE EVENT statement. If you want the implicit parameter SENDER to be used as well, you must list it in the interface. This parameter allows an instance event handler to access the trigger, for example, to allow it to return results. If you declare an event handler method in a class, it means that the instances of the class or the class itself are, in principle, able to handle an event <evt> triggered in a method.

Registering Event Handler Methods To allow an event handler method to react to an event, you must determine at runtime the trigger to which it is to react. You can do this with the following statement: SET HANDLER... <hi>... [FOR]... It links a list of handler methods with corresponding trigger methods. There are four different types of event. It can be •

An instance event declared in a class

An instance event declared in an interface

A static event declared in a class

A static event declared in an interface

The syntax and effect of the SET HANDLER depends on which of the four cases listed above applies. For an instance event, you must use the FOR addition to specify the instance for which you want to register the handler. You can either specify a single instance as the trigger, using a reference variable <ref>: SET HANDLER... <hi>...FOR <ref>. or you can register the handler for all instances that can trigger the event: SET HANDLER... <hi>...FOR ALL INSTANCES. The registration then applies even to triggering instances that have not yet been created when you register the handler. You cannot use the FOR addition for static events: SET HANDLER... <hi>...

1398

December 1999


SAP AG

BC - ABAP Programming Triggering and Handling Events

The registration applies automatically to the whole class, or to all of the classes that implement the interface containing the static event. In the case of interfaces, the registration also applies to classes that are not loaded until after the handler has been registered.

Timing of Event Handling After the RAISE EVENT statement, all registered handler methods are executed before the next statement is processed (synchronous event handling). If a handler method itself triggers events, its handler methods are executed before the original handler method continues. To avoid the possibility of endless recursion, events may currently only be nested 64 deep. Handler methods are executed in the order in which they were registered. Since event handlers are registered dynamically, you should not assume that they will be processed in a particular order. Instead, you should program as though all event handlers will be executed simultaneously.

December 1999

1399


BC - ABAP Programming

SAP AG

Overview Graphic

Overview Graphic Suppose we have two classes, C1 and C2:

Event trigger CLASS C1 DEFINITION. PUBLIC SECTION. EVENTS E1 EXPORTING VALUE(P1) TYPE I. METHODS M1. PRIVATE SECTION. DATA A1 TYPE I. ENDCLASS. CLASS C1 IMPLEMENTATION. METHOD M1. A1 = ... RAISE EVENT E1 EXPORTING P1 = A1. ENDMETHOD. ENDCLASS.

Event handler CLASS C2 DEFINITION. PUBLIC SECTION. METHODS: M2 FOR EVENT E1 OF C1 IMPORTING P1. PRIVATE SECTION. DATA A2 TYPE I. ENDCLASS. CLASS C2 IMPLEMENTATION. METHOD M2. A2 = P1. ... ENDMETHOD. ENDCLASS.

The class C1 contains an event E1, which is triggered by the method M1. Class C2 contains a method M2, which can handle event E1 of class C1. The following diagram illustrates handler registration:

1400

December 1999


SAP AG

BC - ABAP Programming Overview Graphic

Registering handlers

DATA: R1 TYPE REF TO C1, H1 TYPE REF TO C2, H2 TYPE REF TO C2. CREATE OBJECT: R1, H1, H2. SET HANDLER H1->M2 H2->M2 FOR R1. CALL METHOD R1->M1.

C2<2> E1 M2 M2 ‌.

C2<1>

C1<1>

H2 R1

H1

The program creates an instance of the class C1 and two instances of the class C2. The values of the reference variables R1, H1, and H2 point to these instances. The SET HANDLER statement creates a handler table, invisible to the user, for each event for which a handler method has been registered. The handler table contains the names of the handler methods and references to the registered instances. The entries in the table are administered dynamically by the SET HANDLER statement. A reference to an instance in a handler table is like a reference in a reference

December 1999

1401


BC - ABAP Programming

SAP AG

Overview Graphic variable. In other words, it counts as a use of the instance, and therefore directly affects its lifetime. In the above diagram, this means that the instances C2<1> and C2<2> are not deleted by the garbage collection, even if H1 and H2 are initialized, so long as their registration is not deleted from the handler table. For static events, the system creates an instance-independent handler table for the relevant class. When an event is triggered, the system looks in the corresponding event table and executes the methods in the appropriate instances (or in the corresponding class for a static handler method).

1402

December 1999


SAP AG

BC - ABAP Programming Events: Introductory Example

Events: Introductory Example The following simple example shows the principle of events within ABAP Objects. It is based on the Simple Introduction to Classes [Page 1359]. An event critical_value is declared and triggered in class counter.

REPORT demo_class_counter_event. CLASS counter DEFINITION. PUBLIC SECTION. METHODS increment_counter. EVENTS critical_value EXPORTING value(excess) TYPE i. PRIVATE SECTION. DATA: count TYPE i, threshold TYPE i VALUE 10. ENDCLASS. CLASS counter IMPLEMENTATION. METHOD increment_counter. DATA diff TYPE i. ADD 1 TO count. IF count > threshold. diff = count - threshold. RAISE EVENT critical_value EXPORTING excess = diff. ENDIF. ENDMETHOD. ENDCLASS. CLASS handler DEFINITION. PUBLIC SECTION. METHODS handle_excess FOR EVENT critical_value OF counter IMPORTING excess. ENDCLASS. CLASS handler IMPLEMENTATION. METHOD handle_excess. WRITE: / 'Excess is', excess. ENDMETHOD. ENDCLASS. DATA: r1 TYPE REF TO counter, h1 TYPE REF TO handler. START-OF-SELECTION. CREATE OBJECT: r1, h1. SET HANDLER h1->handle_excess FOR ALL INSTANCES. DO 20 TIMES. CALL METHOD r1->increment_counter. ENDDO.

December 1999

1403


BC - ABAP Programming

SAP AG

Events: Introductory Example The class COUNTER implements a counter. It triggers the event CRITICAL_VALUE when a threshold value is exceeded, and displays the difference. HANDLER can handle the exception in COUNTER. At runtime, the handler is registered for all reference variables that point to the object.

1404

December 1999


SAP AG

BC - ABAP Programming Events in ABAP Objects - Example

Events in ABAP Objects - Example The following example shows how to declare, call, and handle events in ABAP Objects.

Overview This object works with the interactive list displayed below. Each user interaction triggers an event in ABAP Objects. The list and its data is created in the class C_LIST. There is a class STATUS for processing user actions. It triggers an event BUTTON_CLICKED in the AT USER-COMMAND event. The event is handled in the class C_LIST. It contains an object of the class C_SHIP or C_TRUCK for each line of the list. Both of these classes implement the interface I_VEHICLE. Whenever the speed of one of these objects changes, the event SPEED_CHANGE is triggered. The class C_LIST reacts to this and updates the list.

Constraints The ABAP statements used for list processing are not yet fully available in ABAP Objects. However, to produce a simple test output, you can use the following statements: •

WRITE [AT] /<offset>(<length>) <f>

ULINE

SKIP

NEW-LINE Note: The behavior of formatting and interactive list functions in their current state are not guaranteed. Incompatible changes could occur in a future release.

Declarations

December 1999

1405


BC - ABAP Programming

SAP AG

Events in ABAP Objects - Example This example is implemented using local interfaces and classes. Below are the declarations of the interfaces and classes:

***************************************************************** * Interface and Class declarations ***************************************************************** INTERFACE I_VEHICLE. DATA

MAX_SPEED TYPE I.

EVENTS SPEED_CHANGE EXPORTING VALUE(NEW_SPEED) TYPE I. METHODS: DRIVE, STOP. ENDINTERFACE. *---------------------------------------------------------------CLASS C_SHIP DEFINITION. PUBLIC SECTION. METHODS CONSTRUCTOR. INTERFACES I_VEHICLE. PRIVATE SECTION. ALIASES MAX FOR I_VEHICLE~MAX_SPEED. DATA SHIP_SPEED TYPE I. ENDCLASS. *---------------------------------------------------------------CLASS C_TRUCK DEFINITION. PUBLIC SECTION. METHODS CONSTRUCTOR. INTERFACES I_VEHICLE. PRIVATE SECTION. ALIASES MAX FOR I_VEHICLE~MAX_SPEED. DATA TRUCK_SPEED TYPE I. ENDCLASS. *---------------------------------------------------------------CLASS STATUS DEFINITION. PUBLIC SECTION. CLASS-EVENTS BUTTON_CLICKED EXPORTING VALUE(FCODE) LIKE SY-UCOMM. CLASS-METHODS: CLASS_CONSTRUCTOR, USER_ACTION. ENDCLASS. *----------------------------------------------------------------

1406

December 1999


SAP AG

BC - ABAP Programming Events in ABAP Objects - Example

CLASS C_LIST DEFINITION. PUBLIC SECTION. METHODS: FCODE_HANDLER FOR EVENT BUTTON_CLICKED OF STATUS IMPORTING FCODE, LIST_CHANGE FOR EVENT SPEED_CHANGE OF I_VEHICLE IMPORTING NEW_SPEED, LIST_OUTPUT. PRIVATE SECTION. DATA: ID TYPE I, REF_SHIP TYPE REF TO C_SHIP, REF_TRUCK TYPE REF TO C_TRUCK, BEGIN OF LINE, ID TYPE I, FLAG, IREF TYPE REF TO I_VEHICLE, SPEED TYPE I, END OF LINE, LIST LIKE SORTED TABLE OF LINE WITH UNIQUE KEY ID. ENDCLASS. *****************************************************************

The following events are declared in the example: •

The instance event SPEED_CHANGE in the interface I_VEHICLE

The static event BUTTON_CLICKED in the class STATUS.

The class C_LIST contains event handler methods for both events. Note that the class STATUS does not have any attributes, and therefore only works with static methods and events.

Implementations Below are the implementations of the methods of the above classes:

***************************************************************** * Implementations ***************************************************************** CLASS C_SHIP IMPLEMENTATION. METHOD CONSTRUCTOR. MAX = 30. ENDMETHOD. METHOD I_VEHICLE~DRIVE. CHECK SHIP_SPEED < MAX. SHIP_SPEED = SHIP_SPEED + 10. RAISE EVENT I_VEHICLE~SPEED_CHANGE EXPORTING NEW_SPEED = SHIP_SPEED. ENDMETHOD.

December 1999

1407


BC - ABAP Programming

SAP AG

Events in ABAP Objects - Example

METHOD I_VEHICLE~STOP. CHECK SHIP_SPEED > 0. SHIP_SPEED = 0. RAISE EVENT I_VEHICLE~SPEED_CHANGE EXPORTING NEW_SPEED = SHIP_SPEED. ENDMETHOD. ENDCLASS. *---------------------------------------------------------------CLASS C_TRUCK IMPLEMENTATION. METHOD CONSTRUCTOR. MAX = 150. ENDMETHOD. METHOD I_VEHICLE~DRIVE. CHECK TRUCK_SPEED < MAX. TRUCK_SPEED = TRUCK_SPEED + 50. RAISE EVENT I_VEHICLE~SPEED_CHANGE EXPORTING NEW_SPEED = TRUCK_SPEED. ENDMETHOD. METHOD I_VEHICLE~STOP. CHECK TRUCK_SPEED > 0. TRUCK_SPEED = 0. RAISE EVENT I_VEHICLE~SPEED_CHANGE EXPORTING NEW_SPEED = TRUCK_SPEED. ENDMETHOD. ENDCLASS. *---------------------------------------------------------------CLASS STATUS IMPLEMENTATION. METHOD CLASS_CONSTRUCTOR. SET PF-STATUS 'VEHICLE'. WRITE 'Click a button!'. ENDMETHOD. METHOD USER_ACTION. RAISE EVENT BUTTON_CLICKED EXPORTING FCODE = SY-UCOMM. ENDMETHOD. ENDCLASS. *---------------------------------------------------------------CLASS C_LIST IMPLEMENTATION. METHOD FCODE_HANDLER. CLEAR LINE. CASE FCODE. WHEN 'CREA_SHIP'. ID = ID + 1. CREATE OBJECT REF_SHIP. LINE-ID = ID. LINE-FLAG = 'C'.

1408

December 1999


SAP AG

BC - ABAP Programming Events in ABAP Objects - Example

LINE-IREF = REF_SHIP. APPEND LINE TO LIST. WHEN 'CREA_TRUCK'. ID = ID + 1. CREATE OBJECT REF_TRUCK. LINE-ID = ID. LINE-FLAG = 'T'. LINE-IREF = REF_TRUCK. APPEND LINE TO LIST. WHEN 'DRIVE'. CHECK SY-LILLI > 0. READ TABLE LIST INDEX SY-LILLI INTO LINE. CALL METHOD LINE-IREF->DRIVE. WHEN 'STOP'. LOOP AT LIST INTO LINE. CALL METHOD LINE-IREF->STOP. ENDLOOP. WHEN 'CANCEL'. LEAVE PROGRAM. ENDCASE. CALL METHOD LIST_OUTPUT. ENDMETHOD. METHOD LIST_CHANGE. LINE-SPEED = NEW_SPEED. MODIFY TABLE LIST FROM LINE. ENDMETHOD. METHOD LIST_OUTPUT. SY-LSIND = 0. SET TITLEBAR 'TIT'. LOOP AT LIST INTO LINE. IF LINE-FLAG = 'C'. WRITE / ICON_WS_SHIP AS ICON. ELSEIF LINE-FLAG = 'T'. WRITE / ICON_WS_TRUCK AS ICON. ENDIF. WRITE: 'Speed = ', LINE-SPEED. ENDLOOP. ENDMETHOD. ENDCLASS. *****************************************************************

The static method USER_ACTION of the class STATUS triggers the static event BUTTON_CLICKED. The instance methods I_VEHICLE~DRIVE and I_VEHICLE~STOP trigger the instance event I_VEHICLE~SPEED_CHANGE in the classes C_SHIP and C_TRUCK.

Using the Classes in a Program The following program uses the above classes:

REPORT OO_EVENTS_DEMO NO STANDARD PAGE HEADING.

December 1999

1409


BC - ABAP Programming

SAP AG

Events in ABAP Objects - Example

***************************************************************** * Global data of program ***************************************************************** DATA LIST TYPE REF TO C_LIST. ***************************************************************** * Program events ***************************************************************** START-OF-SELECTION. CREATE OBJECT LIST. SET HANDLER: LIST->FCODE_HANDLER, LIST->LIST_CHANGE FOR ALL INSTANCES. *---------------------------------------------------------------AT USER-COMMAND. CALL METHOD STATUS=>USER_ACTION. ***************************************************************** The program creates an object of the class C_LIST and registers the event handler method FCODE_HANDLER of the object for the class event BUTTON_CLICKED, and the event handler method LIST_CHANGE for the event SPEED_CHANGE of all instances that implement the interface I_VEHICLE.

1410

December 1999


SAP AG

BC - ABAP Programming Class Pools

Class Pools This section discusses the structure and special features of class pools.

Global Classes and Interfaces Classes and interfaces are both object types. You can define them either globally in the R/3 Repository or locally in an ABAP program. If you define classes and interfaces globally, they are stored in special ABAP programs called class pools (type K) or interface pools (type J), which serve as containers for the respective object types. Each class or interface pool contains the definition of a single class or interface. The programs are automatically generated by the Class Builder when you create a class or interface. A class pool is comparable to a module pool or function group. It contains both declarative and executable ABAP statements, but cannot be started on its own. Instead, the system can only execute the statements in the class pool on request, that is, when the CREATE OBJECT statement occurs to create instances of the class. Interface pools do not contain any executable statements. Instead, they are used as containers for interface definitions. When you implement an interface in a class, the interface definition is implicitly included in the class definition.

Structure of a Class Pool Class pools are structured as follows:

December 1999

1411


BC - ABAP Programming

SAP AG

Class Pools

CLASS-POOL ... Definition part for types TYPES … CLASS … ... ENDCLASS.

Visibility

INTERFACE … ... ENDINTERFACE. Declaration part of class CLASS … DEFINITION PUBLIC. ... ENDCLASS. Implementation part of class CLASS … IMPLEMENTATION. ... ENDCLASS. Class Pool Class pools contain a definition part for type declarations, and the declaration and implementation parts of the class.

Differences From Other ABAP Programs Class pools are different from other ABAP programs for the following reasons: •

ABAP programs such as executable programs, module pools, or function modules, usually have a declaration part in which the global data for the program is defined. This data is visible in all of the processing blocks in the program. Class pools, on the other hand, have a definition part, in which you can define data and object types, but no data objects or field symbols. The types that you define in a class pool are only visible in the implementation part of the global class.

The only processing blocks that you can use are the declaration part and implementation part of the global class. The implementation part may only implement the methods declared in the global class. You cannot use any of the other ABAP processing blocks (dialog modules, event blocks, subroutines, function modules).

The processing blocks of class pools are not controlled by the ABAP runtime environment. No events occur, and you cannot call any dialog modules or procedures.

1412

December 1999


SAP AG

BC - ABAP Programming Class Pools

Class pools serve exclusively for class programming. You can only access the data and functions of a class using its interface. •

Since events and dialog modules are not permitted in classes, you cannot process screens in classes. You cannot program lists and selection screens in classes, since they cannot react to the appropriate events. It is intended to make screens available in classes. Instead of dialog modules, it will be possible to call methods of the class from the screen flow logic.

Local Classes in Class Pools The classes and interfaces that you define in the definition part of a class pool are not visible externally. Within the class pool, they have a similar function to local classes and interfaces in other ABAP programs. Local classes can only be instantiated in the methods of the global class. Since subroutines are not allowed in class pools, local classes are the only possible modularization unit in global classes. Local classes have roughly the same function for global classes as subroutines in function groups, but with the significant exception that they are not visible externally.

December 1999

1413


BC - ABAP Programming

SAP AG

Appendix

Appendix Übersicht über ABAP-Aufrufe [Page 1421] ABAP-Systemfelder [Page 1498] ABAP-Glossar [Page 1522] Programs, Screens, and Processing Blocks [Page 1415] ABAP Statement Overview [Page 1437] Statements that Introduce Programs [Page 1419] Syntax Conventions [Page 1540]

1414

December 1999


SAP AG

BC - ABAP Programming Programs, Screens, and Processing

Blocks

Programs, Screens, and Processing Blocks This section contains a summary of possible ABAP programs, their screens, and their processing blocks.

Overview Screens

ABAP ABAPruntime runtime environment environment

Processing Processing block block

Processing Processing block block

Processing Processing blocks blocks

...

ABAP ABAP program programwith withparticular particulartype type ABAP programs consist of processing blocks, and can contain screens as components. Both processing blocks and screens are controlled by the ABAP runtime environment.

ABAP Programs ABAP has the following program types: •

Executable Program Type 1; introduced with the REPORT statement; can be started by entering the program name or using a transaction code; can be called using SUBMIT; can have its own screens.

Module Pool Type M; introduced with the PROGRAM statement; can be started using a transaction code; can be called using CALL TRANSACTION or LEAVE TO TRANSACTION; have their own screens.

Function Group Type F; introduced with the FUNCTION-POOL statement; non-executable; container for function modules; can have its own screens.

December 1999

1415


BC - ABAP Programming

SAP AG

Programs, Screens, and Processing Blocks •

Class Definition Type K; introduced with the CLASS-POOL statement; non-executable; container for classes; cannot (currently) have its own screens.

Interface Definition Type J; introduced with the CLASS-POOL statement; non-executable; container for interfaces; cannot have its own screens.

Subroutine Pool Type S; introduced with the PROGRAM statement; non-executable; container for subroutines; cannot have its own screens.

Type Groups Type T; introduced with the TYPE-POOL statement; non-executable; container for type definitions; cannot have its own screens.

Include Program Type I; no introductory statement; non-executable; container for source code modules.

Non-executable programs with types F, K, J, S, and T are loaded into memory as required. Include programs are not separately-compiled units; their source code is inserted into the programs in which the corresponding include statement occurs.

Screens ABAP programs with types 1, M, or F can contain and process the following types of screen: •

Screens Defined using the Screen Painter; can be combined into screen sequences; called using CALL SCREEN or a transaction code; processed in dialog modules of the corresponding ABAP program.

Selection Screen Defined within an ABAP program; called by the runtime environment or using the CALL SELECTION-SCREEN statement; processed in event blocks of the corresponding ABAP program.

Lists Defined within an ABAP program; called by the runtime environment; processed in event blocks of the corresponding ABAP program.

Class definitions (type K programs) do not yet support screens. Subroutine pools (type S programs) cannot contain their own screens.

Processing Blocks All ABAP programs are made up of processing blocks. You cannot nest processing blocks. When a program is executed, its processing blocks are called. All of the statements in an ABAP program, apart from its global data declarations, belong to a processing block. ABAP contains the following processing blocks:

1416

December 1999


SAP AG

BC - ABAP Programming Programs, Screens, and Processing

Blocks

Dialog Module Defined between the MODULE...ENDMODULE statements in type 1, M, and F programs; has no local data area and no parameter interface; called using the MODULE statement in screen flow logic; processes screens.

Event Block Defined by one of the event key words; no local data area and no parameter interface; reacts to events in the ABAP runtime environment. (Exceptions: AT SELECTION-SCREEN and GET are implemented internally using subroutines, and have a local data area). We differentiate between: •

Reporting events INITIALIZATION START-OF-SELECTION GET END-OF-SELECTION Called by the ABAP runtime environment while a type 1 program is running; contain application logic for report programs.

Selection screen events AT SELECTION-SCREEN OUTPUT AT SELECTION-SCREEN ON VALUE REQUEST AT SELECTION-SCREEN ON HELP REQUEST AT SELECTION-SCREEN ON <f> AT SELECTION-SCREEN ON BLOCK AT SELECTION-SCREEN ON RADIOBUTTON GROUP AT SELECTION SCREEN AT SELECTION SCREEN ON END OF <f> Called by the ABAP runtime environment following a user action on a selection screen in a type 1, M, or F program; process selection screens.

List events TOP-OF-PAGE END-OF-PAGE AT LINE-SELECTION AT PF<nn> AT USER-COMMAND Called by the ABAP runtime environment while a list is being created or after a user action on a list in a type 1, M, or F program.

December 1999

1417


BC - ABAP Programming

SAP AG

Programs, Screens, and Processing Blocks

Procedures ABAP contains the following procedures. They have a local data area and a parameter interface: •

Subroutines Defined by FORM...ENDFORM in any program except for type K; called using the PERFORM statement in any ABAP program.

Function modules Defined by FUNCTION...ENDFUNCTION in type F programs; called using CALL FUNCTION from any ABAP program.

Methods Defined by METHOD...ENDMETHOD in global classes in programs with type K, or in local classes in any ABAP program; called using CALL METHOD from any ABAP program for global classes, and, for local classes, from the program in which the class is defined.

1418

December 1999


SAP AG

BC - ABAP Programming Introductory Statements for Programs

Introductory Statements for Programs Each ABAP program type has a statement that introduces programs of that type:

Program type

Introductory statement

1

REPORT

M

PROGRAM

F

FUNCTION-POOL

K

CLASS-POOL

J

CLASS-POOL

S

PROGRAM

T

TYPE-POOL

I

-

Include programs (type I) are not compilation units. Instead, they are purely modularization units that are only ever used in the context of the programs to which they belong. For this reason, include programs do not have a special introductory statement. The following sections describe the function of introductory statements:

REPORT and PROGRAM The REPORT and PROGRAM statements currently have the same function. They allow you to specify the message class of the program and the formatting options for its default list. Whether a program is executable or can only be started using a transaction code depends exclusively on the program type and not on the statement that introduces it. However, executable programs should always begin with a REPORT statement, and module pools always with a PROGRAM statement. Subroutine pools (type S programs) should also always begin with a PROGRAM statement.

FUNCTION-POOL The introductory statement FUNCTION-POOL declares a program in which you can define function modules. At runtime, function pool programs are loaded in to a new program group [Page 498] with their own user dialogs and their own shared data areas in the internal session of the calling program. For this reason, function groups (type F programs) must always begin with a FUNCTION-POOL statement. This is usually generated by the Function Builder. Type 1, M, or S programs should not begin with a FUNCTION-POOL statement, since they would then not share common data areas with the caller. However, in exceptional cases, you can introduce a type 1 or type M program with FUNCTION-POOL to ensure that externally-called subroutines can process their own screens. As in the REPORT and PROGRAM statements, you can specify the message class and standard list formatting options of the program in the FUNCTION-POOL statement.

CLASS-POOL The introductory statement CLASS-POOL can only be used for class or interface definitions (type K or J programs). A program introduced with the CLASS-POOL statement can only contain global type definitions and definitions of classes and interfaces. The CLASS-POOL statement is

December 1999

1419


BC - ABAP Programming

SAP AG

Introductory Statements for Programs generated automatically where required by the Class Builder - you should not insert it into programs manually.

TYPE-POOL The introductory statement TYPE-POOL can only be used for type groups (type T programs). A program introduced with the TYPE-POOL statement can only contain global type definitions and constants declarations. The CLASS-POOL statement is generated automatically where required by the ABAP Dictionary - you should not insert it into programs manually.

1420

December 1999


SAP AG

BC - ABAP Programming Overview of ABAP Calls

Overview of ABAP Calls ABAP programs can contain calls to various other program units. The units can be classified according to the context in which they run when called, and according to the type of unit. Call contexts: •

Internal Calls [Page 1423]

External Procedure Calls [Page 1425]

External Program Calls [Page 1427]

Callable units: •

ABAP Programs [Page 1430]

Procedures [Page 1432]

Screens and Screen Sequences [Page 1434]

December 1999

1421


BC - ABAP Programming

SAP AG

Call Contexts

Call Contexts Internal Calls [Page 1423] External Procedure Calls [Page 1425] External Program Calls [Page 1427]

1422

December 1999


SAP AG

BC - ABAP Programming Internal Calls

Internal Calls In an internal call, the called unit is part of the calling program. The source code of the called unit is either part of the source code of the calling program or attached to it as an include program. This means that, at runtime, no extra programs have to be loaded into the internal session of the calling program. You can use internal calls for procedures and subscreens.

ABAP program

Function group (Type F)

Class pool (Type K)

Processing block

Processing block

Method

Subroutine

Function module

Method

Internal sessions

Procedures All procedures [Page 1432] - subroutines, function modules, and methods - can be called internally in the program in which they are defined. •

Using an internal call is the recommended and most frequently used method of calling a subroutine.

Function modules can only be called internally if a function module calls another function module from the same group. Otherwise, function modules are called externally.

Methods are called internally when a class calls one of its own methods, or when you use a method of a local class in an ABAP program.

December 1999

1423


BC - ABAP Programming

SAP AG

Internal Calls

Screens All of the screens [Page 1434] belonging to a program can be called internally. When you call a screen, a screen sequence begins, in which the next screen is defined by the next screen specified in the current screen. The special screen types selection screen and list are only ever called internally. You should only call subscreens internally.

1424

December 1999


SAP AG

BC - ABAP Programming External Procedure Calls

External Procedure Calls In an external procedure call, the called unit is not part of the calling program. This means that, at runtime, an extra program has to be loaded into the internal session of the calling program. You can use external calls for procedures and subscreens. The additional loaded program is an instance with its own global data area. When you call an external subroutine, the calling program and the loaded program form a single program group, unless the loaded program is a function group. Function groups always form their own program group. Furthermore, when you call methods externally, they and their class form their own program group. Within a program group, interface work areas [Page 131] and the screens of the calling program are shared. Classes cannot contain interface work areas.

Internal Session Main Program Group Main program (Type 1 or M)

Main program (Type 1, M, S)

Interface work areas Processing block

FORM

Additional Program Group Function group (Type F)

Main program (Type 1, M, S)

Class Class pool (Type K)

Interface work areas FUNCTION

FORM

METHOD

Procedures All procedures [Page 1432], that is, subroutines, function modules, and methods, can be called externally from any ABAP program. •

You are recommended not to use external calls for subroutines, in particular if the subroutines share interface work areas [Page 131] with the calling program and call their own screens. The program group into which the main program of a subroutine is loaded depends on the sequence of the calls. The sequence is often not statically defined, but changes depending on user actions or the contents of fields. For this reason, it may not

December 1999

1425


BC - ABAP Programming

SAP AG

External Procedure Calls be clear which interface work areas [Page 131] and screens will be used by an externally-called subroutine. •

Function modules are intended for external procedure calls.

•

Accessing an externally-visible method of a global class counts as an external procedure call.

Subscreens You can call a subscreen screen [Page 1434] externally by specifying an ABAP program other than the current program in the CALL SUBSCREEN statement. This program is treated in the same way as in an external subroutine call. In other words, it is loaded into the program group of the calling program, or, if it is a function group, as its own program group in the same internal session as the calling ABAP program. For this reason, you should not use external subscreens that do not belong to a function group, since the same problems can occur with interface work areas [Page 131] and screen calls as can occur with external subroutines.

1426

December 1999


SAP AG

BC - ABAP Programming External Program Calls

External Program Calls In an external program call, the unit that you call is an independent ABAP program. At runtime, the called program is loaded into its own internal session in the current external session. Any program that can have its own screens can be called in an external program call. The most usual external program calls are for executable programs and transactions assigned to a module pool.

ABAP runtime environment

Executable ABAP program VerarbeitungsVerarbeitungsblรถcke Processing blรถcke blocks

ABAP runtime environment

ABAP program with screens VerarbeitungsVerarbeitungsblรถcke Processing blรถcke blocks

Internal session n

Internal session n

ABAP program

ABAP program

Processing block

Internal session m

December 1999

Processing block

Internal session m

1427


BC - ABAP Programming

SAP AG

External Program Calls

Executable Programs When you call an executable program, the program is loaded, and the ABAP runtime environment calls the processors that control its flow.

Transactions When you call a transaction, the program linked to the transaction code is loaded and its initial screen is processed. The initial screen calls dialog modules in the called program, and then branches to its next screen.

1428

December 1999


SAP AG

BC - ABAP Programming Callable Units

Callable Units ABAP Programs [Page 1430] Procedures [Page 1432] Screens and Screen Sequences [Page 1434]

December 1999

1429


BC - ABAP Programming

SAP AG

ABAP Programs

ABAP Programs Any ABAP programs with type 1, M, or F that have their own screens can be called externally in their own internal session and with their own SAP LUW.

SUBMIT … AND RETURN ... CALL TRANSACTION ...

SUBMIT … LEAVE TO TRANSACTION ...

ABAP program

ABAP program

VerarbeitungsVerarbeitungsblöcke Processing blöcke blocks

VerarbeitungsVerarbeitungsblöcke Processing blöcke blocks

Internal session n

Internal session m

ABAP program

ABAP program

Processing block

Processing block

Internal session m

Internal session m

Executable Programs You can call executable programs directly using the statement SUBMIT <prog> ... [AND RETURN]. If you omit the AND RETURN addition, the system terminates the calling program and calls the new executable program <prog>. The internal session of the calling program is replaced by the internal session of the new program. When the new program has finished, control returns to the point from which the calling program was started. If you use the AND RETURN addition, the executable program <prog> is started in a new session. The internal session of the calling program is returned, and control returns to the calling program after the new program has finished.

1430

December 1999


SAP AG

BC - ABAP Programming ABAP Programs

All Programs with Screens You can assign a transaction code to any screen of a program. Normally, you assign a transaction code to a single screen in a module pool (type M program). This then allows you to start the program using one of the statements LEAVE TO TRANSACTION <tcode> ... or CALL TRANSACTION <tcode> ... The program starts by processing the screen that you specified when you defined the transaction code. This is called the initial screen. If you use LEAVE TO TRANSACTION, the calling program terminates, and its internal session is replaced by the internal session of the new program. When the new program has finished, control returns to the point from which the calling program was started. If you use CALL TRANSACTION, the calling program is started in a new internal session, and the internal session of the calling program is retained. When the new program has finished, control returns to the point from which the calling program was started.

Leaving a Called Program To leave a program that you have called, use the ABAP statement LEAVE PROGRAM.

December 1999

1431


BC - ABAP Programming

SAP AG

Procedures

Procedures Called procedures (subroutines, function modules, and methods) always run in the same internal session as the calling program.

ABAP program

Processing block

PERFORM ... CALL FUNCTION ‌ CALL METHOD ...

ABAP program

Function group

Class pool

Subroutine

Function module

Method

Procedure

Internal session

Subroutines You call a subroutine using the PERFORM <subr>[(<prog>)] ... statement. If you omit the (<prog>) addition, the subroutine is called internally, that is, it belongs to the calling program and must not be loaded. If you use the (<prog>) addition, the call is external, that is, the subroutine belongs to the program <prog>. When you call the subroutine, the entire program <prog> is loaded into the internal session of the calling program (if it has not been already). The loaded program belongs to the program group of the calling program. However, if the subroutine belongs to a function group, a new additional program group is created. The program group to which the external subroutine belongs determines the interface work areas and screens that it will use. However, this assignment can vary dynamically, so it is best to avoid using external subroutines.

Function Modules You call function modules using the CALL FUNCTION <func> ... statement. Function module calls are external unless a function module is called by another procedure within the same function group. When you call a function module, its entire function group is loaded into the internal session of the calling program (unless it has already been

1432

December 1999


SAP AG

BC - ABAP Programming Procedures

loaded). Within the internal session, the function group forms an additional program group with its own interface work areas and screens. This means that function modules provide better encapsulation of data and screens than external subroutines.

Methods You call a method using the CALL METHOD [<ref>->|<class>=>]<meth> ... statement. If you omit the <ref> or <class> part of the statement, the call is local within the same class. The class is not reloaded. If you use <ref> or <class>, the method call applies to the method of the class specified through the object reference <ref> or the class name <class>. When you call the method, the entire class pool is loaded into the internal session of the calling program (unless it has already been loaded). The class pool forms an additional program group in the internal session, which does not share data and screens with the caller, and from which you cannot call external subroutines.

Leaving a Called Procedure You can leave a procedure using the EXIT. or CHECK <logexp>. statement.

December 1999

1433


BC - ABAP Programming

SAP AG

Screens and Screen Sequences

Screens and Screen Sequences Screens and their flow logic, which together form dynamic programs, are instances that control the flow of an ABAP program by calling a series of dialog modules. Screens can be combined into sequences, where the next screen in the sequence can be defined either statically or dynamically. The simplest screen sequence is a single screen. The sequence starts when you call its first screen. You can do this in a variety of ways.

CALL SCREEN ...

LEAVE TO TRANSCACTION … CALL TRANSACTION … CALL DIALOG ...

ABAP program

ABAP program

VerarbeitungsVerarbeitungsblock Processing block blocks

VerarbeitungsVerarbeitungsProcessing blöcke blöcke blocks

Internal session m

Internal session n

Calling Screens Internally from the Same ABAP Program In any ABAP program that can have its own screens (type 1, M, or F), you can use the CALL SCREEN <dynnr>. statement to call a screen and its subsequent sequence within that program. The flow logic of each screen calls dialog modules in the program that called the screen. When the screen sequence ends, control returns to the statement after the original CALL SCREEN statement.

Calling Screens as a Transaction A transaction (or transaction code) links a screen to a main program (usually a module pool). You can call a transaction from any ABAP program using the

1434

December 1999


SAP AG

BC - ABAP Programming Screens and Screen Sequences

CALL TRANSACTION <tcod> ... or LEAVE TO TRANSACTION <tcod> ... statement. The transaction starts with the initial screen that you specified when you defined the transaction code. The program of the transaction is started in a new internal session, and has its own SAP LUW. The screens in the screen sequence call the various dialog modules of the main program. When the screen sequence is finished, control returns to the program that contained the CALL TRANSACTION statement. If you start a transaction using LEAVE TO TRANSACTION, control returns to the point from which the calling program was started.

Calling Screens as a Dialog Module A dialog module can be linked to a screen of any main program, usually a module pool. You can call a dialog module from any ABAP program using the CALL DIALOG <diag> ... statement. The dialog module starts with the initial screen that you specified when you defined it. The program of the dialog module is started in a new internal session, and has its own SAP LUW. The screens in the screen sequence call the various dialog modules of the main program. When the screen sequence ends, control returns to the statement after the dialog module call. Dialog modules are obsolete, and should no longer be used. Instead, you can encapsulate screen sequences in function groups and call them from an appropriately-programmed function module.

Leaving a Screen Sequence A screen sequence terminates when a screen ends and the defined next screen has the number 0. You can leave a single screen within a sequence using the LEAVE SCREEN. or LEAVE TO SCREEN <dynnr>. statement. These statements exit the current screen and call the defined next screen. If the next screen is screen 0, the entire screen sequence concludes.

Special Single Screens There are three special types of screen:

Selection Screen A selection screen is a special screen, created using ABAP statements. You can only call them using the CALL SELECTION-SCREEN <dynnr> ... statement. The selection screen is processed (reaction to user input in the selection screen events) in the calling program.

December 1999

1435


BC - ABAP Programming

SAP AG

Screens and Screen Sequences

List Each screen in a screen sequence has a corresponding list system of twenty levels. You can start this list system using the LEAVE TO LIST-PROCESSING [AND RETURN TO SCREEN <dynnr>]. statement. This statement calls a system program that contains the standard container screen used for lists. This replaces the current screen. On this screen, you can display a basic list and up to 19 detail lists. List processing (reacting to user actions in list events) takes place in the calling program. You can leave the list system using the LEAVE LIST-PROCESSING. statement. In an executable program, the list system is automatically called after the last reporting event.

Subscreens In the PBO event of the flow logic of a screen, you can call a subscreen using the following statement: CALL SUBSCREEN <area> INCLUDING [<prog>] <dynnr>. The screen of a subscreen that you call is placed in the subscreen area <area> on the main screen. If you do not specify a program <prog>, the system uses a screen from the current ABAP program. If you do specify a program <prog>, the system uses a screen from the program <prog> for the subscreen. This program is treated in the same way as an external subroutine call. In other words, it is loaded into the program group of the calling program, or, if it is a function group, as its own program group in the same internal session as the calling ABAP program.

1436

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

ABAP Statement Overview The following is an alphabetical classification of the most important generally-released ABAP statements. A B C D E F G H I L M N O P R S T U W

A ADD for Single Fields Adds two single fields.

Syntax

ADD <n> TO <m>. The contents of <n> are added to the contents of <m>. The result is placed in <m>. Equivalent of <m> = <m> + <n>.

ADD for Sequences of Fields Adds sequences of fields.

Syntax

ADD <n1> THEN <n2> UNTIL <nz> GIVING <m>. ADD <n1> THEN <n2> UNTIL <nz> ACCORDING TO <sel> GIVING <m>. ADD <n1> THEN <n2> UNTIL <nz> TO <m>. ADD <n1> FROM <m1> TO <mz> GIVING <m>. If <n1>, <n2>,..., <nz> is a sequence of fields with a uniform gap between each, the same type, and the same length, the fields are added together and the result placed in <m>. The variants allow you to restrict the fields to a partial sequence, to include <m> in the sum, or to perform the operation for a sequence of consecutive fields.

ADD-CORRESPONDING Adds components of structures.

Syntax

ADD-CORRESPONDING <struc1> TO <struc2>. Adds together all of the components of structures <struc1> and <struc2> that have identical names, and places the results in the corresponding components of <struc2>.

December 1999

1437


BC - ABAP Programming

SAP AG

ABAP Statement Overview

ALIASES Defines class-specific alias names for an interface component in ABAP Objects.

Syntax ALIASES <alias> FOR <intf~comp>. Defines <alias> within a class as a synonym for the interface component <intf~comp>.

APPEND Appends one or more lines to the end of an index table.

Syntax

APPEND <line>|LINES OF <jtab> TO <itab>. Appends one line <line> or several lines of an internal table <jtab> to the index table <itab>.

ASSIGN Assigns a field to a field symbol.

Syntax

ASSIGN <f> TO <FS>. Assigns the data object <f> to the field symbol <FS>, after which, <FS> points to the data object. The pointed brackets are part of the syntax of the field symbol.

AT for Event Blocks Event keywords for defining event blocks for screen events.

Syntax

AT SELECTION-SCREEN... AT LINE-SELECTION. AT USER-COMMAND. AT PFn. User actions on selection screens or lists trigger events in the ABAP runtime environment. The event keywords define event blocks, which are called when the corresponding event occurs.

AT for Control Levels Control level change when you process extracts and internal tables in a loop.

Syntax

AT NEW <f>.

1438

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

AT END OF <f>. AT FIRST. AT LAST. AT <fg>. These statements are used in control level processing with extract datasets or internal tables. Each introduces a statement block that you must conclude with the ENDAT statement. The statements between AT and ENDAT are executed whenever the corresponding control level change occurs.

AUTHORITY-CHECK Checks the authorization of a user.

Syntax

AUTHORITY-CHECK OBJECT <object> ID <name1> FIELD <f1> ID <name2> FIELD <f2> ... ID <name10> FIELD <f10>. The statement checks whether the user has all of the authorizations defined in the authorization object <object>. <name1>,..., <name10> are the authorization fields in the object, and <f1>,... ,<f10> are data objects in the program. The value of each data object is checked against the corresponding authorization field.

B BACK Relative positioning for output in a list.

Syntax

BACK. Positions the list output either in the first column of the first line after the page header on the current page, or in the first column of the first line of a line block if you have previously used the RESERVE statement.

BREAK-POINT Starts the ABAP Debugger.

Syntax

BREAK-POINT. Interrupts program execution and starts the Debugger. This allows you to test your programs by halting them at any point.

December 1999

1439


BC - ABAP Programming

SAP AG

ABAP Statement Overview

C CALL CUSTOMER-FUNCTION Calls a customer function module.

Syntax

CALL CUSTOMER-FUNCTION <func>... Similar to CALL FUNCTION. The function module that it calls must be programmed and activated by a customer using the modification concept.

CALL FUNCTION Calls a function module.

Syntax CALL FUNCTION <func> [EXPORTING ... fi = ai... ] [IMPORTING ... fi = ai... ] [CHANGING ... fi = ai... ] [TABLES ... fi = ai... ] [EXCEPTIONS... ei = ri... ] [DESTINATION <dest>] [IN UPDATE TASK] [STARTING NEW TASK] [IN BACKGOUND TASK]. Starts a function module, either in the same system or in an external system, depending on the type of call that you use. You can also use update function modules in transactions, and call function modules asynchronously. The remaining additions are used for the parameter interface of the function module, in which you can specify actual parameters and determine how to handle exceptions.

CALL DIALOG Calls a dialog module.

Syntax CALL DIALOG <dialog> [AND SKIP FIRST SCREEN] [EXPORTING... fi = ai... ] [IMPORTING... fi = ai... ] [USING itab]. Calls the dialog module <dial>. A dialog module is an ABAP program containing a chain of screens. It does not have to be called using a transaction code, and runs in the same SAP LUW as the program that called it. The additions allow you to skip the first screen in the chain and pass actual parameters to and from the parameter interface of the dialog module.

1440

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

CALL METHOD Calls a method in ABAP Objects.

Syntax CALL METHOD <meth> [EXPORTING ... <ii> =.<fi>... ] [IMPORTING ... <ei> =.<gi>... ] [CHANGING ... <ci> =.<fi>... ] [RECEIVING r = h ] [EXCEPTIONS... <ei> = ri... ] Calls a static method or instance method <meth>. The additions allow you to pass parameters to and from the method and handle its exceptions.

CALL METHOD OF Calls a method in OLE2 Automation.

Syntax

CALL METHOD OF <obj> <m>. Calls the method <m> of the OLE2 Automation object <obj>.

CALL SCREEN Calls a sequence of screens.

Syntax

CALL SCREEN <scr> [STARTING AT <X1> <Y1>] [ENDING AT <X2> <Y2>]. Calls the sequence of screens beginning with screen number <scr>. All of the screens in the chain belong to the same ABAP program. The chain ends when a screen has the next screen number 0. The additions allow you to call a single screen as a modal dialog box.

CALL SELECTION-SCREEN Calls a selection screen.

Syntax

CALL SELECTION-SCREEN <scr> [STARTING AT <x1> <y1>] [ENDING AT <x2> <y2>]. Calls a user-defined selection screen in a program. Selection screens are processed in the AT SELECTION-SCREEN events. The additions allow you to call a selection screen as a modal dialog box.

CALL TRANSACTION Calls a transaction.

December 1999

1441


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

CALL TRANSACTION <tcod> [AND SKIP FIRST SCREEN] [USING <itab>]. Calls the transaction <tcod> while retaining the data in the calling program. At the end of the transaction, control returns to the point from which the transaction was called. The additions allow you to skip the first screen of the transaction or pass an internal table for batch input to it.

CASE Conditional branching.

Syntax

CASE <f>. Opens a CASE control structure that must conclude with the ENDCASE statement. This allows you to branch to various statement blocks (introduced with the WHEN statement), depending on the contents of the data object <f>.

CATCH Catches runtime errors.

Syntax

CATCH SYSTEM-EXCEPTIONS <except1> = <rc1>... <exceptn> = <rcn>. Introduces a CATCH area, which concludes with an ENDCATCH statement. If a catchable runtime error <excepti> occurs within this block, the current block terminates immediately, and the program jumps directly to the corresponding ENDCATCH statement, filling SY-SUBRC with <rci>.

CHECK Conditional termination of a loop pass or a processing block.

Syntax

CHECK <logexp>. If the logical expression <logexp> is true, the program continues at the next statement. If, however, <logexp> is false, the current loop pass terminates and the next begins. If the program is not currently processing a loop, the current processing block terminates. There are special forms of the CHECK statement for use with selection tables and in GET event blocks.

CLASS - Declaration Declares a class in ABAP Objects.

1442

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax

CLASS <class> DEFINITION [PUBLIC] [INHERITING FROM <superclass>] [DEFERRED] [LOAD]. This statement introduces the declaration part of a class <class>. The declaration part concludes with ENDCLASS, and contains the declarations of all components in the class. The PUBLIC addition is generated by the Class Builder, and defines a global class in the class library. The INHERITING FROM addition allows you to derive the class <class> from a superclass <superclass>. The DEFERRED addition declares the class before it is actually defined. The LOAD addition loads a class explicitly from the class library.

CLASS – Implementation Implementation of a class in ABAP Objects.

Syntax

CLASS <class> IMPLEMENTATION. Introduces the implementation part of a class <class>. This concludes with the ENDCLASS statement, and contains the implementations of all of the methods in the class.

CLASS-DATA Declares static attributes of a class or interface.

Syntax

CLASS-DATA <a>... Like DATA. However, the attribute <a> is declared as a static attribute. Static attributes are independent of instances of the class. Only one copy of the attribute exists in the class, and this is shared by all instances.

CLASS-METHODS Declares static methods of a class or interface.

Syntax

CLASS-METHODS <meth>... Like METHODS. However, the method <meth> is declared as a static method. A static method can access static attributes, and may only trigger static events.

CLASS-EVENTS Declares static events of a class or interface.

December 1999

1443


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

CLASS-EVENTS <evt>... Like EVENTS. However, the event <evt> is declared as a static event. Static events are the only events that may be triggered in a static method.

CLEAR Resets a variable to its initial value.

Syntax

CLEAR <f>. Resets the variable <f>, which may be of any data type, to the initial value defined for that type.

CLOSE DATASET Closes a file.

Syntax

CLOSE DATASET <dsn>. Closes a file <dsn> on the application server previously opened with the OPEN DATASET statement.

CLOSE CURSOR Closes a database cursor.

Syntax

CLOSE CURSOR <c>. Closes a cursor opened using the OPEN CURSOR statement.

COLLECT Inserts lines into an internal table in summarized form.

Syntax

COLLECT <line> INTO <itab>. The statement first checks whether the internal table contains an entry with the same key. If not, it acts like INSERT. If there is already a table entry with the same key, COLLECT does not insert a new line. Instead, it adds the values from the numeric fields of the work area <line> to the values in the corresponding fields of the existing table entry.

1444

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

COMMIT Concludes an SAP LUW.

Syntax

COMMIT WORK [AND WAIT]. All database updates are written firmly to the database, and all locks are released. Triggers the database update. The AND WAIT addition allows you to pause the program until the update is complete. If you omit it, the database is updated asynchronously.

COMMUNICATION Allows communication between programs.

Syntax

COMMUNICATION INIT DESTINATION <dest> ID <id> [Additions]. COMMUNICATION ALLOCATE ID <id> [Additions]. COMMUNICATION ACCEPT ID <id> [Additions]. COMMUNICATION SEND ID <id> BUFFER <f> [Additions]. COMMUNICATION RECEIVE ID <id> [Additions]. COMMUNICATION DEALLOCATE ID <id> [Additions]. These statements allow you to initialize, start, and accept program-to-program communication, send and receive data between partner programs, and then terminate the connection.

COMPUTE Performs numeric operations.

Syntax

COMPUTE <n> = <expression>. The result of the mathematical expression in <expression> is assigned to the result field <n>. The COMPUTE keyword is optional.

CONCATENATE Combines a series of strings into a single string.

Syntax

CONCATENATE <c1>... <cn> INTO <c> [ SEPARATED BY <s> ]. The strings <c1> to <cn> are concatenated, and the result placed in <c>. The SEPARATED BY addition allows you to specify a string <s> to be placed between the strings.

December 1999

1445


BC - ABAP Programming

SAP AG

ABAP Statement Overview

CONDENSE Removes spaces from a string.

Syntax

CONDENSE <c> [NO-GAPS]. Removes all leading spaces, and replaces other series of blanks with a single space in the character field <c>. If you use the NO-GAPS addition, all of the spaces are removed.

CONSTANTS Declares constant data objects.

Syntax

CONSTANTS <c>... VALUE [<val> | IS INITIAL]... The syntax is similar to DATA, except that the VALUE addition is required, and that internal tables and deep structures cannot be declared as constants. The starting value that you assign in the VALUE addition cannot be changed during the program.

CONTINUE Ends a loop pass.

Syntax

CONTINUE. Only possible within loops. This statement terminates the current loop pass and starts the next.

CONTEXTS Declares a context.

Syntax CONTEXTS <c>. Generates an implicit data type CONTEXT_<c>, which you can use to create context instances.

CONTROLS Defines a control.

Syntax

CONTROLS <ctrl> TYPE <ctrl_type>. Defines an ABAP runtime object <ctrl>. This displays data in a particular format on a screen, depending on the type <ctrl_type>. Currently, <ctrl_type> may be a table control or tabstrip control.

1446

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

CONVERT for Dates Converts a data into an inverted date form.

Syntax

CONVERT DATE <d1> INTO INVERTED-DATE <d2>. CONVERT INVERTED-DATE <d1> INTO DATE <d2>. If <d1> and <d2> are date fields in the internal form YYYYMMDD, the nines complement of <d1> is placed in field <d2> and vice versa. In inverted date format, the most recent date has the smaller numerical value.

CONVERT for Timestamps Converts a timestamp into the correct date and time for the current time zone.

Syntax

CONVERT TIME STAMP <tst> TIME ZONE <tz> INTO DATE <d> TIME <t>. CONVERT DATE <d> TIME <t> INTO TIME STAMP <tst> TIME ZONE <tz>. As long as <tst> has type P(8) or P(11) with 7 decimal placed, and <tz> has type C(6), the time stamp <tst> will be converted to the correct date <d> and time <t> for the time zone <tz>.

CONVERT for Text Converts a text into a format that can be sorted alphabetically.

Syntax

CONVERT TEXT <text> INTO SORTABLE CODE <x>. <text> must have type C and <x> must have type X. The string is then converted so that the relative order of the characters allows them to be sorted alphabetically in the current text environment.

CREATE OBJECT in ABAP Objects Creates an object in ABAP Objects.

Syntax

CREATE OBJECT <cref>. <cref> must be a reference variable, defined with reference to a class. CREATE OBJECT then creates an object of that class, to which the reference in <cref> then points.

CREATE OBJECT in OLE2 Automation Creates an external object in OLE2 Automation.

December 1999

1447


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

CREATE OBJECT <obj> <class>. If <class> is a class assigned to an automation server, an initial object <obj> of this class is created.

D DATA with Reference to Declared Data Types Declares variables with a previously-declared data type.

Syntax DATA <f>... [TYPE <type>|LIKE <obj>]... [VALUE <val>]. Declares a variable <f> with the fully-defined data type <type> or the same data type as another data object <obj>. The data type <type> can be D, F, I, T, a type defined locally in the program using the TYPES statement, or a type from the ABAP Dictionary. The data object <obj> is a data object or line of an internal table that has already been defined. The VALUE addition allows you to specify a starting value.

DATA with Reference to Generic Data Types Declares variables by completing the description of a generic type.

Syntax DATA <f>[(<length>)] TYPE <type> [DECIMALS <d>]... [VALUE <val>]. DATA <f> TYPE <itab>. The data type <type> can be C, N, P, or X. In the <length> option, you specify the length of the field. If you do not specify the length, the default value for the data type is used. If <type> is P, you can use the DECIMALS addition to specify a number of decimal places <d>. If you do not specify a number of decimal places, it is set to none. If you do not specify a type, the system uses the default type C.

Syntax DATA <f> TYPE <itab>. The data type <itab> is a standard internal table with generic key. The default key is automatically used in the DATA statement.

DATA, Creating an Associated Data Type Declares variables with data types that only exist as an attribute of the variable.

Syntax DATA <f> TYPE REF TO <class>|<interface>.

1448

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Declares the variable <f> as a reference variable for the class <class> or the interface <interface>.

Syntax DATA: BEGIN OF <structure>, ... <fi>..., ... END OF <structure>. Combines the variables <fi> to form the structure <structure>. You can address the individual components of a structure by placing a hyphen between the structure name and the component name: <structure>-<fi>.

Syntax DATA <f> TYPE|LIKE <tabkind> OF <linetype> WITH <key>. Declares the variable <f> as an internal table with the table type <tabkind>, line type <linekind>, and key <key>.

DATA for Shared Data Areas Declares shared data areas in a program.

Syntax

DATA: BEGIN OF COMMON PART <c>, <fi>... END OF COMMON PART. The variables <fi> are assigned to a data area <c>, which can be defined in more than one program. These data areas use the same memory addresses for all programs that are loaded into the same internal session.

DEFINE Defines a macro.

Syntax

DEFINE <macro>. Introduces the definition of the macro <macro>. Each macro must consist of complete ABAP statement and be concluded with the END-OF-DEFINITION statement.

DELETE for Files Deletes files on the application server.

Syntax

DELETE DATASET <dsn>.

December 1999

1449


BC - ABAP Programming

SAP AG

ABAP Statement Overview Deletes the file <dsn> from the file system of the application server.

DELETE for Database Table Entries Deletes entries from database tables.

Syntax

DELETE FROM <dbtab> WHERE <cond>. Deletes all of the lines from the database table <dbtab> that satisfy the WHERE condition.

Syntax DELETE <dbtab> FROM <wa>. DELETE <dbtab> FROM TABLE <itab>. Deletes the lines with the same primary key as the work area <wa>, or all of the lines from the database table with the same primary key as one of the lines in the internal table <itab>. The work area <wa> or the lines of the internal table <itab> must be at least as long as the primary key of the database table and have the same alignment.

DELETE for Cluster Database Tables Deletes data clusters from cluster database tables.

Syntax DELETE FROM DATABASE <dbtab>(<ar>) ID <key>. Deletes the entire data cluster from the area <ar> with the name <key> from the cluster database table <dbtab>.

DELETE for the Cross-Transaction Application Buffer Deletes data clusters from the cross-transaction application buffer.

Syntax DELETE FROM SHARED BUFFER <dbtab>(<ar>) ID <key>. Deletes the data cluster for the area <ar> with the name <key> stored in the cross-transaction application buffer for the table <dbtab>.

DELETE for Lines from an Internal Table Deletes lines from internal tables of any type.

Syntax DELETE TABLE <itab> FROM <wa>. DELETE TABLE <itab> WITH TABLE KEY <k1> = <f1>... <kn> = <fn>.

1450

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Deletion using the table key: All lines with the same key are deleted. The key values are taken either from a compatible work area <wa> or specified explicitly.

Syntax DELETE <itab> WHERE <cond>. Deletion using a condition: Deletes all table entries that satisfy the logical expression <cond>. The logical condition may consist of more than one expression. However, the first operand in each expression must be a component of the line structure.

Syntax DELETE ADJACENT DUPLICATE ENTRIES FROM <itab> [COMPARING... ]. Deletes adjacent duplicate entries, either by comparing the key fields or the comparison fields specified explicitly in the COMPARING addition.

DELETE for Lines from Index Tables Deletes lines from index tables.

Syntax DELETE <itab> [INDEX <idx>]. If you use the INDEX option, deletes the line with the index <idx> from the table <itab>. If you do not use the INDEX option, the statement can only be used within a LOOP ‌ ENDLOOP construction. In this case, it deletes the current line.

Syntax DELETE <itab> [FROM <n1>] [TO <n2>] [WHERE <cond>]. Deletes all rows from <itab> with index between <n1 > and <n 2 > an which satisfy the WHERE condition. If you do not use the FROM addition, the system deletes lines starting at the beginning of the table. If you do not use the TO addition, the system deletes lines to the end of the table. The logical expression <cond> can consist of more than one expression. However, the first operand in each expression must be a component of the line structure of the internal table.

DEMAND Retrieves values from a context instance.

Syntax DEMAND <val1> = <f 1>... <val n> = <f n> FROM CONTEXT <inst> [MESSAGES INTO <itab>]. Fills the fields <fn> with the values <valn> of the context instance <inst>. The MESSAGES addition allows you to control how messages from the context are handled in the program.

DESCRIBE DISTANCE Determines the distance between two fields.

December 1999

1451


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

DESCRIBE DISTANCE BETWEEN <f1> AND <f2> INTO <f3>. Writes the distance in bytes between fields <f1> and <f2> to <f3>, always including the length of the field that occurs first in memory.

DESCRIBE FIELD Describes the attributes of a field.

Syntax DESCRIBE FIELD <f> [LENGTH <l>] [TYPE <t> [COMPONENTS <n>]] [OUTPUT-LENGTH <o>] [DECIMALS <d>] [EDIT MASK <m>] [HELP-ID <h>]. The attributes of the data object <f> named in the additions to the statement are placed in the corresponding variables. You can use any number of additions in a single statement.

DESCRIBE LIST Describes the attributes of a list.

Syntax

DESCRIBE LIST NUMBER OF LINES <lin> [INDEX <idx>]. DESCRIBE LIST NUMBER OF PAGES <n> [INDEX <idx>]. DESCRIBE LIST LINE <lin> PAGE <pag> [INDEX <idx>]. DESCRIBE LIST PAGE <pag> [INDEX <idx>]... Depending on the variant of the statement that you use, writes the number of lines, number of pages, a line of a list on a given page, or various attributes of a page to variables.

DESCRIBE TABLE Describes the attributes of an internal table.

Syntax

DESCRIBE TABLE [LINES <l>] [OCCURS<n>] [KIND <k>]. Depending on the additions you use, writes the number of lines occupied, the value specified for the INITIAL SIZE of the table, or the table type into a corresponding variable.

DIVIDE Divides one field by another.

Syntax

DIVIDE <n> BY <m>.

1452

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Divides the content of <n> by <m>, and places the result in <n>. The equivalent of n = n / m.

DIVIDE-CORRESPONDING Divides matching components of structures.

Syntax

DIVIDE-CORRESPONDING <struc1> BY <struc2>. Divides all matching components of the structures <struc1> and <struc2> and places the results into the corresponding components of <struc1>.

DO Introduces a loop.

Syntax DO [<n> TIMES] [VARYING <f> FROM <f1> NEXT <f2>]. Introduces a statement block that must conclude with ENDDO. If you omit the TIMES addition, the statement block is repeated until a termination statement such as CHECK or EXIT occurs. The TIMES addition restricts the number of loop passes to <n>. The VARYING addition allows you to process a sequence of fields the same distance apart in memory.

E EDITOR-CALL Loads an ABAP program or internal table into a text editor.

Syntax

EDITOR-CALL FOR <itab>... EDITOR-CALL FOR REPORT <prog>... Loads the internal table <itab> or the program <prog> into a text editor, where you can edit it using standard editor functions.

ELSE Introduces a statement block in an IF control structure.

Syntax

ELSE. If the logical expression in an IF statement is false, ELSE introduces the statement block to be executed instead.

December 1999

1453


BC - ABAP Programming

SAP AG

ABAP Statement Overview

ELSEIF Introduces a statement block in an IF control structure.

Syntax

ELSEIF <logexp>. If the logical expression in the preceding IF is false and <logexp> is true, ELSEIF introduces the statement block that will be executed.

END-OF-DEFINITION Concludes a macro definition.

Syntax

END-OF-DEFINITION. This statement concludes a macro definition introduced with DEFINITION.

END-OF-PAGE Event keyword for defining an event block for a list event.

Syntax

END-OF-PAGE. Whenever the page footer is reached while a list is being created, the runtime environment triggers the END-OF-PAGE event, and the corresponding event block is executed.

END-OF-SELECTION Event keyword for defining an event block for a reporting event.

Syntax

END-OF-SELECTION. Once a logical database has read all of the required lines and passed them to the executable program, the runtime environment triggers the END-OF-SELECTION event, and the corresponding event block is executed.

ENDAT Concludes a statement block in control level processing.

Syntax

ENDAT. The statement concludes a control level processing block introduced with the AT statement.

1454

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

ENDCASE Concludes a CASE control structure.

Syntax

ENDCASE. This statement concludes a control structure introduced with the CASE statement.

ENDCATCH Concludes a CATCH area.

Syntax ENDCATCH. The statement concludes an exception handling area introduced with CATCH.

ENDCLASS Concludes a class definition.

Syntax ENDCLASS. This statement concludes a class declaration or implementation introduced with CLASS.

ENDDO Concludes a DO loop.

Syntax

ENDDO. This statement concludes a loop introduced with DO.

ENDEXEC Concludes a Native SQL statement.

Syntax

ENDEXEC. This statement concludes a Native SQL statement introduced with EXEC SQL.

ENDFORM Concludes a subroutine.

December 1999

1455


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

ENDFORM. This statement concludes a subroutine definition introduced with FORM.

ENDFUNCTION Concludes a function module.

Syntax

ENDFUNCTION. This statement concludes a function module introduced with FUNCTION.

ENDIF Concludes an IF control structure.

Syntax

ENDIF. This statement concludes a control structure introduced using IF.

ENDINTERFACE Concludes an interface definition.

Syntax

ENDINTERFACE. This statement concludes an interface definition introduced with INTERFACE.

ENDLOOP Concludes a loop.

Syntax

ENDLOOP. This statement concludes a loop introduced with LOOP.

ENDMETHOD Concludes a method.

Syntax

ENDMETHOD. This statement concludes a method implementation introduced with METHOD.

1456

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

ENDMODULE Concludes a dialog module.

Syntax

ENDMODULE. This statement concludes a dialog module introduced with MODULE.

ENDON Concludes a conditional statement block.

Syntax

ENDON. This statement concludes a conditional statement block introduced with ON CHANGE.

ENDPROVIDE Concludes a PROVIDE loop.

Syntax

ENDPROVIDE. This statement concludes a loop introduced with PROVIDE.

ENDSELECT Concludes a SELECT loop.

Syntax

ENDSELECT. This statement concludes a loop introduced with SELECT.

ENDWHILE Concludes a WHILE loop.

Syntax

ENDWHILE. This statement concludes a loop introduced with WHILE.

EVENTS Defines events in classes or interfaces.

December 1999

1457


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax EVENTS <evt> EXPORTING.. VALUE(<ei>) TYPE type [OPTIONAL]... The event <evt> can be declared in the declaration part of a class or within an interface definition, and may have EXPORTING parameters that are passed to the event handler. The parameters are always passed by value.

EXEC SQL Introduces a Native SQL statement.

Syntax

EXEC SQL [PERFORMING <form>]. Between EXEC SQL and the ENDEXEC statement, you can include a database-specific Native SQL statement. The PERFORMING addition allows you to pass a multiple-line selection line by line to a subroutine.

EXIT Terminates a loop or processing block.

Syntax

EXIT. Within a loop: The entire loop is terminated, and processing continues with the first statement following the loop. Outside a loop: Terminates the current processing block. In a reporting event: Jumps directly to the output list.

EXIT FROM STEP-LOOP Ends a step loop.

Syntax

EXIT FROM STEP-LOOP. Terminates step loop processing. A step loop is a way of displaying a table on a screen.

EXIT FROM SQL Terminates Native SQL processing.

Syntax

EXIT FROM SQL. This statement may occur within a subroutine called using the PERFORMING addition in the EXEC SQL statement. The entire subroutine is processed, but no more subsequent lines of the selection are processed.

1458

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

EXPORT Exports a data cluster.

Syntax EXPORT... <fi> [FROM <gi>]... | (<itab>) TO MEMORY | DATABASE <dbtab>(<ar>) ID(<key>) | SHARED BUFFER <dbtab>(<ar>) ID(<key>). The data objects <fi> or <gi>, or the data objects in the internal table <itab> are stored as a data cluster in the cross-program ABAP memory of the current internal session, in a cluster database table <dbtab>, or in the cross-transaction application buffer of the table <dbtab>.

EXTRACT Creates an extract dataset and adds lines to it.

Syntax

EXTRACT <fg>. The first EXTRACT statement in a program creates an extract dataset and adds the first entry to it. Each subsequent EXTRACT statement adds a new entry. Each extract entry contains the fields of the field group <fg> and, at the beginning, the fields of the field group HEADER as a sort key.

F FETCH Uses a cursor to read entries from a database table.

Syntax

FETCH NEXT CURSOR <c> INTO <target>. If the cursor <c> is linked with a selection in a database table, FETCH writes the next line of the selection into the flat target area <target>.

FIELD-GROUPS Declares a field group for an extract dataset.

Syntax

FIELD-GROUPS <fg>. Declares the field group <fg>. Field groups define the line structure of an extract dataset. You can define a special field group called HEADER as the sort key. When you fill the extract dataset, the HEADER field group precedes each entry.

December 1999

1459


BC - ABAP Programming

SAP AG

ABAP Statement Overview

FIELD-SYMBOLS Declares a field symbol.

Syntax FIELD-SYMBOLS <FS> [<type>|STRUCTURE <s> DEFAULT <wa>]. Field symbols are placeholders or symbolic names for fields. The pointed brackets in the name of a field symbol are part of its syntax. The <type> addition allows you to specify a type. The STRUCTURE addition imposes a structure on the data object assigned to the field symbol.

FORM Defines a subroutine.

Syntax FORM <subr> [USING ... [VALUE(]<pi>[)] [TYPE <t>|LIKE <f>]... ] [CHANGING... [VALUE(]<pi>[)] [TYPE <t>|LIKE <f>]... ]. Introduces a subroutine <form>. The USING and CHANGING additions define the parameter interface. The subroutine definition is concluded with the ENDFORM statement.

FORMAT Sets formatting options for list output.

Syntax FORMAT... <optioni> [ON|OFF]... The formatting options <optioni> (color, for example) apply to all subsequent list output until they are disabled with the OFF option.

FREE Releases memory space.

Syntax

FREE <itab>. FREE MEMORY ID(<key>). FREE OBJECT <obj>. This statement deletes an internal table, a data cluster in ABAP memory, or an external object in OLE2 Automation, depending on the form of the statement used. It also releases the memory occupied by the object.

1460

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

FUNCTION Defines a function module.

Syntax

FUNCTION <func>. Introduces the function module <func>. This statement does not have to be entered in the ABAP Editor, but is automatically generated by the Function Builder in the ABAP Workbench. The function module definition is concluded with the ENDFUNCTION statement.

FUNCTION-POOL Introduces a function group.

Syntax

FUNCTION-POOL. The first statement in a function group. This statement does not have to be entered by hand, but is generated automatically by the Function Builder in the ABAP Workbench. A function group is an ABAP program that contains function modules.

G GET Event keyword that defines event blocks for reporting events.

Syntax GET <node> [FIELDS <f1> <f2>...]. Only occurs in executable programs. When the logical database has passed a line of the node <node> to the program, the runtime environment triggers the GET event, and the corresponding event block is executed. The FIELDS addition allows you to specify explicitly the columns of the node that the logical database should retrieve.

GET BIT Reads an individual bit.

Syntax

GET BIT <n> OF <f> INTO <g>. Reads the bit at position <n> of the hexadecimal field <f> into the field <b>.

GET CURSOR Determines the cursor position on a screen or in an interactive list event.

December 1999

1461


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax GET CURSOR FIELD <f> [OFFSET <off>] [LINE <lin>] [VALUE <val>] [LENGTH <len>]. GET CURSOR LINE <lin> [OFFSET <off>] [VALUE <val>] [LENGTH <len>]. At a user action on a list or screen, the statement writes the position, value, and displayed length of a field or line into the corresponding variables.

GET LOCALE LANGUAGE Finds out the current text environment.

Syntax

GET LOCALE LANGUAGE <lg> COUNTY <c> MODIFIER <m>. Returns the current language, country ID and any modifier into the corresponding variables.

GET PARAMETER Finds out the value of a SPA/GPA parameter.

Syntax

GET PARAMETER ID <pid> FIELD <f>. Places the value of the SPA/GPA parameter <pid> from the user-specific SAP memory into the variable <f>.

GET PF-STATUS Finds out the current GUI status.

Syntax

GET PF-STATUS <f> [PROGRAM <prog>] [EXCLUDING <itab>]. Returns the name of the current GUI status (the same as SY-PFKEY) into the variable <f>. The PROGRAM addition writes the name of the ABAP program to which the status belongs into the variable <prog>. The EXCLUDING addition returns a list of all currently inactive function codes into the internal table <itab>.

GET PROPERTY Finds out a property of an OLE2 Automation object.

1462

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax

GET PROPERTY OF <obj> <p> = <f>. Returns the property <p> of an external OLE2 Automation object to the variable <f>.

GET RUN TIME FIELD Measures the runtime in microseconds.

Syntax

GET RUN TIME FIELD <f>. The first time the statement is executed, the variable <f> is set to zero. In each further call, the runtime since the first call is written to <f>.

GET TIME Synchronizes the time.

Syntax

GET TIME [FIELD <f>]. Refreshes the system fields SY-UZEIT, SY-DATUM, SY-TIMLO, SY-DATLO, and SY-ZONLO. If you use the FIELD addition, the variable <f> is filled with the current time.

GET TIME STAMP FIELD Returns a time stamp.

Syntax

GET TIME STAMP FIELD <f>. Returns the short or long form of the current date and time, depending on whether the variable <f> has the type P(8) or P(11). The long form returns the time correct to seven decimal places.

H HIDE Stores information about list lines.

Syntax

HIDE <f>. During list creation, this statement stores the contents of the field <f> and the current line number in the internal HIDE area. When the cursor is positioned on a line in an interactive list event, the stored value is returned to the field <f>.

December 1999

1463


BC - ABAP Programming

SAP AG

ABAP Statement Overview

I IF Conditional branching. Introduces a new branch.

Syntax

IF <logexp>. Opens an IF control structure that must be concluded with ENDIF. The system evaluates the logical expression <logexp>, and processes different statement blocks depending on the result.

IMPORT Imports a data cluster.

Syntax IMPORT... <fi> [TO <gi>]... | (<itab>) FROM MEMORY | DATABASE <dbtab>(<ar>) ID(<key>) | SHARED BUFFER <dbtab>(<ar>) ID(<key>). The data objects <fi> or the objects listed in the table <itab> are written from data clusters in the cross-program ABAP memory of the current internal session, a cluster database table <dbtab>, or the cross-transaction application buffer of the table <dbtab> into the variables <fi> or <gi>.

IMPORT DIRECTORY Creates the directory of a data cluster from a cluster database.

Syntax IMPORT DIRECTORY INTO <itab> FROM DATABASE <dbtab>(<ar>) Id <key>. The statement creates a directory of the data objects in a data cluster of the cluster database <dbtab> and writes it to the internal table <itab>. In the third variant, the table <itab> contains a directory of the objects stored using EXPORT TO DATABASE.

INCLUDE Inserts an include program in another program.

Syntax

INCLUDE <incl>. This has the same effect as inserting the source code of the include program <incl> at the same position in the program as the INCLUDE statement. Includes are not loaded dynamically at

1464

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

runtime, but are automatically expanded when the program is loaded. An include must have the program type I.

INCLUDE STRUCTURE Includes a structure within another.

Syntax

INCLUDE STRUCTURE <s>|TYPE <t>. Adopts the structure of an ABAP Dictionary structure <s> or a structured data type <t> as part of a new structure declared using DATA BEGIN OF …

INITIALIZATION Event keyword that defines an event block for a reporting event.

Syntax

INITIALIZATION. Only occurs in executable programs. The ABAP runtime environment triggers the INITIALIZATION event before the selection screen is processed, at which point the corresponding event block is processed.

INSERT for Database Tables Inserts lines into a database table.

Syntax INSERT <dbtab> FROM <wa>. INSERT <dbtab> FROM TABLE <itab> [ACCEPTING DUPLICATE KEYS]. Inserts one line from the work area <wa> or several lines from the internal table <itab> into the database table <dbtab>. The addition ACCEPTING DUPLICATE KEYS prevents a runtime error from occurring if two entries have the same primary key. Instead, it merely discards the duplicate.

INSERT for Field Groups Defines the structure of field groups for extract datasets.

Syntax INSERT <f1>... <f n> INTO <fg>. Includes the fields <fi> in the field group <fg>, thus defining a line structure for an extract dataset.

INSERT for any Internal Table Inserts lines in an internal table of any type.

December 1999

1465


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax INSERT <line>|LINES OF <jtab> [FROM <n1>] [TO <n2>] INTO TABLE <itab>. Inserts a line <line> or a set of lines from the internal table <jtab> into the internal table <itab>. If <jtab> is an index table, you can use the FROM and TO additions to restrict the lines inserted.

INSERT for Index Tables Inserts lines in index tables.

Syntax INSERT <line>|LINES OF <jtab> [FROM <n1>] [TO <n2>] INTO <itab> [INDEX <idx>]. Inserts a line <line> or a set of lines from an internal table <jtab> into the internal table <itab> before the line with the index <idx>. If <jtab> is an index table, you can restrict the lines to be inserted using the FROM and TO additions. If you omit the INDEX addition, you can only use the statement within a LOOP construction. In this case, the new line is inserted before the current line.

INSERT for Programs Inserts ABAP programs into the program library.

Syntax INSERT REPORT <prog> FROM <itab>. The lines of the internal table <itab> are added to the program library as the program <prog>.

INTERFACE Defines an interface in ABAP Objects.

Syntax

INTERFACE <ifac> [DEFERRED] [LOAD]. Introduces the definition of the interface <interface>. The definition concludes with ENDINTERFACE, and contains the declaration of all of the components in the interface. You can use the DEFERRED addition to declare the interface before you actually define it. The LOAD addition loads the interface definition explicitly from the class library.

INTERFACES Implements interfaces in a class.

Syntax

INTERFACES <ifac>.

1466

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Used in a class declaration: This statement adds the components of the interface to the existing class definition. Used in an interface definition: Forms a compound interface.

L LEAVE for Screens Leaves a screen.

Syntax

LEAVE SCREEN. Terminates the current screen and calls the next screen. The next screen can either be defined statically in the screen attributes or set dynamically using the SET SCREEN statement.

Syntax

LEAVE TO SCREEN <scr>. Terminates the current screen and calls the dynamically-defined next screen <scr>.

LEAVE for Lists During Screen Processing Switches between screen and list processing.

Syntax

LEAVE TO LIST-PROCESSING [AND RETURN TO SCREEN <scr>]. This statement allows you to create and display a list while processing a series of screens. The addition allows you to specify the next screen (to which you return after the list has been displayed). If you do not use the addition, screen processing resumes with the PBO of the current screen.

Syntax

LEAVE LIST-PROCESSING. Allows you to switch back explicitly from list processing to screen processing.

LEAVE for Programs Terminates an ABAP program.

Syntax

LEAVE [PROGRAM]. Terminates the current program and returns to the point from which it was called.

Syntax

LEAVE TO TRANSACTION <tcod> [AND SKIP FIRST SCREEN].

December 1999

1467


BC - ABAP Programming

SAP AG

ABAP Statement Overview Terminates the current program and starts a new transaction <tcod>. The addition allows you to skip the initial screen of the transaction.

LOCAL Protects global data against changes.

Syntax

LOCAL <f>. Only occurs in subroutines. When the subroutine starts, the value of <f> is stored temporarily, and restored to the variable <f> at the end of the subroutine.

LOOP Through Extracts Starts a loop through an extract dataset.

Syntax

LOOP. Loops through an extract dataset. The loop is concluded with ENDLOOP. When the LOOP statement is executed, the system finishes creating the extract dataset, and loops through all of its entries. One entry is read in each loop pass. The values of the extracted data are placed in the output fields of the field group within the loop.

LOOP Through Internal Tables Starts a loop through an internal table.

Syntax LOOP AT <itab> INTO <wa> WHERE <logexp>. LOOP AT <itab> ASSIGNING <FS> WHERE <logexp>. LOOP AT <itab> TRANSPORTING NO FIELDS WHERE <logexp>. Loops through an internal table. The loop is concluded with ENDLOOP. If the logical expression <logexp> is true, the current line contents are either placed in the work area <wa>, assigned to the field symbol <FS>, or not assigned at all. The first operand in each part of <logexp> must be a component of the internal table. The pointed brackets in the field symbol name are part of its syntax. With index tables, you can use the additions FROM <n> and TO <n> to restrict the lines that are read by specifying an index range.

LOOP Through Screen Fields Starts a loop through the special table SCREEN.

1468

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax

LOOP AT SCREEN... Similar to a loop through an internal table. The system table SCREEN contains the names and attributes of all of the fields on the current screen.

M MESSAGE Outputs a message.

Syntax

MESSAGE <xnnn> [WITH <f1>... <f4>] [RAISING <except>]. MESSAGE ID <mid> TYPE <x> NUMBER <nnn>. MESSAGE <xnnn>(<mid>). Outputs the message <nnn> of message class <mid> as message type <x>. The message type determines how the message is displayed, and how the program reacts. The WITH addition allows you to fill placeholders in the message text. The RAISING addition in function modules and methods allows you to terminate the procedure and trigger the exception <exception>.

METHOD Introduces the implementation of a method in a class.

Syntax

METHOD <meth>. Only occurs in the implementation part of classes. This statement begins a statement block that must be concluded with ENDMETHOD. You do not have to specify any interface parameters, since these are defined in the method declaration.

METHODS Declares methods in classes and interfaces.

Syntax METHODS <meth> IMPORTING... [VALUE(]<ii>[)] TYPE <t> [OPTIONAL]... EXPORTING... [VALUE(]<ei>[)] TYPE <t> [OPTIONAL]... CHANGING ... [VALUE(]<ci>[)] TYPE <t> [OPTIONAL]... RETURNING VALUE(<r>) EXCEPTIONS ... <ei>... Declares a method <meth> in the declaration part of a class or in an interface definition. The additions define the parameter interface and exceptions of the method. The function of the method must be implemented using the METHOD statement.

December 1999

1469


BC - ABAP Programming

SAP AG

ABAP Statement Overview

MODIFY for Database Tables Inserts or changes lines in database tables.

Syntax MODIFY <dbtab> FROM <wa>. MODIFY <dbtab> FROM TABLE <itab>. Works like INSERT for database tables if there is not yet a line in the table with the same primary key. Works like UPDATE if a line already exists with the same primary key.

MODIFY for All Internal Tables Changes the contents of lines in any type of internal table.

Syntax MODIFY TABLE <itab> FROM <wa> [TRANSPORTING <f1> <f 2>...]. Copies the work area <wa> into the line of the internal table with the same table key as <wa>. You can use the TRANSPORTING addition to specify the exact components that you want to change. MODIFY <itab> FROM <wa> TRANSPORTING <f1> <f 2>... WHERE <logexp>. Copies the work area <wa> into the lines of the internal table for which the logical expression is true. The first operand in each comparison of the logical expression must be a component of the line structure.

MODIFY for Index Tables Changes the contents of lines in index tables.

Syntax MODIFY <itab> FROM <wa> [INDEX <idx>] [TRANSPORTING <f1> <f2>...]. Copies the work area <wa> into the line of the internal table with index <idx>. If you omit the INDEX addition, you can only use the statement within a LOOP. This changes the current line.

MODIFY for Lists Changes a line of a list.

Syntax MODIFY LINE <n> [INDEX <idx>] [OF CURRENT PAGE|OF PAGE <p>] |CURRENT LINE LINE FORMAT <option1> <option2>... FIELD VALUE <f1> [FROM <g1>] <f2> [FROM <g2>]... FIELD FORMAT <f1> <options1> <f2> <options2>

1470

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Changes either line <n> on the current or specified list (or page), or the last line to be chosen. The exact nature of the change is specified in the additions.

MODIFY SCREEN Changes the table SCREEN.

Syntax

MODIFY SCREEN... Like changing an internal table. This statement allows you to change the attributes of fields on the current screen.

MODULE Introduces a dialog module.

Syntax

MODULE <mod> OUTPUT |[INPUT]. Introduces the dialog module <mod>. The OUTPUT and INPUT additions designate the module as a PBO or PAI module respectively. Each module must conclude with the ENDMODULE statement.

MOVE Assigns values.

Syntax

MOVE <f1> TO <f2>. Assigns the contents of the data object <f1> to the variable <f2>, with automatic type conversion if necessary. Equivalent to <f2> = <f1>.

MOVE-CORRESPONDING Assigns values between identically-named components of structures.

Syntax

MOVE-CORRESPONDING <struc1> TO <struc2>. The contents of the components of the structure <struc1> are assigned to the identically-named components of the structure <struc2>.

MULTIPLY Multiplies two individual fields.

December 1999

1471


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

MULTIPLY <n> BY <m>. The contents of <n> are multiplied by the contents of <m>, and the result is placed in <m>. Equivalent is M = m * n.

MULTIPLY-CORRESPONDING Multiplies components of structures.

Syntax

MULTIPLY-CORRESPONDING <struc1> BY <struc2>. Multiplies all of the identically-named components of <struc1> and <struc2> and places the results in the components in <struc1>.

N NEW-LINE Inserts a line break in a list.

Syntax

NEW-LINE [NO-SCROLLING|SCROLLING]. Positions the list output on a new line. The NO-SCROLLING addition locks the line against horizontal scrolling. To lift the lock, use the SCROLLING addition.

NEW-PAGE Inserts a page break in a list.

Syntax

NEW-PAGE [NO-TITLE|WITH-TITLE] [NO-HEADING|WITH-HEADING] [LINE-COUNT] [LINE-SIZE] [PRINT ON|OFF]. Generates a new page and positions the list output after the page header. The additions control how the page header is displayed, the length and width of the page, and the print output.

NODES Declares an interface work area.

Syntax

NODES <node>.

1472

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Declares a variable with the same data type and the same name as a data type from the ABAP Dictionary. Structures in main programs and subroutines declared with nodes use a common data area. This statement is used in conjunction with logical databases.

O ON CHANGE Introduces a branch.

Syntax

ON CHANGE OF <f> [OR <f1> OR <f2>...]. Opens an ON control structure, concluded with ENDON. The statement block is executed whenever the contents of the field <f> or one of the other fields <fi> has changed since the statement was last executed.

OPEN CURSOR Opens a database cursor.

Syntax OPEN CURSOR [WITH HOLD] <c> FOR SELECT FROM <source> [WHERE <condition>] [GROUP BY <fields>] [HAVING <cond>] [ORDER BY <fields>].

<result>

Opens a cursor <c> with type CURSOR for a SELECT statement. All of the clauses of the SELECT statement apart from the INTO clause can be used. The INTO clause is set in the FETCH statement. If you use the WITH HOLD addition, the cursor is not closed when a database commit occurs.

OPEN DATASET Opens a file.

Syntax

OPEN DATASET <dsn> [FOR INPUT|OUTPUT|APPENDING] [IN BINARY|TEXT MODE] [AT POSITION <pos>] [MESSAGE <mess>] [FILTER <filt>]. Opens a file <dsn> on the application server. The additions determine whether the file is for reading or writing, whether the contents are to be interpreted in binary or character form, the position in the file, the location to which an operating system can be written, and allow you to execute an operating system command.

December 1999

1473


BC - ABAP Programming

SAP AG

ABAP Statement Overview

OVERLAY Overlays a character string with another.

Syntax

OVERLAY <c1> WITH <c2> [ONLY <str>]. All of the characters in field <c1> that occur in <str> are overlaid with the contents of <c2>. <c2> remains unchanged. If you omit the ONLY <str> addition, all positions in <c1> containing spaces are overwritten.

P PACK Converts type C variables into type P.

Syntax

PACK <f> TO <g>. Packs the string <f> and places it in the field <g>. This can be reversed with the UNPACK statement.

PARAMETERS Declares parameters for a selection screen.

Syntax

PARAMETERS <p>[(<length>)] [TYPE <type>|LIKE <obj>] [DECIMALS <d>] [DEFAULT <f>] [MEMORY ID <pid>] [LOWER CASE] [OBLIGATORY] [VALUE CHECK] [AS CHECKBOX] [RADIOBUTTON GROUP <radi>] [NO-DISPLAY] [MODIF ID <key>]. Declares a variable <p>, as in the DATA statement. However, the PARAMETERS statement also creates an input field for <p> on the relevant selection screen. You can use the additions to define default values, accept lowercase input, define the field as required, check values, define a checkbox or radio button, prevent the field from being displayed on the selection screen, or modify the field.

PERFORM Calls a subroutine.

1474

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax PERFORM <subr> | <subr>(<prog>) [IF FOUND] |(<fsubr>)[IN PROGRAM (<fprog>)][IF FOUND] [USING ... <pi>... ] [CHANGING... <pi>... ] [ON COMMIT]. Calls an internal or external subroutine <subr> or the subroutine whose name occurs in the <fsubr> field. The external program is <prog> or the name contained in <fprog>. The IF FOUND addition prevents a runtime error from occurring if the subroutine does not exist. You must use the USING and CHANGING additions to supply values to the interface parameters of the subroutine. The ON COMMIT addition delays the execution of the subroutine until the next COMMIT WORK statement.

POSITION Absolute positioning of the output on a list.

Syntax

POSITION <col>. Positions the list output in column <col>.

PRINT-CONTROL for Print Format Specifies the print format.

Syntax PRINT-CONTROL <formats> [LINE <lin>] [POSITION <col>]. Sets the print format starting either at the current list position or at line <lin> and column <col>.

PRINT-CONTROL for Index Lines Creates index lines in the spool file.

Syntax

PRINT-CONTROL INDEX-LINE <f>. Writes the contents of the field <f> into an index line at the end of the current print line. The index line is not printed. In optical archiving, the spool system separates the lists into a data file and a description file containing the index lines.

PRIVATE Defines the private section of a class.

December 1999

1475


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax

PRIVATE SECTION. Introduces the declaration of all of the components of a class that are only visible in the class itself.

PROGRAM Introduces a program.

Syntax

PROGRAM <prog>... The first statement in some ABAP programs. Equivalent of REPORT.

PROTECTED Defines the protected section of a class.

Syntax

PROTECTED SECTION. Introduces the declaration of all of the components of a class that are only visible in the class and its subclasses.

PROVIDE Loops through internal tables at given intervals.

Syntax

PROVIDE <f1>... <fn> <g1>... <gm> ... ... BETWEEN

FROM <itab1> FROM <itab2> FROM <itabn> <f> AND <g>.

The contents of the specified fields of the internal tables <itab1> … <itabn> are placed in their header lines. Then, the processing block between PROVIDE and ENDPROVIDE is executed for each interval.

PUBLIC Defines the public section of a class.

Syntax

PUBLIC SECTION. Introduces the declaration of all components of a class that are visible in the class, its subclasses, and for all users.

1476

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

PUT Triggers a GET event.

Syntax

PUT <node>. Only occurs in logical databases. Branches the program flow according to the structure of the logical database.

R RAISE for Exceptions Triggers an exception.

Syntax

RAISE <except>. Only occurs in function modules and methods. Terminates the procedure and triggers the exception <except>.

RAISE for Events Triggers an event in ABAP Objects.

Syntax

RAISE EVENT <evt>. Only occurs in methods. The event <evt> is triggered, and this calls all of the handler methods registered for it.

RANGES Declares a RANGES table.

Syntax

RANGES <rangetab> FOR <f>. Declares a RANGES table for the field <f>. RANGES tables have the same data type as a selection table, but they do not have input fields on a selection screen.

READ for Files Reads a file.

Syntax READ DATASET <dsn> INTO <f> [LENGTH <len>].

December 1999

1477


BC - ABAP Programming

SAP AG

ABAP Statement Overview Reads the contents of the file <dsn> on the application server to the variable <f>. The number of bytes transferred can be written to <len>.

READ for any Internal Table Reads a line from any internal table.

Syntax READ TABLE <itab> FROM <wa> |WITH TABLE KEY <k1> = <f1>... <kn> = <fn> |WITH KEY = <f> |WITH KEY <k1> = <f1>... <kn> = <fn> INTO <wa> [COMPARING <f1> <f2>... |ALL FIELDS] [TRANSPORTING <f1> <f2>... |ALL FIELDS|NO FIELDS] |ASSIGNING <FS>. This statement reads either the line of the internal table with the same key as specified in the work area <wa>, the line with the key specified in the TABLE KEY addition, the line that corresponds fully to <f>, or the one corresponding to the freely-defined key in the KEY addition. The contents of the line are either written to the work area <wa>, or the line is assigned to the field symbol <FS>. If you assign the line to a work area, you can compare field contents and specify the fields that you want to transport.

READ for Index Tables Reads a line of an index table.

Syntax READ TABLE <itab> INDEX <idx> INTO <wa>... | ASSIGNING <FS>. Reads the line with the index <idx>. The result is available as described above.

READ for Lists Reads the contents of a line from a list.

Syntax READ LINE <n> [INDEX <idx>] [OF CURRENT PAGE|OF PAGE <p>] |CURRENT LINE [FIELD VALUE <f1> [INTO <g1>]... <fn> [INTO <gn>]]. Reads either the line <n> on the current or specified list or page, or the last line to have been selected by the user. The addition specifies the fields that you want to read, and the target fields into which they should be placed. The entire line is always placed in the system field SY-LISEL, and the HIDE area is filled for the line.

READ for Programs Reads ABAP programs from the program library.

1478

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax READ REPORT <prog> INTO <itab>. Copies the lines of the program <prog> into the internal table <itab>.

RECEIVE Receives results from an asynchronous function module call.

Syntax

RECEIVE RESULTS FROM FUNCTION <func> [KEEPING [IMPORTING ... fi = ai... [TABLES ... fi = ai... [EXCEPTIONS... ei = ri...

TASK] ] ] ]

Occurs in special subroutines to receive IMPORTING and TABLES parameters from function modules called using the STARTING NEW TASK addition.

REFRESH Initializes an internal table.

Syntax

REFRESH <itab>. Resets the internal table <itab> to its initial value, that is, deletes all of its lines.

REFRESH CONTROL Initializes a control.

Syntax

REFRESH CONTROL <ctrl> FROM SCREEN <scr>. The control <ctrl> defined in the CONTROLS statement is reset with the initial values specified for screen <scr>.

REJECT Terminates a GET processing block.

Syntax

REJECT [<dbtab>]. Stops processing the current line of the node of the logical database. If you specify <dbtab>, the logical database reads the next line of the node <dbtab>, otherwise the next line of the current node.

December 1999

1479


BC - ABAP Programming

SAP AG

ABAP Statement Overview

REPLACE Replaces strings in fields with another string.

Syntax

REPLACE <str1> WITH <str2> INTO <c> [LENGTH <l>]. This statement searches the first occurrence of the first <l> characters of the search pattern <str1> in field <c> and replaces them with the string <str2>.

REPORT Introduces a program.

Syntax

REPORT <rep> [MESSAGE-ID <mid>] [NO STANDARD PAGE HEADING] [LINE-SIZE <col>] [LINE-COUNT <n>(<m>)] [DEFINING DATABASE <ldb>]. This is the first statement within certain ABAP programs. <rep> can be any name you choose. The addition MESSAGE-ID specifies a message class to be used in the program. The DEFINING DATABASE addition defines the program as the database program of the logical database <ldb>. The other options are formatting specifications for the default list of the program.

RESERVE Conditional page break in a list.

Syntax

RESERVE <n> LINES. Executes a page break on the current page if less than <n> lines are free between the current line and the page footer.

ROLLBACK Undoes the changes in a SAP LUW.

Syntax

ROLLBACK WORK. Undoes all changes within a database LUW to the beginning of the LUW. The registered update modules are not executed, and the record entry is deleted from table VBLOG.

1480

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

S SCROLL Scrolls in a list.

Syntax SCROLL LIST FORWARD|BACKWARD [INDEX <idx>]. SCROLL LIST TO FIRST PAGE|LAST PAGE|PAGE <pag> [INDEX <idx>] [LINE <lin>]. SCROLL LIST LEFT|RIGHT [BY <n> PLACES] [INDEX <idx>]. SCROLL LIST TO COLUMN <col> [INDEX <idx>]. Positions the current list or the list level <idx> in accordance with the additions specified. You can scroll by window, page, columns, or to the left- or right-hand edge of the list.

SEARCH Searches for a string.

Syntax

SEARCH <f>|<itab> FOR <g> [ABBREVIATED] [STARTING AT <n1>] [ENDING AT <n2>] [AND MARK]. Searches the field <f> or the table <itab> for the string in field <g>. The result is placed in the system field SY-FDPOS. The additions allow you to hide intermediate characters, search from and to a particular position, and convert the found string into uppercase.

SELECT Reads data from the database.

Syntax SELECT <result> INTO <target> FROM <source> [WHERE <condition>] [GROUP BY <fields>] [HAVING <cond>] [ORDER BY <fields>]. The SELECT statement consists of a series of clauses, each of which fulfils a certain task:

SELECT clause Defines the structure of the selection.

December 1999

1481


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax SELECT [SINGLE]|[DISTINCT] * | <si> [AS <ai>]... <agg>( [DISTINCT] <sj>) [AS <aj>]... The selection can be a single line SINGLE or a series of lines. You can eliminate duplicate lines using the DISTINCT addition. To select the entire line, use *, otherwise, you can specify individual columns <si>. For individual columns, you can use aggregate functions <agg>, and assign alternative column names <ai>.

INTO clause Defines the target area into which the selection from the SELECT clause is to be placed.

Syntax ... INTO [CORRESPONDING FIELDS OF] <wa> | INTO|APPENDING [CORRESPONDING FIELDS OF] TABLE <itab> [PACKAGE SIZE <n>] | INTO (<f1>, <f2>,...) The target area can be a flat work area <wa>, an internal table <itab>, or a list of fields <fi>. If you use the CORRESPONDING FIELDS addition, data is only selected if there is an identicallynamed field in the target area. If you use APPENDING instead of INTO, the data is appended to an internal table instead of overwriting the existing contents. PACKAGE SIZE allows you to overwrite or extend the internal table in a series of packages. The data type of the target area must be appropriate for the selection in the SELECT clause.

FROM clause Specifies the database tables from which the data in the selection in the SELECT clause is to be read.

Syntax ... FROM [<tab> [INNER]|LEFT [OUTER] JOIN] <dbtab> [AS <alias>] [ON <cond>] [CLIENT SPECIFIED] [BYPASSING BUFFER] [UP TO <n> ROWS] You can read a single table <dbtab> or more than one table, using inner and outer joins to link tables with conditions <cond>, where <tab> is a single table or itself a join condition. You can specify individual database tables either statically or dynamically, and you can replace their names with an alternative <alias>. You can bypass automatic client handling with the CLIENT SPECIFIED addition, and SAP buffering with BYPASSING BUFFER. You can also restrict the number of lines read from the table using the UP TO <n> ROWS addition.

WHERE clause Restricts the number of lines selected.

Syntax ... [FOR ALL ENTRIES IN <itab>] WHERE <cond> The condition <cond> may contain one or more comparisons, tests for belonging to intervals, value list checks, subqueries, selection table queries or null value checks, all linked with AND, OR, and NOT. If you use the FOR ALL ENTRIES addition, the condition <cond> is checked for each line of the internal table <itab> as long as <cond> contains a field of the internal table as an

1482

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

operand. For each line of the internal table, the lines from the database table meeting the condition are selected. The result set is the union of the individual selections resulting from each line.

GROUP BY clause Groups lines in the selection

Syntax ... GROUP BY <s1> <s2> Groups lines with the same contents in the specified columns. Uses aggregate functions for all other columns in each group. All columns listed in the SELECT clause that do not appear in the GROUP BY addition must be specified in aggregate expressions.

HAVING clause Restricts the number of line groups.

Syntax ... HAVING <cond> Like the WHERE clause, but can only be used in conjunction with a GROUP BY clause. Applies conditions to aggregate expressions to reduce the number of groups selected.

ORDER BY clause Sorts the lines in the selection.

Syntax ... ORDER BY PRIMARY KEY |... <si> [ASCENDING|DESCENDING]... Sorts the selection in ascending or descending order according to the primary key or the contents of the fields listed.

SELECT-OPTIONS Declares selection criteria for a selection screen.

Syntax

SELECT-OPTIONS <sel> FOR <f> [DEFAULT <g> [to <h>] [OPTION <op>] SIGN <s>] [MEMORY ID <pid>] [LOWER CASE] [OBLIGATORY] [NO-DISPLAY] [MODIF ID <key>] [NO-EXTENSION] [NO INTERVALS] [NO DATABASE SELECTION]. Declares a selection table <sel> for the field <f>, and also places input fields on the corresponding selection screen. The additions allow you to set a default value, accept input in lowercase, define a required field, suppress or modify the display on the selection screen, restrict

December 1999

1483


BC - ABAP Programming

SAP AG

ABAP Statement Overview the selection table to a line or a selection to a single field, or prevent input from being passed to a logical database.

SELECTION-SCREEN for Selection Screen Formatting Formats a selection screen.

Syntax SELECTION-SCREEN SKIP [<n>]. SELECTION-SCREEN ULINE [[/]<pos(len)>] [MODIF ID <key>]. SELECTION-SCREEN COMMENT [/]<pos(len)> <comm> [FOR FIELD <f>] [MODIF ID <key>]. SELECTION-SCREEN BEGIN OF LINE. ... SELECTION-SCREEN END OF LINE. SELECTION-SCREEN BEGIN OF BLOCK <block> [WITH FRAME [TITLE <title>]] [NO INTERVALS]. ... SELECTION-SCREEN END OF BLOCK <block>. SELECTION-SCREEN FUNCTION KEY <i>. SELECTION SCREEN PUSHBUTTON [/]<pos(len)> <push> USER-COMMAND <ucom> [MODIF ID <key>]. Allows you to insert blank lines, lines and comments, group input fields together in lines and blocks, and create pushbuttons.

SELECTION-SCREEN for Defining Selection Screens Defines selection screens.

Syntax SELECTION-SCREEN BEGIN OF <numb> [TITLE <tit>] [AS WINDOW]. ... SELECTION-SCREEN END OF <numb>. Defines a selection screen with the screen number <numb>. All PARAMETERS, SELECTOPTIONS, and SELECTION-SCREEN statements within the SELECTION-SCREEN BEGIN OF … END OF block belong to the selection screen <numb>. The TITLE addition allows you to define a title for the selection screen. The AS WINDOW addition allows you to define the selection screen as a modal dialog box.

SELECTION-SCREEN for Selection Screen Versions Defines selection screen versions.

1484

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax SELECTION-SCREEN BEGIN OF VERSION <dynnr> ... SELECTION-SCREEN EXCLUDE <f>. ... SELECTION-SCREEN BEGIN OF VERSION <dynnr>. Only in logical databases. The statement hides fields that otherwise appear on the standard selection screen.

SELECTION-SCREEN for Logical Databases Provides special functions in conjunction with logical databases.

Syntax SELECTION-SCREEN DYNAMIC SELECTIONS | FIELD SELECTION FOR NODE|TABLE <node>. Can only be used in logical databases. Declares a node as accepting dynamic selections or field selections.

SET BIT Sets an individual bit.

Syntax SET BIT <n> OF <f> [TO <b>]. Sets t he bit at position <n> of hexadecimal field <f> to 1 or the value of the field <b>. <b> must be 0 or 1.

SET BLANK LINES Allows blank lines in lists.

Syntax SET BLANK LINES ON|OFF. Prevents blank lines created in WRITE statements from being suppressed in list output.

SET COUNTRY Sets the output format

Syntax SET COUNTRY <c>. Sets the output formats for numeric and date fields for the country with the ID <c>.

December 1999

1485


BC - ABAP Programming

SAP AG

ABAP Statement Overview

SET CURSOR Sets the cursor on the screen.

Syntax SET CURSOR FIELD <f> [OFFSET <off>] [LINE <lin>]. SET CURSOR LINE <lin> [OFFSET <off>]. SET CURSOR <col> <line>. Sets the cursor either to a particular position in a field, line, or column of a line.

SET EXTENDED CHECK Affects the extended program check.

Syntax SET EXTENDED CHECK ON|OFF. Switches the extended program check (SLIN) on or off, suppressing the corresponding messages.

SET HANDLER Registers event handlers in ABAP Objects.

Syntax SET HANDLER... <hi>... [FOR <ref>|FOR ALL INSTANCES]. If you do not use the FOR addition, the handler is set for all static events. Use the FOR addition to register handlers for instance events.

SET HOLD DATA Sets a screen attribute.

Syntax SET HOLD DATA ON|OFF. Sets the screen attribute “Hold data” from the program.

SET LANGUAGE Sets the display language.

Syntax SET LANGUAGE <lg>. All text symbols are refreshed with the contents of the text pool in language <lg>.

1486

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

SET LEFT SCROLL BOUNDARY Sets the left-hand boundary for horizontal scrolling.

Syntax SET LEFT SCROLL-BOUNDARY [COLUMN <col>]. Sets the current output position or the position <col> as the left-hand edge of the scrollable area on the current list page.

SET LOCALE LANGUAGE Sets the text environment.

Syntax SET LOCALE LANGUAGE <lg> [COUNTRY <c>] [MODIFIER <m>]. Sets the text environment for alphabetical sorting according to the language <lg>, country <c>, and any further modifier <m>.

SET MARGIN Sets the margin of a print page. SET MARGIN <x> [<y>]. Sends the current list page to the spool system with a margin of <x> columns from the left-hand edge and <y> rows from the top edge of the page.

SET PARAMETER Sets a SPA/GPA parameter.

Syntax

SET PARAMETER ID <pid> FIELD <f>. Copies the value of the field <f> into the SPA/GPA parameter <pid> in the user-specific SAP memory.

SET PF-STATUS Sets the GUI status.

Syntax SET PF-STATUS <stat> [EXCLUDING <f>|<itab>] [IMMEDIATELY] [OF PROGRAM <prog>]. Sets the GUI status <stat> for the subsequent screens. The EXCLUDING addition allows you to deactivate functions dynamically. The IMMEDIATELY addition sets the GUI status of the list

December 1999

1487


BC - ABAP Programming

SAP AG

ABAP Statement Overview currently displayed. The OF PROGRAM addition allows you to use a GUI status from another program.

SET PROPERTY Sets a property of an OLE2 Automation object.

Syntax

GET PROPERTY OF <obj> <p> = <f>. Sets the property <p> of an external OLE2 Automation object to <f>.

SET RUN TIME ANALYZER Controls the runtime analysis.

Syntax SET RUN TIME ANALYZER ON|OFF. The runtime analysis only measures the runtime of the statements in the block between SET RUN TIME ANALYZER ON and OFF.

SET RUN TIME CLOCK Sets the clock accuracy for runtime analysis.

Syntax SET RUN TIME CLOCK RESOLUTION HIGH|LOW. Sets the accuracy of the runtime to low accuracy with long measurement interval or high accuracy with shorter measurement interval.

SET SCREEN Sets the next screen.

Syntax SET SCREEN <scr>. Temporarily overwrites the statically-defined next screen with <scr>. <scr> is processed after the current screen.

SET TITLEBAR Sets the screen title.

Syntax SET TITLEBAR <t> [OF PROGRAM <prog>] [WITH <g1 >... <g9>].

1488

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Sets the title <t> for the subsequent screens. The OF PROGRAM addition allows you to use a title from another program. The WITH addition fills any placeholders in the title.

SET UPDATE TASK LOCAL Switches on local update.

Syntax SET UPDATE TASK LOCAL. Updates are processed in the current work process.

SET USER-COMMAND Triggers a list event.

Syntax SET USER-COMMAND <fc>. Triggers a list event with the function code <fc> and calls the corresponding event block.

SHIFT Shifts strings.

Syntax SHIFT <c> [BY <n> PLACES] [LEFT|RIGHT|CIRCULAR]. Shifts the field <c> by one or <n> places. The additions allow you to specify the direction, and how the empty spaces are dealt with.

SKIP for Blank Lines Creates blank lines on the output list.

Syntax

SKIP [<n>]. Creates <n> blank lines after the current line in a list. If you omit <n>, inserts one line.

SKIP for Positioning Absolute positioning for output on a list.

Syntax

SKIP TO LINE <lin>. Positions the list output in line <lin>.

December 1999

1489


BC - ABAP Programming

SAP AG

ABAP Statement Overview

SORT for Extracts Sorts an extract dataset.

Syntax SORT [ASCENDING|DESCENDING] [AS TEXT] [STABLE] ... BY <fi> [ASCENDING|DESCENDING] [AS TEXT]... Ends creation of the extract dataset in the program and sorts it. If you omit the BY addition, the extract is sorted by the key specified in the HEADER field group. The BY addition allows you to specify a different sort key. The other additions specify whether you want to sort in ascending or descending order, and whether strings should be sorted alphabetically.

SORT for Internal Tables Sorts internal tables.

Syntax SORT <itab> [ASCENDING|DESCENDING] [AS TEXT] [STABLE] ... BY <fi> [ASCENDING|DESCENDING] [AS TEXT]... Sorts the internal table <itab>. If you omit the BY addition, the table is sorted by its key. The BY addition allows you to specify a different sort key. The remaining additions allow you to specify whether you want to sort in ascending or descending order, and whether strings should be sorted alphabetically.

SPLIT Splits a character string.

Syntax

SPLIT <c> AT <del> INTO <c1>... <cn> INTO TABLE <itab>. Searches the field <c> for the character <del> and places the partial fields before and after <del> into the target fields <c1> … <cn>, or into a new line of the internal table <itab>.

START-OF-SELECTION Event keyword that defines an event block for a reporting event.

Syntax

START-OF-SELECTION. After the selection screen has been processed, the runtime environment triggers the START-OFSELECTION event and processes the corresponding event block.

1490

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

STATICS Defines static variables.

Syntax

STATICS <f>... Like DATA. Retains the value of a local variable beyond the runtime of the procedure in which it occurs.

STOP Exits a reporting event.

Syntax

STOP. Can only occur in event blocks for reporting events. Leaves the block and jumps to END-OFSELECTION.

SUBMIT Calls an executable program.

Syntax SUBMIT <rep> [AND RETURN] [VIA SELECTION-SCREEN] [USING SELECTION-SET <var>] [WITH <sel> <criterion>] [WITH FREE SELECTIONS <freesel>] [WITH SELECTION-TABLE <rspar>] [LINE-SIZE <width>] [LINE-COUNT <length>]. Calls the program <rep>. If you omit the AND RETURN addition, the current program is terminated, otherwise, the data from the current program is retained, and processing returns to the calling program when <rep> has finished running. The other additions control the selection screen and set attributes of the default list in the called program.

SUBTRACT for Single Fields Subtracts two single fields.

Syntax

SUBTRACT <n> FROM <m>. The contents of <n> are subtracted from the contents of <m> and the result placed in <m>. Equivalent of m = m - n.

December 1999

1491


BC - ABAP Programming

SAP AG

ABAP Statement Overview

SUBTRACT-CORRESPONDING Subtracts components of structures.

Syntax

SUBTRACT-CORRESPONDING <struc1> FROM <struc2>. Subtracts the contents of the components of <struc1> from identically-named components in <struc2> and places the results in the components of <struc2>.

SUM Calculates sums of groups.

Syntax SUM. Can only be used in loops through internal tables. Calculates the sums of the numeric fields in all lines of the current control level and writes the results to the corresponding fields in the work area.

SUPPLY Fills context instances with values.

Syntax SUPPLY <key1> = <f 1>... <key n> = <f n> TO CONTEXT <inst>. Fills the key fields <keyn> of the context instance <inst> with the values <fn>.

SUPPRESS DIALOG Prevents the current screen from being displayed.

Syntax

SUPPRESS DIALOG. Can only occur in a PBO dialog module. The screen is not displayed, but its flow logic is still processed.

T TABLES Declares an interface work area.

Syntax

TABLES <dbtab>.

1492

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Declares a structure with the same data type and name as a database table, a view, or a structure from the ABAP Dictionary. Structures declared using TABLES in main programs and subroutines use a common data area.

TOP-OF-PAGE Event keyword for defining an event block for a list event.

Syntax TOP-OF-PAGE [DURING LINE-SELECTION]. Whenever a new page begins while a standard list is being created, the runtime environment triggers the TOP-OF-PAGE event and the corresponding event block is executed. The addition DURING LINE-SELECTION has the same function, but for detail lists.

TRANSFER Writes data to a file.

Syntax TRANSFER <f> TO [LENGTH <len>]. Writes the field <f> to the file <dsn> on the application server. The LENGTH addition specifies the length <len> of the data you want to transfer.

TRANSLATE Converts characters in strings.

Syntax TRANSLATE <c> TO UPPER|LOWER CASE |USING <r>. The characters of the string <c> are converted into upper- or lowercase, or according to a substitution rule specified in <r>.

TYPE-POOL Introduces a type group.

Syntax

TYPE-POOL <tpool>. The first statement in a type group. You do not have to enter this statement in the ABAP Editor instead, it is automatically inserted in the type group by the ABAP Dictionary. A type group is an ABAP program containing type definitions and constant declarations that can then be used in several different programs.

December 1999

1493


BC - ABAP Programming

SAP AG

ABAP Statement Overview

TYPE-POOLS Declares the types and constants of a type group to a program.

Syntax

TYPE-POOLS <tpool>. After this statement, you can use all of the data types and constants defined in the type group <tpool> in your program.

TYPES for Simple Field Types Defines a simple field type.

Syntax TYPES <t>[(<length>)] [TYPE <type>|LIKE <obj>] [DECIMALS <dec>]. Defines the internal data type <t> in the program with length <len>, reference to the ABAP Dictionary type <type> or a data object <obj>, and, where appropriate, with <dec> decimal places.

Syntax TYPES <t> TYPE REF TO <class>|<interface>. Defines the internal data type <t> in the program with reference to the class <class> or the interface <interface>.

TYPES for Aggregate Types Defines aggregated types.

Syntax TYPES: BEGIN OF <structure>, ... <ti>..., ... END OF <structure>. Combines the data types <ti> to form the structure <structure>. You can address the individual components of a structure in a program using a hyphen between the structure name and the component name as follows: <structure>-<ti>.

Syntax TYPES <t> TYPE|LIKE <tabkind> OF <linetype> [WITH <key>]. Defines the local data type <t> in the program as an internal table with the access type <tabkind>, the line type <linetype>, and the key <key>.

1494

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

U ULINE Places a horizontal line on the output list.

Syntax ULINE [AT [/][<pos>][(<len>)]]. Without additions, generates a new line on the current list and fills it with a horizontal line. The additions allow you to insert a line break and specify the starting position and length of the line.

UNPACK Converts variables from type P to type C.

Syntax

UNPACK <f> TO <g>. Unpacks the packed field <f> and places it in the string <g> with leading zeros. The opposite of PACK.

UPDATE Modifies lines in database tables.

Syntax UPDATE <dbtab> SET <si> = <f> |<si> = <si> + <f> |<si> = <si> - <f> [WHERE <cond>]. Sets the value in <si> to <f>, increases it by <f>, or decreases it by <f> for all selected lines. The WHERE addition determines the lines that are updated. If you omit the WHERE addition, all lines are updated.

Syntax UPDATE <dbtab> FROM <wa>. UPDATE <dbtab> FROM TABLE <itab>. Overwrites the line with the same primary key as <wa> with the contents of <wa>, or all lines with the same primary key as a line in the internal table <itab> with the corresponding line of itab. The work area <wa> or the lines of the table <itab> must have at least the same length and the same alignment as the line structure of the database table.

W WHEN Introduces a statement block in a CASE control structure.

December 1999

1495


BC - ABAP Programming

SAP AG

ABAP Statement Overview Syntax WHEN <f1> [OR <f2> OR...] | OTHERS. The statement block after a WHEN statement is executed if the contents of the field <f> in the CASE statement are the same as those of one of the fields <f i>. Processing then resumes after the ENDCASE statement. The WHEN OTHERS statement block is executed if the contents of <f> do not correspond to any of the fields <fi>.

WHILE Introduces a loop.

Syntax WHILE <logexp> [VARY <f> FROM <f1> NEXT <f2>]. Introduces a statement block that is concluded with ENDWHILE. The statement block between WHILE and ENDWHILE is repeated for as long as the expression <logexp> is true, or until a termination statement such as CHECK or EXIT occurs. The VARY addition allows you to process fields that are a uniform distance apart within memory.

WINDOW Displays a list as a modal dialog box.

Syntax

WINDOW STARTING AT <x1> <y1> [ENDING AT <x2> <y2>]. Can only be used in list processing. The current detail list is displayed as a modal dialog box. The top left-hand corner of the window is positioned at column <x1> and line <y1>. The bottom right-hand corner is positioned at column <x2> and line <y2> (if specified).

WRITE Creates list output.

Syntax

WRITE [AT [/][<pos>][(<len>)]] <f> [AS CHECKBOX|SYMBOL|ICON|LINE] [QUICKINFO <g>]. [<format>] The contents of the field <f> are formatted according to their data type and displayed on the list. The additions before the field allow you to specify a line break, the starting position, and the length of the field. The additions after the field allow you to display checkboxes, symbols, icons, and lines. The <format> addition can contain various other formatting options. The QUICKINFO addition allows you to assign a quickinfo <g> to the field.

WRITE TO Assigns strings.

1496

December 1999


SAP AG

BC - ABAP Programming ABAP Statement Overview

Syntax

WRITE <f1> TO <f2> [<format>]. Converts the contents of the data object <f1> to type C and assigns the resulting string to the variable <f2>. You can use the same formatting options available in the WRITE statement.

December 1999

1497


BC - ABAP Programming

SAP AG

ABAP System Fields

ABAP System Fields The ABAP system fields are active in all ABAP programs. They are filled by the runtime environment, and you can query their values in a program to find out particular states of the system. Although they are variables, you should not assign your own values to them, since this may overwrite information that is important for the normal running of the program. However, there are some isolated cases in which you may need to overwrite a system variable. For example, by assigning a new value to the field SY-LSIND, you can control navigation within details lists. The names and data types of the system fields are contained in the ABAP Dictionary structure SYST. To address them in an ABAP program, use the form SY-<fieldname>. Within screen flow logic, you can also use the form SYST-<fieldname>. System Fields in Alphabetical Order System Fields in Thematic Order

System Fields in Alphabetical Order The following table contains an alphabetical list of the fields in the ABAP Dictionary structure SYST. The first column indicates how you can use the field in an ABAP program: The system field is set by the runtime environment. You can use its value in an ABAP program, but you must not change it. The system field is set by the runtime environment. You can both use and change its value in the ABAP program to affect the runtime behavior of the program. The system field must be set from the ABAP program. After that, it can be used by the runtime environment and within your program. The system field is for internal use only, and must not be used in ABAP programs. The system field is obsolete. No values are assigned to it, and it must not be used in ABAP programs. “Name” stands for the component name. “Type” and “Length” are the ABAP Dictionary type and length of the field. The “Use” column indicates the contexts in which the system fields can be set, and the “Description” column contains a short description of the field's function. A B C D E F G H I JK L M N O P QR S T U V W X Y Z

Name

Type Length Use

Description

ABCDE

CHAR 26

Alphabet (A,B,C,...)

1498

Constants

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

APPLI

RAW

2

Obsolete

BATCH

CHAR 1

Background processing

BATZD

CHAR 1

Obsolete

BATZM

CHAR 1

Obsolete

BATZO

CHAR 1

Obsolete

BATZS

CHAR 1

Obsolete

BATZW

CHAR 1

Obsolete

BINPT

CHAR 1

Batch input

BREP4

CHAR 4

Obsolete

BSPLD

CHAR 1

Obsolete

CALLD

CHAR 1

ABAP program

Call mode of the ABAP program

CALLR

CHAR 8

Printing lists

ID for print dialog function

CCURS

DEC

9

Obsolete

CCURT

DEC

9

Obsolete

CDATE

DATS

8

Obsolete

CFWAE

CUKY 5

Internal

CHWAE CUKY 5

Internal

COLNO

INT4

10

Creating lists

Current list column

CPAGE

INT4

10

Processing lists

Current page number

CPROG

CHAR 40

ABAP program

Program that called the current external procedure

CTABL

CHAR 4

Obsolete

CTYPE

CHAR 1

Obsolete

CUCOL

INT4

10

Screens

Horizontal cursor position in PAI

CUROW INT4

10

Screens

Vertical cursor position in PAI

Is program running in the background?

Is program running in the background?

DATAR

CHAR 1

Screens

Displays user input

DATLO

DATS

8

Date and time

User’s local date

DATUM

DATS

8

Date and time

Current application server date

DAYST

CHAR 1

Date and time

Flag for summer (daylight saving) time

DBCNT

INT4

Database access

Number of database rows processed

DBNAM

CHAR 20

ABAP program

Logical database linked to the program

December 1999

10

1499


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order DBSYS

CHAR 10

R/3 System

DCSYS

CHAR 4

Obsolete

DEBUG

CHAR 1

Internal

DSNAM

CHAR 8

Internal

DYNGR

CHAR 4

ABAP program

Screen group of the current screen

DYNNR

CHAR 4

ABAP program

Number of the current screen

ENTRY

CHAR 72

Internal

FDAYW

INT1

3

Date and time

Day in the factory calendar

FDPOS

INT4

10

Strings

Offset in a string

FFILE

CHAR 8

Internal

FLENG

INT4

Internal

FMKEY

CHAR 3

Obsolete

FODEC

INT4

10

Internal

FOLEN

INT4

10

Internal

FTYPE

CHAR 1

Internal

GROUP

CHAR 1

Internal

HOST

CHAR 8

R/3 System

Name of application server

INDEX

INT4

Loops

Current loop pass

INPUT

CHAR 1

Internal

LANGU

LANG

R/3 System

User’s logon language

LDBPG

CHAR 40

ABAP program

Logical database program

LILLI

INT4

10

Processing lists

List line selected

LINCT

INT4

10

Creating lists

Page length in a list

LINNO

INT4

10

Creating lists

Current line

LINSZ

INT4

10

Creating lists

Line width in a list

LISEL

CHAR 255

Processing lists

Contents of the chosen line

LISTI

INT4

Processing lists

Index of the chosen list

LOCDB

CHAR 1

Obsolete

LOCOP

CHAR 1

Obsolete

LOOPC

INT4

Screens

1500

10

10

1

10

10

Name of the central database system

Number of lines visible in the table

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

LPASS

CHAR 4

Internal

LSIND

INT4

10

Processing lists

Index of the detail list

LSTAT

CHAR 16

Processing lists

ID for list levels

MACDB

CHAR 4

Obsolete

MACOL

INT4

10

Printing lists

Columns from the SET MARGIN statement

MANDT

CLNT

3

R/3 System

Current client

MARKY

CHAR 1

MAROW INT4

10

Obsolete Printing lists

Rows from the SET MARGIN statement

MODNO CHAR 1

R/3 System

Index of the external sessions

MSGID

CHAR 20

Messages

Message class

MSGLI

CHAR 60

Messages

Message line

MSGNO NUMC 3

Messages

Message number

MSGTY

CHAR 1

Messages

Message type

MSGV1

CHAR 50

Messages

Message variable

MSGV2

CHAR 50

Messages

Message variable

MSGV3

CHAR 50

Messages

Message variable

MSGV4

CHAR 50

Messages

Message variable

NEWPA CHAR 1

Internal

NRPAG

CHAR 1

Internal

ONCOM CHAR 1

Internal

OPSYS

CHAR 10

R/3 System

Operating system of application server

PAART

CHAR 16

Printing lists

Print formatting

PAGCT

INT4

10

Obsolete

PAGNO

INT4

10

Creating lists

PAUTH

NUMC 2

Internal

PDEST

CHAR 4

Printing lists

Output device

PEXPI

NUMC 1

Printing lists

Spool retention period

PFKEY

CHAR 20

Screens

Current GUI status

PLAYO

CHAR 5

Internal

PLAYP

CHAR 1

Internal

December 1999

Current page

1501


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order PLIST

CHAR 12

Printing lists

Name of spool request

PNWPA CHAR 1

Internal

PRABT

CHAR 12

Printing lists

Cover sheet: Department

PRBIG

CHAR 1

Printing lists

Selection cover sheet

PRCOP

NUMC 3

Printing lists

Number of copies

PRDSN

CHAR 6

Printing lists

Name of the spool dataset

PREFX

CHAR 3

Obsolete

PRI40

CHAR 1

Internal

PRIMM

CHAR 1

Printing lists

PRINI

NUMC 1

Internal

PRLOG

CHAR 1

Internal

Output immediately

PRNEW CHAR 1

Printing lists

New spool request

PRREC

CHAR 12

Printing lists

Recipient

PRREL

CHAR 1

Printing lists

Delete after output

PRTXT

CHAR 68

Printing lists

Text for cover sheet

REPI2

CHAR 40

Internal

REPID

CHAR 40

ABAP program

RSTRT

CHAR 1

Internal

RTITL

CHAR 70

Printing lists

Program from which you are printing

SAPRL

CHAR 4

R/3 System

R/3 Release in use

SCOLS

INT4

Screens

Number of columns

SFNAM

CHAR 30

Obsolete

SFOFF

INT4

Internal

SLSET

CHAR 14

Selection screens

Variant name

SPONO

NUMC 10

Printing lists

Spool number

SPONR

NUMC 10

Obsolete

10

10

Current main program

SROWS INT4

10

Screens

Number of lines

STACO

INT4

10

List processing

First column displayed

STARO

INT4

10

List processing

Topmost line displayed

STEPL

INT4

10

Screens

Index of current table line

1502

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

SUBCS

CHAR 1

Internal

SUBRC

INT4

10

Return code

SUBTY

RAW

1

Internal

SYSID

CHAR 8

R/3 System

TABID

CHAR 8

Internal

TABIX

INT4

Internal tables

Current line index

TCODE

CHAR 20

ABAP program

Current transaction code

TFDSN

CHAR 8

Obsolete

TFILL

INT4

10

Internal tables

Current number of lines

TIMLO

TIMS

6

Date and time

User’s local time

TITLE

CHAR 70

Screens

Text in the title bar

TLENG

INT4

10

Internal tables

Line size

TLOPC

INT4

10

Internal

TMAXL

INT4

10

Obsolete

TNAME

CHAR 30

Obsolete

TOCCU

INT4

10

Internal tables

TPAGI

INT4

10

Obsolete

TSTIS

INT4

10

Internal

TTABC

INT4

10

Obsolete

TTABI

INT4

10

Obsolete

TVAR0

CHAR 20

Creating lists

Text variable for titles

TVAR1

CHAR 20

Creating lists

Text variable for titles

TVAR2

CHAR 20

Creating lists

Text variable for titles

TVAR3

CHAR 20

Creating lists

Text variable for titles

TVAR4

CHAR 20

Creating lists

Text variable for titles

TVAR5

CHAR 20

Creating lists

Text variable for titles

TVAR6

CHAR 20

Creating lists

Text variable for titles

TVAR7

CHAR 20

Creating lists

Text variable for titles

TVAR8

CHAR 20

Creating lists

Text variable for titles

TVAR9

CHAR 20

Creating lists

Text variable for titles

December 1999

10

Return code following an ABAP statement

Name of the R/3 System

Initial memory requirement

1503


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order TZONE

INT4

10

Date and time

Difference between local time and GMT

UCOMM CHAR 70

Screens

Function code that triggered PAI

ULINE

CHAR 255

Constants

Horizontal line with length 255

UNAME

CHAR 12

R/3 System

Username of current user

UZEIT

TIMS

Date and time

Current application server time

VLINE

CHAR 1

Constants

Vertical line

6

WAERS CUKY 5

Obsolete

WILLI

INT4

10

Obsolete

WINCO

INT4

10

Obsolete

WINDI

INT4

10

Obsolete

WINRO

INT4

10

Obsolete

WINSL

CHAR 79

Obsolete

WINX1

INT4

10

Obsolete

WINX2

INT4

10

Obsolete

WINY1

INT4

10

Obsolete

WINY2

INT4

10

Obsolete

WTITL

CHAR 1

Creating lists

XCODE

CHAR 70

Internal

XFORM

CHAR 30

Internal

XPROG

CHAR 40

Internal

ZONLO

CHAR 6

Date and time

Flag for standard page header

User’s time zone

System Fields in Thematic Order The system fields are grouped thematically below with notes on their use: System Information •

Information About the Current R/3 System

Information About the Current Terminal Session

Information About the Current Date and Time

Information About the Current ABAP Program

1504

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

Background Processing

Batch Input

ABAP Programming •

Constants

Strings

Loops

Internal Tables

Database Access

Return Code

Screens •

Screens

Selection Screens

Lists

Messages

Internal System Fields Obsolete System Fields

System Information Information About the Current R/3 System SY-DBSYS Central database system (such as INFORMIX or ORACLE)

SY-HOST Application server (such as HS0333, PAWDF087 …)

SY-OPSYS Operating system of the application server (such as HP-UX, SINIX)

SY-SAPRL R/3 Release in use (such as 30D, 46A, …)

SY-SYSID R/3 System name (such as B20, I47, ...)

December 1999

1505


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order

Information About the Current Terminal Session SY-LANGU One-character language key with the user’s logon language (such as D, E, F…)

SY-MANDT Client in which the user is logged on (such as 000, 400…) When you use Open SQL to access the database, SY-MANDT is used as the first key field in the WHERE clause.

SY-MODNO Index of the external sessions. The first session has the index zero. The value is increased by one each time you choose System → Create session or start a transaction by entering /o<tcode>. If you have deleted sessions, the system fills free numbers before increasing the count further. Sessions started using CALL TRANSACTION … STARTING NEW TASK begin again at 0.

SY-UNAME Username of the current user, such as KELLERH, BC400-01…

Information About Current Date and Time The following system fields are always set automatically. The GET TIME statement synchronizes the time on the application server with the time on the database server and writes it to the field SY-UZEIT. SY-DATUM and the system fields for the local timezone (SY-TIMLO, SY-DATLO, and SY-ZONLO) are also reset.

SY-DATLO User’s local date, for example 19981129, 19990628, …

SY-DATUM Current application server date, for example 19981130, 19990627, …

SY-DAYST X during summertime, otherwise space.

SY-FDAYW Factory calendar day of the week: Monday = 1 … Friday = 5.

SY-TIMLO User’s local time, for example 154353, 225312, …

SY-TZONE Time difference in seconds between local time and Greenwich Mean Time (UTC), for example, 360, 10800.

SY-UZEIT Current application server time. for example 164353, 215312, …

1506

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

SY-ZONLO User’s time zone, for example, EST, UTC, …

Information About the Current ABAP Program SY-CALLD X if the program was started using CALL TRANSACTION, CALL DIALOG, or SUBMIT … [AND RETURN]. Space if the program was started using LEAVE TO TRANSACTION or using a transaction code from a screen. SY-CALLD is always space when a batch input session is being processed.

SY-CPROG The name of the calling program in an external routine, otherwise the name of the current program.

SY-DBNAM The name of the logical database linked to an executable program.

SY-DYNGR Screen group to which the current screen belongs. You can assign several screens to one screen group, for example, to allow you to modify them all identically.

SY-DYNNR Number of the current screen. During selection screen processing, SY-DYNNR contains the screen number of the current selection screen. During list processing, it contains the number of the container screen. During subscreen processing, SY-DYNNR contains the number of the subscreen. This also applies to tabstrip controls.

SY-LDBPG In executable programs, the database program of the associated logical database.

SY-REPID Name of the current ABAP program. For externally-called procedures, it is the name of the main program of the procedure. If you pass SY-REPID as an actual parameter to an external procedure, the formal parameter does not contain the name of the caller, but that of the main program of the procedure. To avoid this, assign SY-REPID to an auxiliary variable and use that in the call, or use the system field SY-CPROG.

SY-TCODE The current transaction code.

Background Processing SY-BATCH X if the ABAP program is running in the background, otherwise space

December 1999

1507


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order

Batch Input SY-BINPT X while a batch input session is running and when an ABAP program is called using CALL TRANSACTION USING, otherwise space. •

OPTIONS FROM in the CALL TRANSACTION USING statement can set SY-BINPT to space either for the entire duration of the program, or at the end of the BDC data.

SY-BINPT is always space during a CATT procedure.

ABAP Programming Constants SY-ABCDE Contains the alphabet. You can use this field with offset to retrieve a letter of the alphabet regardless of codepage.

SY-ULINE Contains a horizontal line with length 255 that you can use when creating lists.

SY-VLINE Contains a vertical line (|) that you can use when creating lists.

Loops SY-INDEX In a DO or WHILE loop, SY-INDEX contains the number of loop passes including the current pass.

Strings SY-FDPOS Location of hit in string operations. •

When you use CO,CN, CA, NA, CS, NS, CP, and NP, offset values are assigned to SYFDPOS depending on the search result.

SEARCH … FOR … sets SY-FDPOS to the offset of the search string.

Internal Tables SY-TABIX Current line of an internal table. SY-TABIX is set by the statements below, but only for index tables. The field is either not set or is set to 0 for hashed tables. •

APPEND sets SY-TABIX to the index of the last line of the table, that is, it contains the overall number of entries in the table.

1508

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

COLLECT sets SY-TABIX to the index of the existing or inserted line in the table. If the table has the type HASHED TABLE, SY-TABIX is set to 0.

LOOP AT sets SY-TABIX to the index of the current line at the beginning of each loop lass. At the end of the loop, SY-TABIX is reset to the value that it had before entering the loop. It is set to 0 if the table has the type HASHED TABLE.

READ TABLE sets SY-TABIX to the index of the table line read. If you use a binary search, and the system does not find a line, SY-TABIX contains the total number of lines, or one more than the total number of lines. SY-INDEX is undefined if a linear search fails to return an entry.

SEARCH <itab> FOR sets SY-TABIX to the index of the table line in which the search string is found.

SY-TFILL After the statements DESCRIBE TABLE, LOOP AT, and READ TABLE, SY-TFILL contains the number of lines in the relevant internal table.

SY-TLENG After the statements DESCRIBE TABLE, LOOP AT, and READ TABLE, SY-TLENG contains the length of the lines in the relevant internal table.

SY-TOCCU After the statements DESCRIBE TABLE, LOOP AT, and READ TABLE, SY-TLENG contains the initial amount of memory allocated to the relevant internal table.

Database Access SY-DBCNT SQL statements set SY-DBCNT to the number of table entries processed. In an Open SQL SELECT loop, SY-DBCNT is not set until after the ENDSELECT statement. In Native SQL, SYDBCNT is not set until after the ENDEXEC statement. •

DELETE sets SY-DBCNT to the number of deleted lines.

FETCH sets SY-DBCNT to the number of lines read by the corresponding cursor.

INSERT sets SY-DBCNT to the number of lines inserted.

MODIFY sets SY-DBCNT to the number of lines processed.

UPDATE sets SY-DBCNT to the number of lines changed.

Return Code SY-SUBRC Return code, set by the following ABAP statements. As a rule, if SY-SUBRC = 0, the statement was executed successfully. •

ASSIGN sets SY-SUBRC to 0 if the field symbol assignment was possible, otherwise to 4.

AUTHORITY-CHECK sets SY-SUBRC to 0 if the user has the required authorization, otherwise to 4, 8, 12, 16, 24, 28, 32, or 36 depending on the cause of the authorization failure.

December 1999

1509


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order •

CALL DIALOG with USING sets SY-SUBRC to 0 if the processing is successful, otherwise to a value other than 0.

CALL FUNCTION sets SY-SUBRC in accordance with the defined exception handling.

CALL METHOD sets SY-SUBRC in accordance with the defined exception handling.

CALL SELECTION-SCREEN sets SY-SUBRC to 0 if the user chooses Enter or Execute, and 4 if the user chooses Cancel.

CALL TRANSACTION with USING sets SY-SUBRC to 0 if the processing is successful, otherwise to a value other than 0.

CATCH SYSTEM-EXCEPTIONS sets SY-SUBRC after the ENDCATCH statement if a system exception occurs. The value is set in the program.

COMMIT WORK sets SY-SUBRC to 0.

COMMIT WORK AND WAIT sets SY-SUBRC to 0 if the update is successful, otherwise to a value other than 0.

COMMUNICATION INIT DESTINATION … RETURNCODE sets SY-SUBRC as specified.

CONCATENATE sets SY-SUBRC to 0 if the result fits into the target variable, otherwise to 4.

CREATE OBJECT sets SY-SUBRC if the exceptions of the instance constructor are handled in the program.

CREATE OBJECT in OLE2 sets SY-SUBRC to 0 if an external object could be created, otherwise to 1, 2, or 3, depending on the cause.

DELETE sets SY-SUBRC to 0 if the operation is successful, otherwise to 4 or another value other than 0, depending on the cause.

DEMAND … MESSAGES INTO sets SY-SUBRC to 0 if the message table is empty, otherwise to a value other than 0.

DESCRIBE LIST sets SY-SUBRC to 0 if the line or list exists, otherwise to 4 or 8.

EXEC SQL - ENDEXEC sets SY-SUBRC to 0 in nearly all cases. It does, however, set SYSUBRC to 4 if no entry is read in a FETCH statement.

FETCH sets SY-SUBRC to 0 if at least one line was read, otherwise to 4.

GENERATE SUBROUTINE POOL sets SY-SUBRC to 0 if the generation was successful, otherwise to 8.

GET CURSOR sets SY-SUBRC to 0 if the cursor is correctly positioned, otherwise to 4.

GET PARAMETER sets SY-SUBRC to 0 if a corresponding value exists in SAP memory, otherwise to 4.

IMPORT sets SY-SUBRC to 0 if the import is successful, otherwise to 4.

INSERT sets SY-SUBRC to 0 if the operation is successful, otherwise to 4.

LOAD REPORT sets SY-SUBRC to 0 if the operation is successful, otherwise to 4 or 8 depending on the cause of the error.

LOOP sets SY-SUBRC to 0 if there is at least one pass through the extract. Otherwise, it is set to a value other than 0.

1510

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

LOOP AT sets SY-SUBRC to 0 if there is at least one loop pass through the internal table, otherwise to 4.

MODIFY sets SY-SUBRC to 0 if the operation is successful, otherwise to 4.

MODIFY LINE sets SY-SUBRC to 0 if a line in the list was changed, otherwise it sets it to a value other than 0.

MODIFY sets SY-SUBRC to 0 if the operation is successful, otherwise to 4.

OLE2 Automation: Bundled commands set SY-SUBRC to 0 if all commands could be executed successfully, otherwise 1, 2, 3, or 4, depending on the cause of the error.

OPEN DATASET sets SY-SUBRC to 0 if the file could be opened, otherwise to 8.

Open SQL statements set SY-SUBRC to 0 if the operation is successful, otherwise to a value other than 0.

OVERLAY sets SY-SUBRC to 0 if at least one character is overlaid, otherwise to 4.

READ DATASET sets SY-SUBRC to 0 if the read operation was successful, otherwise to 4 or 8, depending on the cause of the error.

READ LINE sets SY-SUBRC to 0 if a list line exists, otherwise to a value other than 0.

READ TABLE sets SY-SUBRC to 0 if table lines are found, otherwise to 2, 4, or 8, depending on the context and cause of the error.

REPLACE sets SY-SUBRC to 0 if the search string was replaced, otherwise to a value other than 0.

SCROLL sets SY-SUBRC to 0 if the scrolling within the list was successful, otherwise to 4 or 8, depending on the cause.

SEARCH sets SY-SUBRC to 0 if the search string was found, otherwise to 4.

SELECT sets SY-SUBRC to 0 if at least one line was read, otherwise to 4, or possibly 8 in SELECT SINGLE FOR UPDATE.

SET COUNTRY sets SY-SUBRC if the country code exists in table T005X, otherwise to 4.

SET BIT sets SY-SUBRC to 0 if the bit could be set, otherwise to a value other than 0.

SET TITLEBAR sets SY-SUBRC to 0 if the title exists, otherwise to 4.

SHIFT … UP TO sets SY-SUBRC to 0 if the position could be found within the string, otherwise to 4.

SPLIT sets SY-SUBRC to 0 if the sizes of the target fields are adequate, otherwise to 4.

UPDATE sets SY-SUBRC to 0 if the operation is successful, otherwise to 4.

WRITE … TO sets SY-SUBRC to 0 if the assignment is successful, otherwise to 4.

December 1999

1511


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order

Screens Screens A group of system fields is set in the PAI event of each screen. With the exception of SY-DATAR, SY-LOOPC, and SY-STEPL, you can also use all of them in interactive list processing

SY-CUCOL Horizontal cursor position. Counter begins at column 2.

SY-CUROW Vertical cursor position. Counter begins at line 1.

SY-DATAR X if at least one input field on the screen was changed by the user or other data transport, otherwise space.

SY-LOOPC Number of lines currently displayed in a table control.

SY-PFKEY GUI status of the current screen. This can be set in the PBO event using the SET PF-STATUS statement.

SY-SCOLS Number of columns on the current screen.

SY-SROWS Number of rows on the current screen.

SY-STEPL Index of the current line in a table control. This is set in each loop pass. SY-STEPL does not have a meaningful value outside the loop (for example, during the POV event for a table line).

SY-TITLE Text that appears in the title bar of the screen. This is the program name for selection screens and lists, and SAP R/3 otherwise. Can be set using the SET TITLEBAR statement.

SY-UCOMM Function code that triggered the PAI event. There is a unique function code assigned to every function that triggers the PAI event with one exception: ENTER triggers the PAI, and various function codes can be passed to SY-UCOMM: •

If the user has entered a command in the command field, this is passed to SY-UCOMM.

If there is no entry in the command field and a function code has been assigned to the ENTER key, this function code is passed to SY-UCOMM.

1512

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

If there is no entry in the command field and there is no function key assigned to the ENTER key, the content of SY-UCOMM remains unchanged.

Selection Screens SY-SLSET Variant used to fill the selection screen.

Creating Lists When you create a list, you can use the following system fields to control navigation. They help you to ensure that output statements do not overwrite existing output, or that data is not written outside the list. The system fields SY-COLNO and SY-LINNO always contain the current output position, and they are reset by each output statement. The other system fields contain other values used for creating lists.

SY-COLNO Current column during list creation. The counter begins at 1. The field is set by the following output statements: •

WRITE, ULINE, and SKIP set SY-COLNO to the next output position.

BACK sets SY-COLNO to 1.

POSITION <col> sets SY-COLNO to <col>. If <col> is beyond the page border, any subsequent output statements are ignored.

NEW-LINE sets SY-COLNO to 1.

NEW-PAGE sets SY-COLNO to 1.

SY-LINCT Page length of the list. For a default list of indefinite length, SY-LINCT is 0. If the page length is defined, SY-LINCT has that value. •

LINE-COUNT in the REPORT, PROGRAM, or FUNCTION POOL statement sets SY-LINCT for the current program.

LINE-COUNT in the SUBMIT statement sets SY-LINCT for the program called in the statement.

SY-LINNO Current line during list creation. The counter begins at 1, and includes the page header. SYLINNO is set by the following output statements: •

WRITE, ULINE, and SKIP increase SY-LINNO by one at each line break.

BACK sets SY-LINNO to the first line following the page header. If you use BACK with RESERVE, SY-LINNO is set to the first line of a block.

NEW-LINE increases SY-LINNO by one.

SKIP TO LINE <lin> sets SY-LINNO to <lin>. If <lin> is not between 1 and the length of the page, the statement is ignored.

December 1999

1513


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order SY-LINSZ Line width in the list. The default value is the default window width. SY-LINSZ = SY-SCOLS, for SY-SCOLS >= 84, and 84 for SY-SCOLS < 84 You can change the line width of the list using the LINE-SIZE addition in the REPORT or NEWPAGE statement. •

LINE-SIZE in the REPORT, PROGRAM, or FUNCTION POOL statement sets SY-LINSZ for the current program.

LINE-SIZE in the SUBMIT statement sets SY-LINSZ for the program called in the statement.

SY-PAGNO Current page during list creation. •

WRITE, ULINE, and SKIP increase SY-PAGNO by one at each page break.

NEW-PAGE increases SY-PAGNO by one, but only if there is at least one output line on both the current page and the intended next page.

NEW-SECTION in the statement NEW-PAGE PRINT ON sets SY-PAGNO to 1.

SY-TVAR0 ... SY-TVAR9 You can assign values to these variables in your programs. Their contents replace the placeholders in the list and column headers of the program in the TOP-OF-PAGE event.

SY-WTITL The REPORT, PROGRAM, and FUNCTION-POOL statements set this variable to N if you use the NO STANDARD PAGE HEADING addition. Otherwise, it has the value space. NEW-PAGE does not set SY-WTITL.

List Processing The following system fields are filled at each interactive list event and at the READ LINE statement:

SY-CPAGE Page number of the topmost page in the display of the list on which the event was triggered. The counter begins at 1.

SY-LILLI Line at which the event was triggered. The counter begins at 1 and includes the page header.

SY-LISEL Contents of the line in which the event was triggered (restricted to the first 255 characters).

SY-LISTI Index of the list in which the event was triggered.

SY-LSIND Index of the list currently being created. The basic list has SY-LSIND = 0, detail lists have SYLSIND > 0. The field is automatically increased by one in each interactive list event. You may change the value of SY-LSIND yourself in the program to enable you to navigate between lists.

1514

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

Changes to SY-LSIND do not take effect until the end of a list event. It is therefore a good idea to place the relevant statement at the end of the corresponding processing block.

SY-LSTAT Program-controlled name for list levels. You can assign values to SY-LSTAT during list creation. The value of SY-LSTAT when the list is finished is saved with the list. In an interactive list event, SY-LSTAT is set to the value assigned to it during creation of the list in which the event occurred. SY-LSTAT is no longer maintained, and you should not use it in your programs.

SY-STACO Number of the first displayed column of the list from which the event was triggered. The counter begins at 1.

SY-STARO Number of the topmost displayed line of the topmost displayed page of the list from which the event was triggered. The counter begins at 1, not including the page header.

Printing Lists When you print lists, the spool and runtime systems require certain internal information that is set in the following system fields when you start printing.

SY-CALLR Contains a value indicating where printing was started, for example, NEW-PAGE for programcontrolled printing, or RSDBRUNT for printing from a selection screen.

SY-PRDSN Contains the name of the spool file during printing.

SY-SPONO Contains the spool number during printing.

SY-MAROW, SY-MACOL The SET MARGIN statement fills the system fields SY-MAROW and SY-MACOL. These determine the number of lines in the top margin and the number of columns in the left-hand margin respectively.

Print Parameters The print parameters are passed to the spool system by the runtime environment, using a structure with the ABAP Dictionary type PRI_PARAMS. Before this structure existed, system fields were used instead. When you start printing, some of the fields from PRI_PARAMS are still written into system fields with the same names. However, you should not use these system fields yourself.

Messages When the MESSAGE statement occurs, the following system fields are set. When the MESSAGE ‌ RAISING statement occurs in a function module or method, these fields are also set in the calling program if it is to handle the exception.

December 1999

1515


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order SY-MSGID SY-MSGID contains the message class

SY-MSGNO SY-MSGNO contains the message number

SY-MSGTY SY-MSGTY contains the message type

SY-MSGV1,…,SY-MSGV4 SY-MSGV1 to SY-MSGV4 contain the fields used to replace the placeholders in the message.

Special Actions that Fill Message Fields •

When you use an ENQUEUE function module to set a lock, and the FOREIGN_LOCK exception occurs, the field SY-MSGV1 contains the name of the owner of the lock.

When you use CALL TRANSACTION or CALL DIALOG with the USING addition, a message that occurs during the screen chain is returned in the fields SY-MSGID, SY-MSGTY, SYMSGNO, and SY-MSGV1 ... SY-MSGV4.

In Remote Function Call (RFC), error messages are retrieved from the remote system and placed in the system fields SY-MSGID, SY-MSGTY, SY-MSGNO,SY-MSGV1, SY-MSGV2, SY-MSGV3, SY-MSGV4. The fields are also set when a short dump or a message with type X occurs.

Internal System Fields Internal system fields are exclusively for internal use in the ABAP runtime environment and the system kernel. They must not be overwritten in any circumstances, and should also not be read in ABAP programs.

SY-CFWAE Undocumented

SY-CHWAE Undocumented

SY-DEBUG Undocumented

SY-DSNAM File name for spool output

SY-ENTRY Undocumented

1516

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

SY-FFILE Flat file (USING/GENERATING DATASET).

SY-FLENG Length of a field

SY-FODEC Number of decimal places in a field

SY-FOLEN Output length of a field

SY-FTYPE Data type of a field

SY-GROUP Bundling

SY-INPUT Undocumented

SY-LPASS Undocumented

SY-NEWPA Undocumented

SY-NRPAG Undocumented

SY-ONCOM Undocumented

SY-PAUTH Undocumented

SY-PLAYO Undocumented

SY-PLAYP Undocumented

SY-PNWPA Undocumented

SY-PRI40 Undocumented

December 1999

1517


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order SY-PRINI Undocumented

SY-PRLOG Undocumented

SY-REPI2 Undocumented

SY-RSTRT Undocumented

SY-SFOFF Undocumented

SY-SUBCS Call status of an executable program

SY-SUBTY Call type of an executable program

SY-TABID Undocumented

SY-TLOPC Undocumented

SY-TSTIS Undocumented

SY-XCODE Extended function code, filled by user actions on a list (like SY-UCOMM). Before the length of SY-UCOMM was extended from 4 to 70 characters, SY-XCODE was used internally to accommodate long entries in the command field. You should always use SY-UCOMM in application programs.

SY-XFORM SYSTEM-EXIT subroutine.

SY-XPROG SYSTEM-EXIT program.

1518

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

Obsolete System Fields Some of the system fields in the R/3 System were originally adopted from R/2, but are no longer filled with values. They are obsolete, and must not (indeed cannot) be used.

SY-APPLI R/2 - ID for the SAP applications installed. Not filled in R/3.

SY-BATZD R/2 - flag for daily background scheduling. Not filled in R/3.

SY-BATZM R/2 - flag for monthly background scheduling. Not filled in R/3.

SY-BATZO R/2 - flag for one-time background scheduling. Not filled in R/3.

SY-BATZS R/2 - flag for immediate background scheduling. Not filled in R/3.

SY-BATZW R/2 - flag for weekly background scheduling. Not filled in R/3.

SY-BREP4 R/2 - root name of the report requesting background processing. Not filled in R/3.

SY-BSPLD R/2 - flag for spool output from background processing. Not filled in R/3.

SY-CCURS R/2 - exchange rate and result field for CURRENCY CONVERSION. Not filled in R/3.

SY-CCURT R/2 - table exchange rate for CURRENCY CONVERSION. Not filled in R/3.

SY-CDATE R/2 - exchange rate date for CURRENCY CONVERSION. Not filled in R/3.

SY-CTABL R/2 - exchange rate table for CURRENCY CONVERSION. Not filled in R/3.

SY-CTYPE R/2 - exchange rate type for CURRENCY CONVERSION. Not filled in R/3.

SY-DCSYS Dialog system of the R/2 System. Not filled in R/3.

December 1999

1519


BC - ABAP Programming

SAP AG

System Fields in Alphabetical Order SY-FMKEY Formerly the current function code menu. Not filled in R/3.

SY-LOCDB Local database. Not implemented.

SY-LOCOP Local database operation. Not implemented.

SY-MACDB Formerly the file name for matchcode access. Not filled in R/3.

SY-MARKY Current line letter for the MARK statement. The MARK statement will not be supported for much longer.

SY-TMAXL Formerly the maximum number of entries in an internal table. Not filled in R/3.

SY-TFDSN Formerly the name of an external storage file for extracts. Not filled in R/3.

SY-PAGCT R/2 - the maximum number of pages per list. Not filled in R/3.

SY-PREFX ABAP prefix for background jobs. Not filled in R/3.

SY-SFNAM Undocumented

SY-SPONR In R/2, you could process spool files with the TRANSFER statement, which also set SY-SPONR. Not filled in R/3.

SY-TNAME Formerly the name of an internal table following access. Not filled in R/3.

SY-TTABC Formerly the index of the last line of an internal table to be read. Not filled in R/3.

SY-TTABI Formerly the offset of internal tables in the roll area. Not filled in R/3.

SY-TPAGI Formerly flagged whether an internal table had been moved to the paging area. Not filled in R/3.

1520

December 1999


SAP AG

BC - ABAP Programming System Fields in Alphabetical Order

SY-WAERS Formerly the company code currency after reading a posting segment. Not filled in R/3.

SY-WILLI R/2 - the number of the list line selected from a detail list. Use SY-LILLI instead.

SY-WINCO R/2 - cursor position on a detail list. Use SY-CUCOL instead.

SY-WINDI R/2 - index of the list for a detail list. Use SY-LSIND instead.

SY-WINRO R/2 - cursor position for a detail list. Use SY-CUROW instead.

SY-WINSL R/2 - contents of the selected line for detail list in a window. Use SY-LISEL instead.

SY-WINX1 R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

SY-WINX2 R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

SY-WINY1 R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

SY-WINY2 R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

December 1999

1521


BC - ABAP Programming

SAP AG

ABAP Glossary

ABAP Glossary A ABAP Advanced Business Application Language. The SAP programming language for application programming.

ABAP Dictionary Central information repository for application and system data. The ABAP Dictionary contains data definitions (metadata) that allow you to describe all of the data structures in the system (like tables, views, and data types) in one place. This eliminates redundancy.

ABAP Editor Tool in the ABAP Workbench in which you enter the source code of ABAP programs and check their syntax. You can also navigate from the ABAP Editor to the other tools in the ABAP Workbench.

ABAP Memory ABAP Memory is a memory area in the internal session (roll area) of an ABAP program. Data within this area is retained within a sequence of program calls, allowing you to pass data between programs that call one another. It is also possible to pass data between sessions using SAP Memory.

ABAP Objects The ABAP runtime environment or the object-oriented extension of ABAP. ABAP Objects uses classes to create objects.

ABAP Processor The ABAP processor executes the processing logic of the application program, and communicates with the database interface.

ABAP Query Allows you to create simple reports without having to know any ABAP.

ABAP Workbench The ABAP Workbench is a fully-fledged development environment for applications in the ABAP language. With it, you can create, edit, test, and organize application developments. It contains a range of tools including the Screen Painter, ABAP Editor, and Repository Browser.

1522

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Aggregated Data Types Data types built up of a series of single field types. An aggregated data type can be a structure or an internal table. With aggregated types, you can either access the whole object or individual fields.

Application Logic Generic term for the parts of application programs that process application-relevant data.

Actual Parameter When you pass parameters to a procedure, the actual parameters are the parameters that you pass from the program. They are passed to the formal parameters within the routine.

Application Server The level within the client/server architecture in which application logic runs.

Attribute A component of a class in ABAP Objects. Attributes contain the data of a class. They are used by the methods of classes.

B Background Processing Program processing without user dialogs.

Bottom-Up Development method that starts with the lowest components in a hierarchy and becomes more generalized as the development project continues. The opposite of top-down.

Business API (BAPI) Standard interface in the R/3 System that allows the system to communicate with components of other business software suites.

C Casting A reference assignment in ABAP Objects. It is checked for correctness at runtime, not in the syntax check.

Class Template for objects in ABAP Objects. You can define classes either locally in an ABAP program, or globally using the Class Builder in the ABAP Workbench. You can either define a new class from first principles, or derive one using inheritance. Classes can implement interfaces.

December 1999

1523


BC - ABAP Programming

SAP AG

ABAP Glossary

Class Builder ABAP Workbench tool used to create classes and interfaces.

Class Reference Data type of a reference variable or object reference that allows you to access all of the visible components of an class.

Client A unit within an R/3 System that is complete in a legal and organizational sense, and which has its own user masters and own tables.

Client Handling Users working in a particular client are only allowed to use certain transactions, as specified in the administration data for that client. The R/3 System automatically enforces this restriction. When you program database accesses, it is possible to bypass automatic client handling.

Client/Server Architecture An architecture in which data and applications are distributed over different hosts in order to make the most efficient use of each host’s resources.

Cluster An object-oriented collection of tables.

Comment Explanatory notes in the source code of a program that make it easier to understand. This makes subsequent maintenance and support easier. You can make a whole line into a comment by placing a * at the beginning of the line. Alternatively, if you place a " anywhere in a line, the rest of that line becomes a comment.

Company Code A legally-independent unit within a client that has its own fiscal year end.

Constant A data object declared statically with a declarative statement. They allow you to store data under a particular name within the memory area of a program. The value of a constant must be defined when you declare it. It cannot subsequently be changed.

Container A file containing several programming units that all have the same type. For example, you can have a container for subroutines.

Contexts A technique for avoiding repeated database access or calculations with data in a program. You create contexts using the Context Builder in the ABAP Workbench. They contain key fields, definitions of the relationships between the fields, and other fields that can be derived or calculated using the key field values.

1524

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Control Levels A series of lines in an internal table or extract dataset that forms a group based on the contents of one or more of its fields.

Control Level Processing Used in an internal table or extract dataset to form groups of entries.

D Data Control Language (DCL) Statements for authorization and consistency checks. Not used in the R/3 System, since the system is itself responsible for checking data.

Data Definition Language (DDL) Language for defining the attributes of a database management system and creating and administering database tables. It is not contained in Open SQL.

Data Dictionary See ABAP Dictionary.

Data Manipulation Language (DML) Statements for reading and changing data in database tables.

Database Set of data that is part of a database system and is managed by the database management system.

Database Commit A COMMIT WORK in a relational database system.

Database Logical Unit of Work (LUW) A logical unit of work is a set of database operations. They belong together, and are either all executed (commit) or all canceled (rollback).

Database Rollback A ROLLBACK WORK in a relational database system.

Database Cursor A mechanism for passing data from the database to an ABAP program. An open cursor is linked to a multiple-line selection in the database table for which it was opened. You can place the lines of the selection one by one into a flat target object and process them.

December 1999

1525


BC - ABAP Programming

SAP AG

ABAP Glossary

Database Interface The part of a work process that links it to the database. It converts Open SQL into Standard SQL, and allows the application server to communicate with the database.

Database Server Host on which the database is installed.

Database Table Most databases that are used for business applications are based on the relational database model, in which the real world is represented by tables.

Data Element Describes the business function of a table field. Its technical attributes are based on a domain, and its business function is described by its field labels and documentation.

Data Object Name for an instance of a data type in ABAP. A data object occupies a field in memory.

Data Type Describes the technical attributes of a data object. ABAP uses the data type of a field to interpret its contents. There are single field types, aggregated types, and object types.

Declaration Part Part of every program or procedure. It contains data, selection screen, and class definitions that are visible throughout the program or procedure.

Deep Structure A structure that contains an internal table as a component.

Deep Tables An internal table whose line type is a deep structure.

Dialog Module Statement block that describes the different states (PBO, PAI, user input) of a screen. A module pool contains a set of dialog modules.

Dialog Program A program that contains (or consists entirely of) dialog modules.

Dispatcher Link between work processes and users. It receives user interaction from the SAPgui, and directs it to a free work process.

1526

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Domain Specifies the technical attributes of a data element - its data type, length, possible values, and appearance on the screen. Each data element has an underlying domain. A single domain can be the basis for several data elements. Domains are objects in the ABAP Dictionary.

Double Byte Character Set Two byte code system for extensive character sets such as Japanese or Chinese.

E Elementary Types There are eight predefined elementary types: Character string (C), numeric string (N), date field (D), time field (T), hexadecimal field (X), integer (I), floating point number (F), and packed number (P). You can use these types as the basis for further types that you create either locally in a program or globally in the ABAP Dictionary.

Encapsulation Property of objects in object-oriented programming. Each object has an external interface. The implementation of the object is encapsulated, that is, invisible externally.

Event Block A series of statements that are processed when a particular event occurs when a program runs or in selection screen and list processing. Each event block begins with an event keyword, and ends at the introductory keyword of the next event block.

Extract Sequential dataset in the memory area of a program. An extract dataset consists of a sequence of records of a pre-defined structure. However, the structure need not be identical for all records. In one extract dataset, you can store records of different length and structure one after the other.

F Field Area in memory with address and length. Data objects in ABAP occupy fields. The contents of a field are interpreted according to the data type of the relevant data object.

Field Symbol Placeholder or symbolic name for a field. Field symbols do not occupy any space, but instead point to a data object.

Flat Structure Structure consisting only of elementary data types.

December 1999

1527


BC - ABAP Programming

SAP AG

ABAP Glossary

Flow Logic See Screen Flow Logic.

Foreign Key One or more fields in a table that occur as key fields in another table.

Formal Parameter Placeholder for passing values to a procedure. Formal parameters declare the number and types of the actual parameters that will be passed to the procedure.

Forward Navigation Forward navigation allows you to access an object by double-clicking its name in the source code of an ABAP program or in an object list.

Function Builder ABAP Workbench tool used to create, display, modify, and delete function modules and function groups.

Function Group Program with type F that contains function modules. Created using the Function Builder.

Function Library Library of existing function modules in the ABAP Workbench.

Function Module Procedure that can only be created within a type F program, but which can be called from any ABAP program within the R/3 System. You create them using the Function Builder in the ABAP Workbench. A function module has a defined parameter interface.

G Gateway This is the interface for the R/3 communication protocols (RFC, CPI/C). It can communicate with other application servers in the same R/3 System, with other R/3 Systems, with R/2 Systems, or with non-SAP systems.

Generic Attributes Attributes that are not fully typed. The missing attributes are specified dynamically at runtime.

Global Data Data that is visible throughout a program (and also in procedures that it calls).

1528

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

GUI Status Each screen has a GUI status. The status is a collection of interactive interface elements that allows the user to select functions. A GUI Status is an independent development object within an ABAP program. You create and edit them using the Menu Painter in the ABAP Workbench.

GUI Title Title of a screen that appears in the title bar of the window. A GUI title is an independent development object within an ABAP program. You create and edit them using the Menu Painter in the ABAP Workbench.

H Hashed Table An internal table whose entries you can access by specifying the key. The system manages the table using a hash algorithm. The advantage of this is that the search overhead does not increase with the size of the table.

Header Line Work area for table access. You can place the successive lines of an internal table into the header line and process them.

I Include Program A technique for modularizing the source code. Program with type I. Allows you to reuse code in different programs. The source code of an include program is fully incorporated into the source code of the program in which the include statement occurs.

Index Table An internal table for which the system maintains a linear index. You can use the index to access entries in the table. There are two kinds of index tables: Standard tables and sorted tables.

Inheritance A special way of defining a class. You can use an existing class to derive a new class. Derived classes (subclasses) inherit the attributes and methods of the original class (superclass). They may also have new methods, or redefine existing ones.

Interface Part of a class definition in ABAP Objects. You can define interfaces either locally in an ABAP program, or globally using the Class Builder in the ABAP Workbench. Classes can implement interfaces. They then adopt all of the components of the interface. The class must implement all of the methods of the interface itself.

December 1999

1529


BC - ABAP Programming

SAP AG

ABAP Glossary

Interface Reference Data type of a reference variable or object reference that allows you to access all of the visible components of an interface.

Interface Work Area A special data object that you use to pass data between screens or logical databases and ABAP programs.

Internal Tables Data object consisting of a set of lines with the same data type. There are different access types for internal tables: Sorted and unsorted index tables, and hashed tables, and also different line types: Vectors, “real� tables, with flat structures, and deep tables. You should use internal tables whenever you need to use structured data within a program.

J Join A technique for linking two or more tables. The tables involved must have at least one common column.

K Kernel Runtime environment for all R/3 applications. It is independent of hardware, operating system, and database. Has the following functions: Running applications, administration of users and processes, database access, communication with other applications, control and administration of the R/3 System.

Key Selected fields of a table used to identify table records. A key may be either unique or nonunique.

L List Lists are output-oriented screens which display formatted, structured data. They are defined, formatted, and filled using ABAP commands. Although they are output-oriented, you can include input fields in a list.

1530

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Literal Data object, without a name, that you create in the source code of a program. It is fully defined by its value. You cannot change the value of a literal.

Local Data Data that is only visible in the current program (including its subroutines) or procedure.

Logical Database Builder Tool in the ABAP Workbench for creating and editing logical databases.

Logical Database An ABAP program that retrieves data from various database tables. The dataset covered by a logical database program is sometimes referred to itself as the logical database. The lines of the relevant tables are passed one by one to the program that is using the logical database. You can use a logical database with any number of executable programs.

M Macro A technique for modularizing the source code. The DEFINE statement introduces a set of statements that you can then use at any point within a program. Unlike include programs, macros can only be used in the program in which you define them.

Menu Painter A tool in the ABAP Workbench that allows you to create menus and assign functions to function keys and pushbuttons.

Metadata Data that describes other data. Data definitions are metadata. They are stored in the ABAP Dictionary.

Method A procedure that is a component of a class in ABAP Objects. Methods represent the functions of a class. They work with the attributes. Methods can only be defined in the implementation parts of classes.

Modularization Splitting a program into various parts (modules). There are two kinds of modules - those that are included in the source code of the program when it is generated (macros (local) or include programs (global)), and those that are called as independent modules at runtime. These are known as procedures. Modularization makes large programs easier to understand and maintain, and reduces the amount of redundancy.

Module Pool Type M program containing the dialog modules of the screens in the program.

December 1999

1531


BC - ABAP Programming

SAP AG

ABAP Glossary

N Native SQL An access method that uses database-specific statements. Native SQL statements are not interpreted, and are passed to the database without any checks. You should not use Native SQL statements, since they are database-specific (your program will no longer be portable), and ABAP does not check to ensure that the statements are correct.

Nested Structure A structure that itself contains a structure as a component.

O Object A piece of code containing data (attributes) and providing services (methods). Objects are instances of classes in ABAP Objects.

Object Reference Object references are used to access the attributes and methods of an object in ABAP Objects. Object references are contained in reference variables.

Object Types Object types are used to describe objects. They contain both data and functions. Classes and interfaces are both object types. They are part of ABAP Objects.

Open SQL A set of statements that allows you to access the database from an ABAP program. Open SQL statements are fully portable to any of the database platforms supported by SAP. Open SQL is a subset of Standard SQL (without the DDL part), but also contains SAP-specific extensions.

P Parameter 1. A data object in a program whose value can either be entered by the user at runtime or be passed from another program. 2. A value passed when you call a procedure or program from another program. See also actual parameter and formal parameter.

1532

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Parameter Interface A method by which programs and the procedures that they call can exchange data. When you write subroutines or procedures, you define formal parameters, which define the type, number, and order of the actual parameters that should be passed.

Polymorphism An attribute of objects in object-oriented programming. Identically-named methods behave differently in different classes.

Presentation Server The host that receives input from the user and presents output from the system.

Procedure A modularization technique. Unlike source code modules (macros, include programs), procedures have interfaces for data transfer. ABAP contains the following kinds of procedures: -

Subroutines: Local modularization (FORM)

-

Function modules Global modularization

-

Methods: Contain the functions of classes and their instances in ABAP Objects.

Process After Input (PAI) Part of the screen flow logic. PAI processing determines what happens after the user has chosen a function on the screen.

Process Before Output (PBO) The part of the screen flow logic that determines the processing steps that occur before a screen is displayed.

Processing Block Any ABAP statement that does not belong to the declaration part, that is, the event blocks, dialog modules, and procedures.

Processing Logic Processing logic implements the business functions of the R/3 System. It is contained in ABAP programs.

Program Types -

Type 1 Report, executable program (input data → process data → display data)

-

Type M: Module pool, started using a transaction code.

-

Type F: Function group, container for function modules. Function modules may only be programmed within a function group. You create them using the Function Builder in the ABAP Workbench.

-

Type K: Class definitions, containers for global classes in ABAP Objects. You create them using the Class Builder in the ABAP Workbench.

December 1999

1533


BC - ABAP Programming

SAP AG

ABAP Glossary -

Type J: Interface definitions, containers for global interfaces in ABAP Objects. You create them using the Class Builder in the ABAP Workbench.

-

Type S: Subroutine pools, containers for subroutines. Non-executable.

-

Type I: Include programs. Non-executable.

Q R R/3 Repository Part of the database containing all development objects of the ABAP Workbench, such as programs, screens, and function modules.

RABAX A program in the ABAP runtime environment that catches runtime errors and triggers a short dump.

Reference See object reference.

Reference Variable Data object that contains an object reference. The data type of a reference variables can be a class reference or an interface reference.

Remote Function Call (RFC) An interface protocol based on CPI-C that allows programs in different systems to communicate with one another. External applications and tools can use ABAP functions, and the R/3 System can access external systems.

Report Executable program with a three-stage function: Data input → data processing → data output. Reports read and calculate using data from database tables, without actually changing it.

Repository Browser A tool in the ABAP Workbench that provides a categorized list of development objects for a development class, program, function group, or class. When you double-click an object in the list, it is opened (along with the correct Workbench tool) for display or editing. Transaction SE80.

Routine See procedure.

1534

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Runtime Error Error that occurs while a program is running, often because the error could not be determined statically by the syntax check.

Runtime Environment Umbrella term for screen and ABAP processors.

S SAPgui The SAP Graphical User Interface is the frontend of the R/3 System. It allows users to run applications and enter and display data.

SAP LUW A logical unit consisting of dialog steps, whose changes are written to the database in a single database LUW.

SAP Memory This is a memory area to which all sessions within a SAPgui have access. You can use SAP memory either to pass data from one program to another within a session (as with ABAP memory) or to pass data from one session to another.

SAP Transaction A dialog-driven program, or any program started using a transaction code.

Screen A screen (also referred to sometimes as a dynamic program or “dynpro�) consists of the screen itself and the flow logic, which controls how the screen is processed. You create both the screen and its flow logic in the Screen Painter.

Screen Flow Logic The screen flow logic consists of PBO and PAI, and controls most user interaction. The R/3 Basis system contains a special language for programming screen flow logic.

Screen Painter Tool in the ABAP Workbench, used to create screens and their flow logic.

Screen Processor The screen processor executes the screen flow logic. It takes control of communication between the work process and the SAPgui, calls processing logic modules, and passes the contents of the screen fields back to the program for processing.

Screen Table Table on a screen, created using the step loop or table control technique.

December 1999

1535


BC - ABAP Programming

SAP AG

ABAP Glossary

Screen Type There are three screen types in the R/3 System: Screens, selection screens, and lists.

Selection Screen Special screens used to enter values in ABAP programs. Unlike normal screens, they are not defined in the Screen Painter, but using ABAP statements in the program.

Selection View Selection views are a collection of fields from different database tables. You can create them in the Repository Browser or the Logical Database Builder in the ABAP Workbench.

Session The R/3 window in the SAPgui represents a session. After logging on, the user can open up to five further sessions (R/3 windows) within the single SAPgui. These behave almost like independent SAPguis.

Shared Memory The memory area shared by all work processes.

Short Dump The text that accompanies a runtime error. This should enable you to find and correct the error.

Single Field Type A data type in ABAP whose data objects occupy a single field. Elementary types and references are single field types.

Sorted Table An index table that is always stored correctly sorted according to its table key.

SPA/GPA Parameters Values stored in the user-specific ABAP memory. You create SPA/GPA parameters using the Repository Browser in the ABAP Workbench.

SQL Report An executable program that does not use a logical database. Instead, it defines its own selection screen, and reads its own data from the database using Open SQL statements.

Standard SQL A largely standardized language for accessing relational databases. It consists of three parts: -

Data Manipulation Language (DML)

-

Data Definition Language (DDL)

-

Data Control Language (DCL)

Standard Table An unsorted index table.

1536

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

Statement A line of an ABAP program. ABAP contains the following kinds of statements: declarative statements, control statements, call statements, operational statements, database statements, and modularization statements.

Structure A structure is a logically-connected set of fields. It is a data object containing a sequence of any data types. Structures can be flat, deep, or nested.

Structured Query Language (SQL) Standard language for database access See also Native SQL, Open SQL, Standard SQL.

Subclass The resulting class when you use inheritance to derive a class from a superclass.

Subquery A special Open SQL selection statement that you can use under certain conditions to form an extra query.

Subroutine A procedure that you define in a program using the FORM statement, and which you can call any number of times from any ABAP program using the PERFORM statement. When you call the subroutine, you can pass parameters to it. Subroutines are normally used locally, that is, called in the same program in which they are defined.

Superclass The class from which a subclass is derived in inheritance.

T Text Pool A set of texts belonging to a program. You address them using text symbols in the source code. The text pool can be translated into other languages.

Text Symbol A data object that is generated when you start a program from the text pool of the program.

Top-Down A development method that starts with the highest level of a hierarchy and becomes more specialized as the development project goes on. The opposite of bottom-up.

Transaction A set of work steps that belong together. In the context of database changes, the term stands for a change of state in the database. It is also used as an abbreviation of SAP transaction.

December 1999

1537


BC - ABAP Programming

SAP AG

ABAP Glossary

Transaction Code A sequence of letters and digits that starts an SAP transaction when you enter it in the command field. Transaction codes are normally used to start dialog-driven programs. However, you can also use them to start reports. You create transaction codes in the Repository Browser. They are linked to an ABAP program and an initial screen.

Transparent Table You define transparent tables in the ABAP Dictionary. They are then created in the database. You can also use transparent tables independently of the R/3 System. Cluster techniques are not used, since they cannot be read using Open SQL.

U V Variable A named data object that you can declare statically using declarative statements, or dynamically while a program is running. They allow you to store changeable data under a particular name within the memory area of a program.

Vector An internal table whose line type is an elementary type.

View A virtual table that does not contain any data, but instead provides an application-oriented view of one or more ABAP Dictionary tables.

W Work Process (Dialog) Consists of a screen processor, ABAP processor, and database interface. Part of an application server, it executes the dialog steps of application programs.

1538

December 1999


SAP AG

BC - ABAP Programming ABAP Glossary

X Y Z

December 1999

1539


BC - ABAP Programming

SAP AG

ABAP Glossary

Syntax Conventions The conventions for syntax statements in this documentation are as follows:

Key

Definition

STATEMENT Keywords and options of statements are uppercase. <variable> Variables, or words that stand for values that you fill in, are in angle brackets. Do not include the angle brackets in the value you use (exception: field symbols). [] Square brackets indicate that you can use none, one, or more of the enclosed options. Do not include the brackets in your option. | A bar between two options indicates that you can use either one or the other of the options. () Parentheses are to be typed as part of the command. , The comma means you may choose as many of the options shown as you like, separating your choices with commas. The commas are part of the syntax. <f1> <f2> Variables with indices mean that you can list as many variables as you like. They must be separated with the same symbol as the first two. ....... Dots mean that you can put anything here that is allowed in the context. In syntax statements, keywords are in upper case, variables are in angle brackets. You can disregard case when you type keywords in your program. WRITE is the same as Write is the same as write. Output on the output screen is either shown as a screen shot or in the following format: Screen output.

1540

December 1999


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.