Sap bc abap programming 1999 05 05

308
SAP AG BC - ABAP Programming Linking a Logical DB to an Executable Program December 1999 1233 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.

description

Complete SAP / Abap manual ( 1999) : 5/5

Transcript of Sap bc abap programming 1999 05 05

Page 1: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Linking a Logical DB to an ExecutableProgram

December 1999 1233

END-OF-SELECTION.

Authorization Checks in Logical DatabasesIt 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 executableprogram:

• 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 executableprogram depends on the following:

• The structure of the logical database.

For example, you should only check authorizations for company code if you actually readlines 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 yourauthorization checks centrally in the logical database program. This makes it easier to maintainlarge programming systems.

Page 2: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Calling a Logical Database Using a Function Module

1234 December 1999

Calling a Logical Database Using a Function ModuleFrom Release 4.5A it is possible to call logical databases independently from any ABAPprogram. Previously it was only possible to link a logical database to an executable program, inwhich the processing blocks of the logical database and the program were controlled by theABAP runtime environment.

To call a logical database from another program, use the function module LDB_PROCESS. Thisallows you to use the logical database as a routine for reading data. You can call more than onelogical database from the same program. You may also call the same logical database more thanonce from the same program. In the past, it was only possible to use a logical database morethan once or use more than one logical database by calling a further executable program usingSUBMIT [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 asimilar technique.

When you call a logical database using the function module LDB_PROCESS, its selection screenis not displayed. Instead, you fill the selections using the interface parameters of the functionmodule. The logical database does not trigger any GET events in the calling program, butpasses the data back to the caller in callback routines. Calling a logical database usingLDB_PROCESS thus decouples the actual data retrieval from the preceding selection screenprocessing and the subsequent data processing.

There is no need to adapt a logical database for use with LDB_PROCESS, except in thefollowing cases: If you do not adapt a logical database, it is not possible to use the functionmodule to call the same logical database more than once. The PAI subroutine is not called whenyou use LDB_PROCESS. This means that none of the checks for selections programmed in itare performed. You can work around these restrictions by including the subroutinesLDB_PROCESS_INIT and LDB_PROCESS_CHECK_SELECTIONS [Page 1269] in thedatabase program.

Runtime BehaviorThe subroutines in the logical database are called in the following sequence when you call thefunction 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 databaseto an executable program [Page 1230] are called, neither does the runtime environment triggerany reporting events in the calling program. Instead, the PUT statements in the logical databasetrigger actions in the function module that call callback routines in the calling program. In otherwords, the function module catches the events that are otherwise processed by the runtimeenvironment.

Parameters of LDB_PROCESSThe function module has the following import parameters:

• LDBNAME

Page 3: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Calling a Logical Database Using aFunction Module

December 1999 1235

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 mustalready be assigned to the database program of the logical database. The data is passedin 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 forwhich dynamic selections are allowed. The data type of the parameter RSDS_TEXPR isdefined in the type group RSDS. The data is passed in the same way as when you usethe 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 logicaldatabase for which dynamic selections are allowed. The data type of the parameter isthe deep internal table RSFS_FIELDS, defined in the type group RSFS. The componentTABLENAME contains the name of the node and the deep component FIELDS containsthe 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, andwhen 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 ofthe logical database. The data type of the parameter corresponds to the structureRSPARAMS in the ABAP Dictionary. The data is passed in the same way as when youuse 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 inSELECTIONS and EXPRESSIONS overwrite values for the same field in VARIANT.

Read Depth and Callback RoutinesWhen you link a logical database with an executable program, the GET statements determine thedepth 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 nodefor which you request data, a callback routine can be executed at two points. These correspondto 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. Acallback routine is a subroutine in the calling program or another program that is to be executedat the required point.

For the GET event, the callback routine is executed directly after the data has been read for thenode, and before the subordinate nodes are processed. For the GET_LATE event, the callbackroutine is processed after the subordinate nodes have been processed.

The line type of the table parameter CALLBACK is the flat structure LDBCB from the ABAPDictionary. It has the following components:

Page 4: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Calling a Logical Database Using a Function Module

1236 December 1999

• 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 GETevent.

• GET_LATE

A flag (contents X or SPACE), to call the corresponding callback routine at the GETLATE 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 orGET_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 followingmeaning:

• <node> contains the name of the node.

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

• <evt> contains G or L, for GET or GET LATE respectively. This means that thesubroutine 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 whenthe subroutine is called. If it has the value SPACE when the subroutine ends, this flagsthat the subordinate nodes of the logical database should not be processed in thefunction module LDB_PROCESS. This is the same as leaving a GET event block usingCHECK [Page 1015] in an executable program. If this prevents unnecessary data frombeing read, it will improve the performance of your program.

Page 5: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Calling a Logical Database Using aFunction Module

December 1999 1237

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 thesubroutine 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] ofthe database program can trigger this exception. The error message is placed in theusual system fields SY-MSG... [Page 486].

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

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.

Page 6: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Calling a Logical Database Using a Function Module

1238 December 1999

APPEND SELTAB_WA TO SELTAB.ENDLOOP.

CALL FUNCTION 'LDB_PROCESS'EXPORTING

LDBNAME = 'F1S'VARIANT = ' 'EXPRESSIONS = TEXPRFIELD_SELECTION = FSEL

TABLESCALLBACK = CALLBACKSELECTIONS = SELTAB

EXCEPTIONSLDB_NOT_REENTRANT = 1LDB_INCORRECT = 2LDB_ALREADY_RUNNING = 3LDB_ERROR = 4LDB_SELECTIONS_ERROR = 5LDB_SELECTIONS_NOT_ACCEPTED = 6VARIANT_NOT_EXISTENT = 7VARIANT_OBSOLETE = 8VARIANT_ERROR = 9FREE_SELECTIONS_ERROR = 10CALLBACK_NO_EVENT = 11CALLBACK_NODE_DUPLICATE = 12OTHERS = 13.

IF SY-SUBRC <> 0.WRITE: 'Exception with SY-SUBRC', SY-SUBRC.

ENDIF.

FORM CALLBACK_SPFLI USING NAME TYPE LDBN-LDBNODEWA TYPE SPFLIEVT TYPE CCHECK TYPE C.

CASE EVT.WHEN 'G'.

WRITE: / WA-CARRID, WA-CONNID, WA-CITYFROM, WA-CITYTO.ULINE.

WHEN 'L'.ULINE.

ENDCASE.ENDFORM.

FORM CALLBACK_SFLIGHT USING NAME TYPE LDBN-LDBNODEWA TYPE SFLIGHTEVT TYPE CCHECK TYPE C.

WRITE: / WA-FLDATE, WA-SEATSOCC, WA-SEATSMAX.ENDFORM.

The program is written to read data using the logical database F1S. The structure ofF1S is:

Page 7: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Calling a Logical Database Using aFunction Module

December 1999 1239

SBOOKSBOOK

SFLIGHTSFLIGHT

SPFLISPFLI

A program-specific selection screen is defined at the beginning of the program. Thisrequires the TABLES statement. Next, the required variables are defined for theinterface.

The internal table CALLBACK is filled so that various callback routines are called inthe program for the two nodes SPFLI and SFLIGHT. For SPFLI, the routine is to becalled 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 selectiontable 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 callbackroutines. The interface parameter WA is fully typed, so you can address theindividual components of the work areas. The events GET and GET LATE arehandled differently in CALLBACK_SPFLI.

The beginning of the list output might look like this:

Page 8: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Calling a Logical Database Using a Function Module

1240 December 1999

Page 9: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing Logical Databases

December 1999 1241

Editing Logical DatabasesYou edit logical databases using the Logical Database Builder in the ABAP Workbench. To startthe Logical Database Builder, use Transaction SE36 or SLDB, or choose Tools → ABAPWorkbench, followed by Development → Programming environment → Logical Database Builder.You can also start it by forward navigation from the Repository Browser or other ABAPWorkbench tools.

In the Logical database field, you can enter a name of up to 20 characters. The name may alsocontain 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 onlydelete a logical database if it is not linked to an executable program. Even if a logical database isnot linked to any executable programs, it can still be used by a program that calls it using thefunction module LDB_PROCESS. Before deleting one, you should therefore check that it is notstill in use. However, the Where-used list function only shows where a logical database isassigned to an executable program.

You can select the individual components of the logical database directly. When you are editinga logical database, two arrow icons appear in the application toolbar that allow you to navigatebackwards and forwards between the most important components. You can also use the normalGoto 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]

Page 10: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Creating a Logical Database

1242 December 1999

Creating a Logical DatabaseTo create a new logical database, you should follow the procedure below. The Logical DatabaseBuilder then saves you work by using components that you have already defined to generateproposals for other components. Some of the most important attributes of a logical database areset when you define its structure. When you have defined the structure, the Logical DatabaseBuilder automatically generates a proposal for the selection include. The system then generatesan input mask for the database program, based on the structure of the logical database and theselections.

These generated proposals allow you to create a working logical database quickly. However,you must program refinements such as authorization checks and performance optimizationyourself.

Procedure for Creating a Logical Database1. 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 logicaldatabase. Enter the node name and its attributes. There are three different types ofnodes:

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

� Data types from the ABAP Dictionary: The node may refer to any data type inthe ABAP Dictionary [Page 105]. The node name and the name of the data typedo 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 atype group in the ABAP Dictionary. Enter the name of the type group in thecorresponding field. You must choose Other types before specifying this type.Data types in type groups were the forerunners of real data types in the ABAPDictionary. Wherever possible, you should use ABAP Dictionary data types.They have all of the semantic properties of their underlying data elements. Thisis 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 ABAPDictionary for the relevant table or data type.

1. The structure editor of the Logical Database Builder appears. On the left is the name ofthe root node, followed by a code for the node type: T for a database table, S for a ABAPDictionary type, and C for a type from a type group. The new logical database now has astructure 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 onwhich you can enter a search help for the logical database as described under EditingSearch 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.

Page 11: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Creating a Logical Database

December 1999 1243

When you have confirmed the dialog box, a list appears, on which you can select all ofthe nodes that you want to use for field selections or dynamic selections. The fields thatyou select are included in the source code generated by the system for the selectioninclude.

5. The generated selection include is displayed in the ABAP Editor. You can change it asdescribed 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 logicaldatabase. The database program is generated from the structure and the selectioninclude. It has a modular structure, consisting of several include programs and all of thenecessary 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 asdescribed in Editing the Database Program [Page 1251].

8. If you repeatedly choose Previous screen (left arrow in the application toolbar), you candisplay and change the general attributes of the logical database.

9. Finally, you can maintain optional selection texts and documentation.

Page 12: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Processing the Structure

1244 December 1999

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

Displaying the StructureThe 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 Cfor 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 individualsubtrees. You can display the attributes of a node by double-clicking it. To display the structureof a node, that is, the components of its data type, place the cursor on the node and chooseDisplay table fields.

The PUT routine function allows you to display the subroutine PUT_<node>. For this to work, thesubroutine must be contained in its own include that follows a particular naming convention. Forfurther 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 editorconsists at first only of its logical name, with which it is declared in the database programusing the TABLES or NODES statement. To define the node fully, double-click it. Youcan then enter its type, the name of the data type from the ABAP Dictionary to which itrefers, and its short text.

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

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

Page 13: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Processing the Structure

December 1999 1245

Page 14: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing a Search Help

1246 December 1999

Editing a Search HelpA search help is a ABAP Dictionary object used to define possible values (F4) help. There aretwo kinds of search help - elementary and collective. An elementary search help uses a searchpath to determine the possible entries. A collective search help consists of two or moreelementary 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 Searchhelps from the initial screen of the Logical Database Builder or use the navigation function fromanother component.

Here, you can assign a search help to the logical database by choosing from a list. You can alsodelete 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 itscontent. For example, if you create a logical database that reads creditor records, the creditornumber should be one of the output fields of the search help. The contents of the output fields ofthe 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 eitheruse 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 selectioninclude using the addition AS SEARCH PATTERN. The system interprets the user’s input on theselection screen and reads the value list from the database. The values are made available tothe database program in the internal table <ldb>_SP, and the subroutine PUT_<ldb>_SP iscalled instead of PUT_<root>. <ldb> is the name of the logical database, and <root> is the nameof the root node. This subroutine can use the value list in <ldb>_SP to read the actual data andtrigger the GET <root> event using the PUT_<root> statement.

Page 15: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing Selections

December 1999 1247

Editing SelectionsTo display or change the structure of a logical database, choose Selections from the initial screenof 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 logicaldatabase. You must not incorporate this include program in the database program using anINCLUDE statement. Instead, the runtime environment includes the selection include in thedatabase 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. Thisincludes SELECT-OPTIONS statements for all of the database tables in the structure (nodes withtype T). For each database table, the system proposes selection criteria [Page 718] for all of thefields in its primary key.

The SELECT-OPTIONS statements are commented out, and contain question marks instead ofthe names of the selection criteria. For each selection criterion that you want to use, you mustenter the name and delete the comment character (*).

If a search help is specified for the logical database, the system also generates a correspondingPARAMETERS statement with the addition AS SEARCH PATTERN. A group box entitledSelection using search help then appears on the selection screen with input fields for the searchhelp ID and the search string. There is also a pushbutton for complex search helps. If youchoose this function, you can enter multiple selections for each field.

Finally, SELECTION-SCREEN statements are generated for dynamic selections and fieldselections 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 selectionscreen:

• 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 theselection include, you must use the addition FOR NODE or FOR TABLE in thePARAMETERS statement. You can use NODE for all node types. You can only useTABLE for nodes with type T. When the selection screen is generated, the system onlygenerates fields for the nodes declared in the executable program in the NODES orTABLES 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, youcan use TABLE instead of NODE. The user can then decide at runtime the componentsof the node for which he or she wants to enter selections. Dynamic selections requirespecial 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 canuse TABLE instead of NODE. In an executable program, you can use a field list in theGET 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

Page 16: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing Selections

1248 December 1999

passed accordingly. Dynamic selections require special handling in the databaseprogram.

• 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 parametersas specified in <f>. This allows an executable program to work with an appropriateselection screen version.

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

Suppose the logical database TEST_LDB has the following structure:

LFC1LFC1

LFB1LFB1

LFA1LFA1

BKPFBKPF

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.

Page 17: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing Selections

December 1999 1249

* 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 isdefined 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 givennames. An additional parameter PSTIDA is declared and linked to the node BKPF.Dynamic selections are defined for the tables LFA1 and LFB1. Field selections aredefined for tables LFB1 and LFC1.

Page 18: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing Selections

1250 December 1999

Page 19: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing the Database Program

December 1999 1251

Editing the Database ProgramTo display or change the database program of a logical database, choose Database programfrom the initial screen of the Logical Database Builder, or navigate to the database program fromanother component. The name of the program is SAPDB<ldb>, where <ldb> is the name of thelogical database.

Structure of the Database ProgramWhen 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 ofgenerated include programs [Page 449]. This makes their structure easy to follow, even if thelogical database has a large number of nodes. Older logical databases may not use includesand consist instead only of a main program.

Main program SAPDB<ldb>

INCLUDE DB<ldb>TOP.

INCLUDE DB<ldb>XXX.

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

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

INCLUDE DB<ldb>F001.

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

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

......

Include programs

FUNCTION <name>....

ENDFUNCTION.

FUNCTION <name>....

ENDFUNCTION.

FUNCTION <name>....

ENDFUNCTION.

FUNCTION <name>....

ENDFUNCTION.

FORM PUT_<node>....

ENDFORM.

FORM PUT_<node>....

ENDFORM.

...

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:

Page 20: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing the Database Program

1252 December 1999

• DB<ldb>001, DB<ldb>002, …

Contain the subroutines PUT_<node> and AUTHORITY_CHECK_<node> for theindividual nodes of the logical database.

• DB<ldb>FXXX

Contains most of the remaining subroutines for initialization, PBO, and PAI of theselection 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 theautomatically-generated include programs and subroutines. However, you can define extraincludes and subroutines, and change the ABAP statements used to read data. User-definedinclude programs must follow the naming convention DB<ldb>F<nnn> to ensure that they aretransported with the logical database.

Full Example of a Generated ABAP Program

Suppose the logical database TEST_LDB has the following structure:

LFC1LFC1

LFB1LFB1

LFA1LFA1

BKPFBKPF

All of the nodes are database tables. Suppose the following selections are defined inthe 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 includeprograms are listed below. The program also contains some user and performancehints as comment lines, but these are not included here.

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

Page 21: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing the Database Program

December 1999 1253

TEST_LDB*----------------------------------------------------------*

INCLUDE DBTEST_LDBTOP . " headerINCLUDE DBTEST_LDBXXX . " all system routines* INCLUDE DBTEST_LDBF001 . " user defined include

Include Program DBTEST_LDBTOPPROGRAM 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 databaseprogram* !!!!! DO NOT CHANGE MANUALLY !!!!!*----------------------------------------------------------*

INCLUDE DBTEST_LDBN001 . " Node LFA1INCLUDE DBTEST_LDBN002 . " Node LFB1INCLUDE DBTEST_LDBN003 . " Node LFC1INCLUDE DBTEST_LDBN004 . " Node BKPFINCLUDE DBTEST_LDBFXXX . " INIT, PBO, PAIINCLUDE DBTEST_LDBSXXX . " 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. "AUTHORITY_CHECK_LFA1

Page 22: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing the Database Program

1254 December 1999

Include Programs DBTEST_LDB002 and DBTEST_LDB003Similar 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.

Page 23: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing the Database Program

December 1999 1255

* 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 processingo.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 SY-SUBRC

MSG LIKESYMSG.

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 '*'.

Page 24: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing the Database Program

1256 December 1999

* 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 thequestion marks replaced by appropriate expressions. When you check the syntax of theprogram, all of the include programs that conform to the naming convention and the selectioninclude are also checked.

In the subroutines PUT_<node>, SELECT statements are generated with conditions in theirWHERE clauses for the primary key fields of the node. Note that these statements do notobserve the performance rules [Page 1148] for Open SQL statements. In particular, thePUT_<node> subroutines for a subtree a structure form nested SELECTED loops, which youshould avoid. Instead, you can buffer the data in internal tables, and pass it to the applicationprogram 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 generatesthe corresponding statements in the subroutine PUT_NODE, and adjusts the automatically-generated SELECT statements, as in the example for the node BKPF. The following sectionsexplain how you can process user input in the dynamic selections and column specifications afterGET statements.

Generated Data Objects and SubroutinesSome internal tables and other subroutines are automatically generated, and can be used in theprogram.

Page 25: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Editing the Database Program

December 1999 1257

• The internal table GET_EVENT contains the nodes of the logical database that arerequested 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. TheKIND 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, asubordinate node is addressed in GET or GET LATE.

• KIND = ' ': Node is addressed neither in GET nor in GET LATE. No subordinatenode is addressed either.

• The subroutines BEFORE_EVENT, AFTER_EVENT, and PUT_<ldb>_SP are generatedas comments in the database program (see example above). You can modify them andactivate them by deleting the comment characters (*). BEFORE_EVENT is called beforethe event specified in the parameter EVENT is processed. AFTER_EVENT is called afterthe event specified in the parameter EVENT is processed. PUT_<ldb>_SP is called forprocessing values instead of PUT_<root> if a search help is used for selection. <root> isthe 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]

Page 26: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Dynamic Selections in the Database Program

1258 December 1999

Dynamic Selections in the Database ProgramThe 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>, youmust use the data object DYN_SEL. The data object DYN_SEL is automatically generated in thelogical 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 thedatabase 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.

Page 27: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Dynamic Selections in the DatabaseProgram

December 1999 1259

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

CLAUSESCLAUSES contains the dynamic selections entered by the user (or possibly program-internalselection 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 fordynamic selections. For each of these database tables, the WHERE_TAB tables contain theselection criteria of the dynamic selections. The WHERE_TAB tables have a format that allowsyou to use them directly in dynamic WHERE clauses.

To use WHERE_TAB in the logical database, you must program the dynamic WHERE clause foreach node <node> designated for dynamic selection in the corresponding subroutinePUT_<node>. For this, the corresponding internal table WHERE_TAB for <node> must be readfrom the data object DYN_SEL. The following example shows how you can use a local dataobject in the subroutine for this purpose:

Suppose the database table SCARR is the root node of the logical database ZHKand 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 thedynamic 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-TABLENAMEINTO DYNAMIC_SELECTIONS.

FLAG_READ = 'X'.ENDIF.

SELECT * FROM SCARRWHERE CARRID IN S_CARRIDAND (DYNAMIC_SELECTIONS-WHERE_TAB).

Page 28: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Dynamic Selections in the Database Program

1260 December 1999

PUT SCARR.

ENDSELECT.

ENDFORM.

The line of the internal table DYN_SEL-CLAUSES that contains the value SCARR incolumn DYN_SEL-CLAUSES-TABLENAME is read into the local structureDYNAMIC_SELECTIONS. The STATICS statements and the FLAG_READ fieldensure that table DYN_SEL is only read once during each program execution. Thetable DYNAMIC_SELECTIONS-WHERE_TAB is used in the dynamic WHEREclause.

Each executable program that uses ZHK as its logical database and contains aNODES or TABLES statement for SCARR or SPFLI now offers dynamic selectionsfor the fields in table SCARR on its selection screen. The dynamic WHERE clausemeans that the logical database only reads the lines that satisfy the selectionconditions on the selection screen and in the dynamic selections.

TEXPRTEXPR contains the selections of the dynamic selections in an internal format (Polishnotation).You can use this format with function modules FREE_SELECTIONS_INIT andFREE_SELECTIONS_DIALOG in order to work with dynamic selections within a program (formore information, see the documentation of these function modules).

TRANGETRANGE contains the selections from the dynamic selection as RANGES tables [Page 719] thatyou 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 designatedfor dynamic selections. For each of these nodes, the FRANGE_T tables contain the selectioncriteria of the dynamic selections in the format of RANGES tables. FRANGE_T contains aFIELDNAME column that contains the fields of the node for which the RANGES tables aredefined. 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 thosestored in the WHERE clause format. The following example shows how you can use local dataobjects of the corresponding subroutine PUT_<node> to work with TRANGE:

Suppose the database table SCARR is the root node of the logical database ZHKand 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 thedynamic selection as follows:FORM PUT_SCARR.

Page 29: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Dynamic Selections in the DatabaseProgram

December 1999 1261

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-TABLENAMEINTO DYNAMIC_RANGES.

DYNAMIC_RANGE1-FIELDNAME = 'CARRNAME'.READ TABLE DYNAMIC_RANGES-FRANGE_T

WITH KEY DYNAMIC_RANGE1-FIELDNAMEINTO DYNAMIC_RANGE1.

DYNAMIC_RANGE2-FIELDNAME = 'CURRCODE'.READ TABLE DYNAMIC_RANGES-FRANGE_T

WITH KEY DYNAMIC_RANGE2-FIELDNAMEINTO DYNAMIC_RANGE2.

FLAG_READ = 'X'.

ENDIF.

SELECT * FROM SCARRWHERE CARRID IN S_CARRIDAND CARRNAME IN DYNAMIC_RANGE1-SELOPT_TAND CURRCODE IN DYNAMIC_RANGE2-SELOPT_T.

PUT SCARR.

ENDSELECT.

ENDFORM.

The line of the internal table DYN_SEL-TRANGE that contains the value 'SCARR' incolumn DYN_SEL-CLAUSES-TABLENAME is read into the local tableDYNAMIC_RANGES. The nested tables DYNAMIC_RANGES-FRANGE_T are readinto the local tables DYNAMIC-RANGE1 and DYNAMIC-RANGE2 according to thecontents of DYNAMIC_RANGES-FIELDNAME. The STATICS statements and theFLAG_READ field assure that the tables are read only once each time theexecutable program is executed. After the READ statements, the nested tablesSELOPT_T of the local tables contain the RANGES tables for the columnsCARRNAME and CURRCODE of the database table SCARR.

The tables SELOPT_T are used in the SELECT statement directly as selectiontables. Besides CARRNAME, CURRCODE and the primary key, there are no furthercolumns in the database table SCARR. Therefore, this logical database has thesame function as the logical database in the above example using the CLAUSEScomponent.

Page 30: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Field Selections in the Database Program

1262 December 1999

Field Selections in the Database ProgramThe 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 correspondingsubroutine PUT_<node>, instead of having to use SELECT * to select all columns. This allowsyou to minimize the amount of data transferred from the database [Page 1153], which can oftenimprove performance.

For each node for which field selection is allowed, you can specify the columns that you want toread using the FIELD addition to the GET statement in the executable program or in theFIELD_SELECTION parameter of the function module LDB_PROCESS. The database programof the logical database can access the names of the columns in the data objectSELECT_FIELDS. The data object SELECT_FIELDS is automatically generated in the logicaldatabase 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 availablein 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. Eachline of the TABLENAME column contains the name of a node that is designated for fieldselection. The table FIELDS contains the columns specified in the GET statements in theapplication program for each of these nodes. The FIELDS table have a format that allows you touse 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 listFIELDS in the SELECT clause of the SELECT statements in the subroutine PUT_<node> foreach node <node> for which field selections are allowed. To do this, you must read thecorresponding internal table from the internal table SELECT_FIELDS. The following exampleshows 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 ZHKand that SPFLI is its only subordinate node.

Page 31: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Field Selections in the DatabaseProgram

December 1999 1263

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 fieldselections 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 SPFLIWHERE CARRID = SCARR-CARRIDAND CONNID IN S_CONNID.

PUT SPFLI.

ENDSELECT.

ENDFORM.

The line of the internal table SELECT_FIELDS that contains the value 'SCARR' incolumn SELECT_FIELD-TABLENAME is read into the local structure FIELDLISTS.The STATICS statements and the FLAG_READ field assure that the table DYN_SELis read only once each time the executable program is run. The table FIELDLISTS-FIELDS is used in the dynamic SELECT clause.

An executable program to which the logical database HKZ is linked could now, forexample, contain the following lines:TABLES SPFLI.

GET SPFLI FIELDS CITYFROM CITYTO.

...

The FIELDS option of the GET statement defines which fields besides the primarykey 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 LIKE SELECT_FIELDS,

ITAB_L LIKE LINE OF ITAB,JTAB LIKE ITAB_L-FIELDS,JTAB_L LIKE LINE OF JTAB.

START-OF-SELECTION.

Page 32: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Field Selections in the Database Program

1264 December 1999

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 addedautomatically to the specified columns.

Page 33: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Search Helps in the Database Program

December 1999 1265

Search Helps in the Database ProgramThe 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 wherethey can be used by the database program. The subroutine PUT_<ldb>_SP is then calledinstead 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 internaltable to make the actual database access more efficient. It triggers the event GET <root> with thestatement PUT_<root>, where <root> is the name of the root node. It is often useful to call thesubroutine PUT_<root> from PUT_<ldb>_SP. PUT_<root> can then select the data and triggerthe corresponding GET event in the PUT <root> statement. However, for technical reasons, thePUT <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 isdisplayed as a comment in the generated source code of the database program. How the tablesare 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 thesearch 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 whichindicate that the following tables and fields were created in addition to those listedunder :

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 outputfields of the search help. The hit list is available to the database programthrough the table ZZF_SP.

Internal table SP_FIELDS:If a collective search help is assigned to the logical database, anelementary search help will normally only fill a selection of the outputfields of the collective search help. The program can find out from tableSP_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 wasassigned to the field in SP_FIELDS-FIELDNAME by the search help.

Page 34: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Search Helps in the Database Program

1266 December 1999

Internal table SP_TABLES:If the search help contains fields from different tables, the program canfind out from the table SP_TABLES which ones are covered by thesearch 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 wasassigned 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 atable in the logical database structure (for example, the first characterstands for the root node). The contents of the individual positions havethe following meaning for the corresponding node:

– 'X': The node is addressed in the application program using the GETstatement. The search help has assigned values for the key fields toSP_<ldb>.

– 'R': The node is addressed in the application program using the GETstatement. The search help has not assigned values for the key fieldsto SP_<ldb>.

– 'M': The node is not addressed in the application program using theGET statement, but the search help has assigned values for the keyfields to SP_<ldb>.

– ' ': The node is not addressed in the application program using theGET statement, and the search help has not assigned values for thekey fields to SP_<ldb>.

If the user selects all suppliers in the search help on the selection screen whose sortfield begins with ABC, and this applies to customer numbers 17, 125, and 230, theabove 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 activatedas follows in order to use the entries from the internal table ZZF_SP:FORM PUT_ZZF_SP.

Page 35: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Search Helps in the Database Program

December 1999 1267

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_SPWHERE KUNNR = ZZF_SP_KUNNR.

PUT KNA1.ENDSELECT.

ENDFORM.

The system uses the table GET_EVENTS to check whether the application programcontains a GET statement for KNA1, or whether the search help has assigned valuesfor the key fields. If this is true, the system calls PUT_KNA1_SP. This contains aSELECT loop for KNA1, in which the lines corresponding to the key fields in ZZF_SPare 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 fromZZF_SP. The program uses the table GET_EVENTS to check whether theapplication program contains a GET statement for KNA1. If so, it calls the subroutinePUT_KUNNR. Here, the data from KNA1 is read according to the selection tableSKUNNR, and the PUT KNA1 statement is executed.

If the database access uses a search help, you should of course, use dynamic selections andfield selections.

You can also use search helps to improve performance. You can program different databaseaccesses depending on the tables and fields that are used and filled using the internal tablesGET_EVENTS, SP_FIELDS, and SP_TABLES. For example, you can use a view or a join and

Page 36: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Search Helps in the Database Program

1268 December 1999

place the entries in internal tables, which you can process later and then trigger thecorresponding GET events.

Page 37: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Independent Calls and the DatabaseProgram

December 1999 1269

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

LDB_PROCESS_INITIf you want to call a logical database more than once in succession, the database program mustcontain 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 SUBRChas been set to 0, the logical database can perform the initialization routines required to allow itto be called more than once. If the parameter SUBRC is not set to 0, the function moduleLDB_PROCESS triggers the exception LDB_NOT_REENTRANT.

LDB_PROCESS_CHECK_SELECTIONSWhen you call a logical database using LDB_PROCESS, there is no selection screenprocessing. 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 candefine 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 havebeen filled from the interface parameters of LDB_PROCESS. If the parameter SUBRC is not setto 0, the function module LDB_PROCESS triggers the exceptionLDB_SELECTIONS_NOT_ACCEPTED. You can assign a message to the structured parameterMSG. This is available to the caller of the function module in the system fields SY-MSG... Theeight components of MSG contain the message type, ID, and number, and up to four messagevariables.

Page 38: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Editing Other Components

1270 December 1999

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

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

DocumentationLogical databases are reusable modules that can be used by a wide range of applicationprograms. You should therefore ensure that they are adequately documented.

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

Checking Logical DatabasesTo check whether a logical database is correct and complete, choose Check from the initialscreen 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

Page 39: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Improving Performance

December 1999 1271

Improving PerformanceChanges to logical databases are immediately visible in all of the programs that use them. Thisallows you to tune the performance [Page 1148] of the Open SQL statements for all of theseprograms in one place. One way of improving performance is to allow the user to specify exactlywhat 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 valuesand 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 thedata selection itself.

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

• The numerical relationship between the table contents at different levels of the structureis very important.

If, for example, one line of a database table at one level of the structure includes exactlyone line of the database table at the next level (case A), other optimizations may makemore 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 aninternal 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, whileother use all of its nodes. In this case, you have the following options for improving theperformance of individual reports:

− You can use the table GET_EVENTS in the logical database program. When you havegenerated an executable program that uses the logical database, this table containsinformation about each node in the structure, and whether the corresponding GETstatement 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 inthe corresponding SELECT statements instead of having to read the entire line.

Page 40: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Improving Performance

1272 December 1999

Page 41: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Using Contexts

December 1999 1273

Using ContextsContexts are objects within the ABAP Workbench that enable you to store details about therelationships between data. You use them in your ABAP programs to derive data which isdependent on a small number of key fields.

Contexts allow you to

• store processing logic from application programs in context programs, reducing thecomplexity 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]

Page 42: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

What are Contexts?

1274 December 1999

What are Contexts?Within the large quantities of data in the R/3 System database, there are always smaller sets ofbasic data that you can use to derive further information. In a relational database model, forexample, these are the key fields of database tables.

When an application program requires further information in order to continue, this is often foundin these small amounts of basic data. The relational links in the database are often used to readfurther data on the basis of this basic data, or further values are calculated from it using ABAPstatements.

It is often the case that certain relationships between data are always used in the same form toget further data, either within a single program or in a whole range of programs. This means thata particular set of database accesses or calculations is repeatedly executed, despite the fact thatthe result already exists in the system. Contexts provide a way of avoiding this unnecessarysystem load.

Contexts are objects within the ABAP Workbench, consisting of key input fields, the relationshipsbetween these fields, and other fields which can be derived from them. Contexts can link thesederived fields by foreign key relationships between tables, by function modules, or by othercontexts. You define contexts abstractly in the ABAP Workbench (Transaction SE33), and useinstances of them as runtime objects in your ABAP programs.

In the ABAP Workbench, contexts consist of fields and modules. Their fields are divided into keyfields 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 theexample context DEMO_TRAVEL, this would be CONTEXT_S_DEMO_TRAVEL).

• in a generated executable program, with the name CONTEXT_X_<context name>.Forthe 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 oneinstance of the same context. The application program supplies input values for the key fields inthe context using the SUPPLY statement, and can query the derived fields from the instanceusing the DEMAND statement.

Each context has a cross-transaction buffer on the application server. When you query aninstance for values, the context program searches first of all for a data record containing thecorresponding 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 andwrites the resulting data record to the buffer.

Whenever, in a program, new key fields are entered into an instance that has already beenpreviously supplied with them, the system invalidates all affected values that have already beenderived. These values are only re-supplied the next time they are queried.

Page 43: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

The Context Builder in the ABAPWorkbench

December 1999 1275

The Context Builder in the ABAP WorkbenchNormally you will use existing contexts within your R/3 System, and only use the Context Builderto familiarize yourself with them and test them (see Finding and Displaying a Context [Page1299]). However, if no suitable context already exists in the system, you can use the ContextBuilder to create your own.

This section describes how to use the Context Builder (Transaction SE33) in the ABAPWorkbench.

Creating and Editing a Context [Page 1276]

Testing a Context [Page 1288]

Buffering Contexts [Page 1290]

Page 44: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Creating and Editing a Context

1276 December 1999

Creating and Editing a ContextTo create a context, call the Context Builder (Transaction SE33) and enter a name for your newcontext in the Context field. In the Sub-objects group box, select Fields and modules, thenchoose Create.

On the next screen, you enter the attributes for your context:

When you have saved the attributes, choose Fields and modules. The context maintenancescreen is then displayed.

FieldsName Ref. Field / type

ModulesName Typ Table/Module

Parameter I/O Field name

There are three tables on this screen, in which you enter the Fields [Page 1293], Modules [Page1295] and Interfaces [Page 1297] in your context. You can enlarge each of these tables bychoosing Enlarge .

The contents of the individual tables are interdependent, and are filled automatically to a certainextent.

The next three sections use simple examples to demonstrate how you can create contexts usingdifferent modules.

Using Tables as Modules [Page 1278]

Using Function Modules as Modules [Page 1281]

Using Contexts as Modules [Page 1285]

Page 45: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Creating and Editing a Context

December 1999 1277

Page 46: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Using Tables as Modules

1278 December 1999

Using Tables as ModulesThe following example demonstrates how to create a context called DOCU_TEST1, which hastwo modules with type table. The tables used are SPFLI and SFLIGHT from the data modelBC_TRAVEL.

1. Enter SPFLI in the Name or Table/Module column of the Modules [Page 1295] table andchoose Enter. The system then fills all of the tables of the context maintenance screenwith unique entries as follows:

FieldsName Type

ModulesName Typ Table/module

Parameter I/O Field name

CITYFROMCARRIDCONNID

AIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTANCEDISTIDFLTYPE

SPFLI-CITYFROMSPFLI-CARRID

SPFLI-CITYTO

SPFLI-FLTIME

SPFLI-ARRTIME

SPFLI-DISTID

SPFLI-CONNID

SPFLI-AIRPFROM

SPFLI-AIRPTO

SPFLI-DEPTIME

SPFLI-DISTANCE

SPFLI-FLTYPE

SPFLI SPFLI

CITYFROMCARRIDCONNID

AIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTANCEDISTIDFLTYPE

CITYFROMCARRIDCONNID

AIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTANCEDISTIDFLTYPE

Module SPFLI: Demo table

All of the columns of table SPFLI are used as fields in the context. The interface ofmodule 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 thescreen:

Page 47: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Using Tables as Modules

December 1999 1279

FieldsName

ModulesName Typ Table/module

Parameter I/O Field name

CITYFROMCARRIDCONNID

AIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTANCEDISTIDFLTYPE

SPFLI-CITYFR

Ref. Field/typeSPFLI-CARRID

SPFLI-CITYTO

SPFLI-FLTIME

SPFLI-ARRTIM

SPFLI-DISTID

SPFLI-CONNID

SPFLI-AIRPFROM

SPFLI-AIRPTO

SPFLI-DEPTIME

SPFLI-DISTANC

SPFLI-FLTYPE

SPFLI

FLDATECARRIDCONNID

PRICECURRENCYPLANETYPESEATSMAXSEATSOCCPLAYMENTSU

FLDATECARRIDCONNID

PRICECURRENCYPLANETYPESEATSMAXSEATSOCCPLAYMENTS

Module SFLIGHT: Demo table

CARRIDFLDATEPRICECURRENCYPLANETYPESEATSMAXSEATSOCCPAYMENTSUM

SFLIGHT- FLDAT

SFLIGHT-PLANE

SFLIGHT-SEATS

SFLIGHT-CARR

SFLIGHT-PRICESFLIGHT-CURR

SFLIGHT- SEATS

SFLIGHT-PAYM

SFLIGHT SFLIGHTSPFLI

All of the columns in SFLIGHT which are not already contained in SPFLI are now alsoused in the context. The interface for module SFLIGHT shows that the key fieldsCARRID, 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 valuesare derived within the context.

Page 48: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Using Tables as Modules

1280 December 1999

Display area

Airline

Date

Flight number CONN

CONN

Connections for

Flights demo tableCARR

CARR

FLDA

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 inprograms (see Using Contexts in ABAP Programs [Page 1298]).

Page 49: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Using Function Modules as Modules

December 1999 1281

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

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

Import parameter Ref. Field/structureSFLIGHT-SEATSMAX

Ref. type

SFLIGHT-SEATSOCCV1V2

Export parameter Reference field/structureSFLIGHT-SEATSOCCRESULT

and the following source code:

FUNCTION SUBTRACTION. RESULT = V1 - V2.ENDFUNCTION.

The function module subtracts import parameter V2 from the other import parameter V1, andreturns 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 screenas follows:

Page 50: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Using Function Modules as Modules

1282 December 1999

FieldsName Type

ModulesName Typ Table/module

Parameter I/O Field name

SEATSOCC_1SEATSMAXSEATSOCC

SFLIGHT-SEATSOSFLIGHT-SEATSMSFLIGHT-SEATSO

SUBTRAC SUBTRACTION

RESULTV1V2

SEATSOCC_1SEATSMAXSEATSOCC

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 theSUBTRACTION module shows that the import parameters V1 and V2 are assigned tothe key fields SEATSMAX and SEATSOCC, and that the export parameter RESULT isassigned to the dependent field SEATSOCC_1.

2. You do not have to adopt these generated names. You can, instead, overwrite thecontext field names in the Fields [Page 1293] and Modules [Page 1295] table. Forexample, as follows:

Page 51: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Using Function Modules as Modules

December 1999 1283

FieldsName Ref. Field/type

ModulesName Typ Table/module

Parameter I/O Field name

FREEMAXOCC

SFLIGHT-SEATSOCSFLIGHT-SEATSMASFLIGHT-SEATSOC

SUBTRAC SUBTRACTION

RESULTV1V2

FREEMAXOCC

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 valuesare derived within the context.

Max. occupancy

Occupancy Test Function Module for

MAX

OCC

Display area

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 inprograms (see Using Contexts in ABAP Programs [Page 1298]).

Page 52: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Using Function Modules as Modules

1284 December 1999

Page 53: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Using Contexts as Modules

December 1999 1285

Using Contexts as ModulesThe following example demonstrates how to create a context called DOCU_TEST3, which usestwo other contexts, DOCU_TEST1 and DOCU_TEST2, as modules. DOCU_TEST1 andDOCU_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 theModules [Page 1295] table and choose Enter. The system fills the tables on the contextmaintenance screen as follows:

FieldsName

ModulesName TypTable/modu

Parameter I/O Field name

CITYFROMAIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTANCEDISTIDFLTYPE

SPFLI-CITYFRType

SPFLI-CITYTO

SPFLI-FLTIME

SPFLI-ARRTIM

SPFLI-DISTID

SPFLI-AIRFROM

SPFLI-AIRTO

SPFLI-DEPTIME

SPFLI-DISTANC

SPFLI-FLTYPE

FREEMAXOCC

SEATSOCC_2SEATSMAX_1SEATSOCC_1

Module DOCU_TEST2: Test for DFLDATEPRICECURRENCYPLANETYPESEATSMAXSEATSOCCPAYMENTSUM

SFLIGHT- FLDAT

SFLIGHT-PLANE

SFLIGHT-SEATS

SFLIGHT-PRICESFLIGHT-CURR

SFLIGHT- SEATS

SFLIGHT-PAYM

DOCU_TEST1DOCU_TEST2 DOCU_TES

DOCU_TES

SEATSMAX_1SEATSOCC_1SEATSOCC_2

SFLIGHT-SEATSSFLIGHT-SEATSSFLIGHT-SEATS

All fields from the two contexts are used as fields in this context. The system generatesthe names of the context fields.

2. You do not have to use all of the context fields. You can also change the context fieldnames in the Fields [Page 1293] and Modules [Page 1295] tables:

Page 54: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Using Contexts as Modules

1286 December 1999

FieldsName

ModulesName TypTable/modu

Parameter I/O Field name

CARRIDCONNIDFLDATESEATSMAXSEATSOCCFREE_SEATS

SPFLI-CARRIDRef. Field/type

SFLIGHT-FLDATE

SFLIGHT-SEATSO

SPFLI-CONNID

SFLIGHT-SEATSM

SFLIGHT-SEATSO

FLDATE

CARRIDCONNID

FLDATE

CARRIDCONNID

Module DOCU_TEST1: Test for D

DOCU_TEST1DOCU_TEST2 DOCU_TES

DOCU_TES

SEATSMAX SEATSMAXSEATSOCC SEATSOCC

In this example, we have kept the three key fields CARRID, CONNID and FLDATE, anddeleted all dependent fields apart from SEATSMAX, SEATSOCC and FREE_SEATS.The output fields from module DOCU_TEST1, SEATSMAX and SEATSOCC are used asinput fields for module DOCU_TEST2. The dependent field FREE_SEATS is filled fromthe 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 valuesare derived within the context.

Page 55: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Using Contexts as Modules

December 1999 1287

Display area

CONNID

CARRID

FLDATE

AirlineCARRID

Flight dateFLDATE

Flight numberCONNID SEATSMAX/SEATSOCC

Test for DocumentationDOCU TEST1

Test for DocumentationDOCU 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 inprograms (see Using Contexts in ABAP Programs [Page 1298]).

Page 56: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Testing a Context

1288 December 1999

Testing a ContextThis section describes how to test a context. It uses the context DOCU_TEST2 from the previousexample Using Function Modules as Modules [Page 1281].

To test a context, call the Context Builder (Transaction SE33) and enter the name of the contextyou wish to test in the Context field. Choose Test. If texts appear in a language other than thelogon language when you test the context, you must regenerate it once. Afterwards, thetranslated texts will appear.

The Context Builder: Testing screen is then displayed. To display the meanings of the variousicons, choose Legend.

F i e l d s Values M o d u l e s

Test Function Module for Cont Occupancy

Occpancy Max. occupancy

Icon Meaning in fields Meaning in modules

Value unknown Module cannot be activated Value calculable Module can be activated Value known Module activated

Module type

Table Function module Context

Actions per module

Display buffer contents

Network graphic

Legend

To test the context, enter values in the key fields of the context. Choose Enter to accept the inputvalues.

If you want to use a blank character (SPACE) as an input value for a field, click on the traffic lightsymbol on the left hand side of the field to change the status of the input field.

F i e l d s V a l u e s M o d u l e s

Test Function Module for Cont Occupancy

Occupancy Max. occupancy 500

345

Page 57: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Testing a Context

December 1999 1289

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

F i e l d s V a l u e s M o d u l e s

Test Function Module for Cont Occupancy

Occupancy Max. occupancy 500

345155

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

F i e l d s M o d u l e s

Test Function Module for Cont��

�� Test Function ModuOccupancy ��

Occupancy Max. occupancy

Page 58: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Buffering Contexts

1290 December 1999

Buffering ContextsThe principal aim of contexts is to avoid the repeated calculation of frequently-used data which isderived 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 databaseinterface or the SAP table buffer is that it is only periodically refreshed (every hour on thehour).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 youwant 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 isused. For more information about this buffer, see the keyword documentation forEXPORT/IMPORT TO/FROM SHARED BUFFER. The cross-transaction applicationbuffer can contain up to 128 context entries. These entries are structured using aprocess similar to LRU (Least Recently Used).

To display the contents of the context buffer on the current application server, chooseGoto → 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 areexported in bundles into the cross-transaction application buffer. The results of thevarious 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 forall modules in a context, using the context will not improve system performance, but ismerely a way of re-using program logic.

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

Construction of the BufferThe context buffer contains two buffer tables for each module:

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

Page 59: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Buffering Contexts

December 1999 1291

• The E buffer (external buffer), which assigns the derived values in the module to the keyvalues in the context. The E buffer is filled each time a query is made. The first time aquery is made using a particular combination of module input parameters, the results arewritten 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 thecombination already exists in the I buffer), the system writes the results to the E bufferalong with the context key values). It is therefore possible for the results of a particularcombination of module input parameters to appear more than once in the E buffer, sincedifferent 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 parametersof a module are either key fields or output parameters of another module. The entries in the Ebuffer for modules which depend on other, previous modules are the same as the I buffer entriesfor those previous modules. The buffering type of the E buffer for the dependent module is thesame as the lowest buffering type of any of the modules on which it depends. Thus, if one of theprevious modules has buffering type N, the system will not store any entries in the E buffer of thedependent module.

When you access the context buffer, either during testing or using the DEMAND statement, thesystem first searches in the E buffer of each module, followed by the I buffer. Access to the Ebuffer is more direct, and quicker than using the I buffer, which usually needs to be accessedmore often.

The inclusion of entries in the E buffer which have been queried more than once is anacceptance of data redundancy as the price for quicker access. The I buffer is a filter for the Ebuffer, only allowing redundant data when absolutely necessary. Together, the I and E buffersprovide 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 thisbuffering concept. Try to include as many relationships between data objects in asingle context for each program, rather than using several contexts in the sameprogram. You can also combine a group of contexts as modules of a single, largercontext. Within a context, the system buffers all intermediate results in an optimalform. If you are using separate contexts, there is no link between any of theindividual buffers.

Deleting a BufferYou can delete the contents of a context buffer as follows:

• in the Context Builder (Transaction SE33), choose Edit → Delete buffer → Local serverto 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 applicationservers.

You can use these functions when testing or buffering contexts.

• in ABAP programs, you can use the function modulesCONTEXT_BUFFER_DELETE_LOCAL and CONTEXT_BUFFER_DELETE to delete thebuffer 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 toensure that the contents of the context buffer are always current.

Page 60: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Buffering Contexts

1292 December 1999

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 updatemodule. You could use it as the last update call following the database changesbefore the COMMIT WORK statement. For more information about asynchronousupdate, see Programming Database Updates [Page 1312]

Page 61: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Fields

December 1999 1293

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

FieldsName

CARRIDCONNIDCITYFROMCOUNTRYFRAIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIME

SPFLI-CARRIDType

SPFLI-CITYFROM

SPFLI-AIRPFROM

SPFLI-AIRPTO

SPFLI-DEPTIME

SPFLI-CONNID

SPFLI-COUNTRYFR

SPFLI-CITYTO

SPFLI-FLTIME

SPFLI-ARRTIMEDISTIDFLTYPEDISTANCECARRNAMECURRCODENAME_FROMNAME_TO

SPFLI-DISTID

SCARR-CARRNAME

SAIRPORT-NAME

SPFLI-FLTYPESPFLI-DISTANCE

SCARR-CURRCODE

SAIRPORT-NAME

Text Default L/TAirlineFlight numberFromCountryDeparture airportToArrival airportFlight timeDeparture timeArrival timeDistance inCharterDistanceAirlineLocal currency Airport FROMAirport TO

LLLLLLLLLLLLLLLLL

These, in turn, can become input parameters for further modules. You can enter new modules inthe table directly, or fill it automatically by creating fields in the Modules [Page 1295] table. Youcan 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 orstructure or a type in a type group.

• Text

The short text for the field from the ABAP Dictionary.

• Default value

Page 62: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Fields

1294 December 1999

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

• Like

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

Page 63: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Modules

December 1999 1295

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

ModulesName

DEMO_CITIESSAIRPORT1SAIRPORT2SCARRSPFLI

Typ Text Msg P/T/NContext: GeograAirports 1Airports 2AirlineSchedule

PP

PPP

DEMO_CITIES

SAIRPORT

SPFLI

SAIRPORT

SCARR

Table/Module

33

No.

800

Variable 1

CARRID

EE

EEE

Messa

Modules have input and output parameters. Together, they form the Interfaces [Page 1297] ofthe 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 keyfields. Each individual module carries out its own part of that task. For example, one module usessome 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 inthe table directly, or fill it automatically by creating fields in the Fields [Page 1293] table. To editthe 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 areoutput parameters.

− a function module:

The import parameters of the function module are input parameters. The exportparameters of the function module are output parameters.

− another context:

The key fields of contexts are input parameters. The dependent fields of contexts areoutput fields.

Different modules can have the same type. This allows you to establish the samerelationships between different groups of fields.

• Table/Module

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

Page 64: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Modules

1296 December 1999

• 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 columnsVariable 1, ... , Variable 4, you can specify context fields whose contents will replace theplaceholders (‘&’) in the message. If the module is unable to supply all of the valuesrequested in a DEMAND statement (because, for example, there is no dependent data inthe database for the key fields), the system sends this message. You can use messagehandling in your application program for this message (see Message Handling inContexts [Page 1305]).

• Buffer type

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

Page 65: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Interfaces

December 1999 1297

InterfacesWhen you select an entry in the Modules [Page 1295] table, the system fills the Interface tablewith 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 modulewhich determines the field and fills the Interface table with the corresponding input and outputparameters for that module.

For example, the interface for the module SPFLI in the sample context DEMO_TRAVEL lookslike this:

Field name

CITYFROMCARRIDCONNID

AIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTIDFLTYPE

TextAirlineFlight numberFromDeparture airportToArrival airportFlight timeDeparture timeArrival timeDistance inCharter

Module SPFLI: Flight ConnectionsParameter

CITYFROMCARRIDCONNID

AIRPFROMCITYTOAIRPTOFLTIMEDEPTIMEARRTIMEDISTIDFLTYPE

I/O

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

Page 66: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Using Contexts in ABAP Programs

1298 December 1999

Using Contexts in ABAP ProgramsThe following sections explain how to use contexts in your ABAP programs. As with logicaldatabases, 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]

Page 67: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Finding and Displaying a Context

December 1999 1299

Finding and Displaying a ContextTo find an existing context and to familiarize yourself with it, use the initial screen of the ContextBuilder (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 ofthe 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 [Page1297] tables to display further information about the context field dependencies.

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

F i e l d s W e Values M o d u l e s

Airline Airline Flight number Timetable From Context: Geographical distance 2-Country Airports 1 Departure airport Airports 2 To Country Arrival airport Flight time Departure time Arrival time Distance in Charter Distance Airline Local currencyAirport FROMAirport TO

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

Page 68: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Finding and Displaying a Context

1300 December 1999

Display area

CONNID

CARRIDAirlineCARRID

Flight numberCONNID

Connections forSPFLI

AirlineSCARR

CARRID

Airports 2SAIRPORT2

Airports 2SAIRPORT2

CONTEXT: Geographical

DEMO CITIES

AIRPTO

AIRPFROM

CITIFROM/CITYTO

To see the names of all context fields, display the Fields [Page 1293] table in theContext Builder.

You now have the most important information which you need to work with thecontext. Further information such as message texts and the buffering types for themodules are contained in the modules [Page 1295] table.

Page 69: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Creating an Instance of a Context

December 1999 1301

Creating an Instance of a ContextAs objects within the ABAP Workbench, contexts store the relationships between data, but nodata itself. In your ABAP programs, you work with instances of contexts. These are runtimeinstances of contexts containing the actual data.

To create a context instance, you must first declare the context in the program. You do this usingthe CONTEXTS statement:

SyntaxCONTEXTS <c>.

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

SyntaxDATA <inst> TYPE CONTEXT_<c>.

This statement generates an instance <inst> of context <c>. You can create as many instancesof 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.

Page 70: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Supplying Context Instances with Key Values

1302 December 1999

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

SyntaxSUPPLY <key1> = <f1> ... <keyn> = <fn> TO CONTEXT <inst>.

This statement supplies the values <fn> to key fields <keyn> of a context instance <inst>. Thefields 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 thecontext 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 derivedvalues are automatically invalidated, and will be re-calculated the next time you derive dependentvalues.

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 andsupplies both with key values.

Page 71: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Querying Data from Context Instances

December 1999 1303

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

SyntaxDEMAND <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. Thisis the case if the values have already been calculated in a previous DEMAND statementand the instance has not since been supplied with new key field values using theSUPPLY 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. Itlooks first in the context buffer (see Buffering Contexts [Page 1290]) for data records withthe right key field values for the current context instance. If it finds the correspondingvalues, the system copies them as valid values into the context instance and assignsthem to fields <fn>.

3. If there are no appropriate values in the context buffer, the system derives the valuesaccording to the context definition. The system also searches the context buffer duringthe derivation for intermediate results, which it uses if they are valid. When it has derivedthe values, the system saves all results in the context buffer, copies the values to thecontext instance and assigns them to fields <fn>.

4. If the system cannot determine the dependent values, it terminates the process, setsfields <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 theMESSAGES 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_FROMCITYTO = C_TOFLTIME = C_TIMEFROM CONTEXT DEMO_TRAVEL_INST1.

Page 72: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Querying Data from Context Instances

1304 December 1999

WRITE: / C_FROM, C_TO, C_TIME.DEMAND CITYFROM = C_FROM

CITYTO = C_TOFLTIME = C_TIMEFROM CONTEXT DEMO_TRAVEL_INST2.

WRITE: / C_FROM, C_TO, C_TIME.This program generates two instances of context DEMO_TRAVEL, supplies themboth with key values and reads three dependent values from each of them.

Page 73: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Message Handling in Contexts

December 1999 1305

Message Handling in ContextsIf a context cannot derive dependent data when you test it or execute the DEMAND statement, itcan send a message to the user.

The way in which messages are handled in contexts depends on the type of module in which thecontext could not determine data. Table and function module modules handle messagesdifferently. Other contexts used as modules can be broken down to table and function modulelevel.

Message Handling in Table Modules [Page 1306]

Message Handling in Function Module Modules [Page 1308]

Page 74: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Message Handling in Table Modules

1306 December 1999

Message Handling in Table ModulesIf you want to send user messages from table modules, you must first have defined messages forthe individual modules in the Modules [Page 1295] table. The system cannot output a messagefor a table module where none is defined, but will simply reset the corresponding dependentvalues.

When you query dependent data from context instances using the DEMAND statement, you candecide whether the system should handle the user message or whether you want to handle ityourself in the program.

Message Handling - SystemIf you want the system to handle the message, use the basic form of the DEMAND statementwithout the MESSAGES option. The system will then behave as though the following statementoccurred 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 inthe Modules [Page 1295] table. Note that the system reaction to the various message typesdepends on the current user dialog (dialog screen, selection screen or list).

Message Handling - ProgramIf you want to catch the message in your program, use the DEMAND statement using the optionMESSAGES INTO <itab>. To do this, you need to define an internal table <itab> with thestructure SYMSG. The system deletes the contents of <itab> table at the beginning of theDEMAND statement. Whilst it is processing the context, the system does not output or react toany messages, but writes their ID to <itab>. If there are messages in <itab> following theDEMAND 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 toprogram your own using the entries in <itab>. This is important, for example, if you want to makeparticular fields on an entry screen ready for input again. In this case, you must base yourmessage handling on the fields (using the FIELDS statement in screen flow logic, or the ABAPstatement 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 Tablesas Modules [Page 1278]) contained the following entries for module SPFLI:

NameSPFLI

Message ID Variable 1 Variable 3 P/T/170 PBCTRAINNo. Variable 4

EMessa

CARRIDVariable 2CONNID

To demonstrate system message handling, execute the following program:REPORT RSGCON02.

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

Page 75: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Message Handling in Table Modules

December 1999 1307

CONTEXTS DOCU_TEST1.

DATA: CONTEXT_INST TYPE CONTEXT_DOCU_TEST1.

SUPPLY CARRID = 'XX'CONNID = '400'TO CONTEXT CONTEXT_INST.

DEMAND CITYFROM = C_FROMCITYTO = C_TOFROM 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_FROMCITYTO = C_TOFROM 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 theinternal table ITAB, where it is available for you to process further.

Page 76: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Message Handling in Function Module Modules

1308 December 1999

Message Handling in Function Module ModulesIn order for a message to be sent from a function module context module, the function modulemust contain the necessary exception handling. In other words, the function module must sendthe message using the MESSAGE ... RAISING statement. If the exception handling in thefunction module is programmed using the RAISE statement, the system reacts with a runtimeerror. 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. Messagesspecified for function modules in the Modules [Page 1295] table are ignored.

When you query dependent data from context instances using the DEMAND statement, you candecide whether the system should handle the user message or whether you want to handle ityourself in the program.

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

Message Handling - ProgramIf you want to catch the message in your program, use the DEMAND statement using the optionMESSAGES INTO <itab>. To do this, you need to define an internal table <itab> with thestructure SYMSG. The system deletes the contents of <itab> table at the beginning of theDEMAND statement. Whilst it is processing the context, the system does not output or react toany messages, but writes their ID to <itab>. If there are messages in <itab> following theDEMAND 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 toprogram your own using the entries in <itab>. This is important, for example, if you want to makeparticular fields on an entry screen ready for input again. In this case, you must base yourmessage handling on the fields (using the FIELDS statement in screen flow logic, or the ABAPstatement 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.

Page 77: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Message Handling in Function ModuleModules

December 1999 1309

Context DOCU_TEST4 uses this function module as its only module, with key fieldsMAX and OCC for input parameters V1 and V2 and the dependent field PERCENTfor 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 = 00OCC = 20TO CONTEXT CONTEXT_INST.

DEMAND PERCENT = PERCENTAGEFROM 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 = 00OCC = 20TO CONTEXT CONTEXT_INST.

DEMAND PERCENT = PERCENTAGEFROM 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: 0

E AT 012

Page 78: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Message Handling in Function Module Modules

1310 December 1999

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

Page 79: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Working With Contexts - Hints

December 1999 1311

Working With Contexts - HintsCreating 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 outputparameters of other modules. If this is not the case, you should split the context into twoor 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 acontext, the module name should be made up as follows:<object name>_<suffix>. Whenyou 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 themrepeatedly causes no problems. In particular,

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

– You should always use the DEMAND statement immediately before using thederived 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. Thisreduces the risk of obsolete values being used in error.

Page 80: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Programming Database Updates

1312 December 1999

Programming Database UpdatesOpen 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 → ABAPOverview → 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.

Page 81: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Transactions and Logical Units of Work

December 1999 1313

Transactions and Logical Units of WorkIn everyday language, a transaction is a sequence of actions that logically belong together in abusiness 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 tocustomers. 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 atransaction, the data will usually be inconsistent. For example, when you transfer an amount infinancial accounting, this must first be deducted from one account before being credited toanother. In between the two postings, the data is inconsistent, since the amount that you areposting does not exist in either account. It is essential for application programmers to know thattheir data is consistent at the end of the transaction. If an error occurs, it must be possible toundo 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 isalways consistent.

SAP LUWAn SAP LUW is a logical unit consisting of dialog steps, whose changes are written tothe database in a single database LUW.

SAP TransactionAn SAP transaction is an application program that you start using a transaction code. Itmay contain one or more SAP LUWs.

The following sections of this documentation explain these three terms in more detail.

Page 82: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Database Logical Unit of Work (LUW)

1314 December 1999

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

State changes -Insert, Update, Delete

ConsistentState

Consistent State

Intermediate StateCOMMIT

ROLLBACK orerror

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

Implicit Database Commits in the R/3 SystemA work process can only execute a single database LUW. The consequence of this is that a workprocess 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.

Page 83: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Database Logical Unit of Work (LUW)

December 1999 1315

Control passes from the work process to the SAPgui.

Explicit Database Commits in the R/3 SystemThere 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 thekeyword documentation for COMMIT WORK).

Implicit Database Rollbacks in the R/3 SystemThe 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 anunforeseen situation (for example, trying to divide by zero).

• Termination message

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

Explicit Database Rollbacks in the R/3 SystemYou can trigger a database rollback explicitly using the ABAP statement ROLLBACKWORK. This statement starts a database rollback, but also performs other tasks (refer tothe keyword documentation for COMMIT WORK).

From the above, we can draw up the following list of points at which database LUWs begin andend.

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

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

Page 84: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Database Logical Unit of Work (LUW)

1316 December 1999

database. A database lock can only be active for the duration of a database LUW. They areautomatically released when the database LUW ends. In order to program SAP LUWs, we needa 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].)

Page 85: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

SAP LUW

December 1999 1317

SAP LUWDie Verbuchungsverwaltung [Extern]

The Open SQL statements INSERT, UPDATE, MODIFY, and DELETE allow you to programdatabase changes that extend over several dialog steps. Even if you have not explicitlyprogrammed a database commit, the implicit database commit that occurs after a screen hasbeen processed concludes the database LUW. The following diagram shows the individualdatabase LUWs in a typical screen sequence:

DB LUW DB LUW DB LUW DB LUW

PBO PBO PBOPAI PAIPAI Screen

100 Screen

200 Screen

300

Input Save

Under this procedure, you cannot roll back the database changes from previous dialog steps. It istherefore only suitable for programs in which there is no logical relationship between theindividual dialog steps.

However, the database changes in individual dialog steps normally depend on those in otherdialog steps, and must therefore all be executed or rolled back together. These dependentdatabase changes form logical units, and can be grouped into a single database LUW using thebundling techniques listed below.

A logical unit consisting of dialog steps, whose changes are written to the database in a singledatabase LUW is called an SAP LUW. Unlike a database LUW, an SAP LUW can span severaldialog steps, and be executed using a series of different work processes. If an SAP LUWcontains database changes, you should either write all of them or none at all to the database. Toensure that this happens, you must include a database commit when your transaction has endedsuccessfully, and a database rollback in case the program detects an error. However, sincedatabase 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. Tomaintain data integrity, you must bundle all of you database changes in the final database LUWof the SAP LUW. The following diagram illustrates this principle:

Page 86: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

SAP LUW

1318 December 1999

DB LUW DB LUW DB LUW DB LUW

PBO PBO PBOPAI PAIPAI Screen

100 Screen

200 Screen

300

Input Save

Bundling

The bundling technique for database changes within an SAP LUW ensures that you can stillreverse them. It also means that you can distribute a transaction across more than one workprocess, and even across more than one R/3 System. The possibilities for bundling databasechanges 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 commitoccurring within the dialog step itself. Of course, this is not suitable for complex businessprocesses. Instead, the R/3 Basis system contains the following bundling techniques.

Bundling using Function Modules for UpdatesIf you call a function module using the CALL FUNCTION... IN UPDATE TASK statement, thefunction module is flagged for execution using a special update work process. This means thatyou can write the Open SQL statements for the database changes in the function module insteadof in your program, and call the function module at the point in the program where you wouldotherwise have included the statements. When you call a function module using the IN UPDATETASK addition, it and its interface parameters are stored as a log entry in a special databasetable called VBLOG.

The function module is executed using an update work process when the program reaches theCOMMIT WORK statement. After the COMMIT WORK statement, the dialog work process is freeto receive further user input. The dialog part of the transaction finishes with the COMMIT WORKstatement. The update part of the SAP LUW then begins, and this is the responsibility of theupdate work process. The SAP LUW is complete once the update process has committed orrolled back all of the database changes.

Page 87: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

SAP LUW

December 1999 1319

For further information about how to create function modules for use in update, refer to CreatingFunction Modules for Database Updates [Page 1335]

During the update, errors only occur in exceptional cases, since the system checks for all logicalerrors, 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, thefunction modules are not called, and the log entry is deleted from table VBLOG. Errors during theupdate itself are usually technical, for example, memory shortage. If a technical error occurs, theupdate work process triggers a database rollback, and places the log entry back into VBLOG. Itthen sends a mail to the user whose dialog originally generated the VBLOG entry with details ofthe termination. These errors must be corrected by the system administrator. After this, thereturned 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 allowsyou to update the database asynchronously, reducing the response times in the dialog workprocess. You can, for example, decouple the update entirely from the dialog work process anduse a central update work process on a remote database server.

Bundling Using SubroutinesThe 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 asubroutine called with PERFORM ON COMMIT that make database changes are executed in thedatabase LUW of the corresponding dialog step.

Update in Dialog Work Process

PERFORM xON COMMIT

PERFORM yON COMMIT

COMMITWORK

FORMx

FORMy

DB

CO

MM

IT

DB

CO

MM

IT

DB

CO

MM

IT

FORM x

FORM y

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

Page 88: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

SAP LUW

1320 December 1999

Bundling Using Function Modules in Other R/3 SystemsFunction modules that you call using CALL FUNCTION... IN BACKGROUND TASKDESTINATION... are registered for background execution in another R/3 System when theprogram reaches the next COMMIT WORK statement (using Remote Function Call). After theCOMMIT 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 executedtogether in a single database LUW. These updates are useful, for example, when you need tomaintain 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 BasisServices documentation.

Page 89: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

SAP Transactions

December 1999 1321

SAP TransactionsAn SAP LUW is a logical unit consisting of dialog steps, whose changes are written to thedatabase in a single database LUW. In an application program, you end an SAP LUW with eitherthe COMMIT WORK or ROLLBACK WORK statement. An SAP transaction is an applicationprogram 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 atthe 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 toarrange 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, eventblocks, function module calls, and subroutines). You should be careful to ensure thatexternal subroutines or function modules do not lead to COMMIT WORK or ROLLBACKWORK statements accidentally being executed.

• By inserting an SAP LUW

The ABAP statements CALL TRANSACTION (start a new transaction), SUBMIT (start anexecutable program), and CALL FUNCTION... DESTINATION (call a function moduleusing RFC) open a new SAP LUW. When you call a program, it always opens its ownSAP LUW. However, it does not end the LUW of the SAP transaction that called it. Thismeans that a COMMIT WORK or ROLLBACK WORK statement only applies to the SAPLUW of the called program. When the new LUW is complete, the system carries onprocessing the first SAP LUW.

• By running two SAP LUWs in parallel

The CALL FUNCTION... STARTING NEW TASK statement calls a function moduleasynchronously in a new session. Unlike normal function module calls, the callingtransaction carries on with its own processing as soon as the function module hasstarted, 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.

Page 90: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

The R/3 Lock Concept

1322 December 1999

The R/3 Lock ConceptDas R/3 Sperrkonzept [Extern]

Reasons for Setting LocksSuppose a travel agent want to book a flight. The customer wants to fly to a particular city with acertain airline on a certain day. The booking must only be possible if there are still free places onthe flight. To avoid the possibility of overbooking, the database entry corresponding to the flightmust be locked against access from other transactions. This ensures that one user can find outthe number of free places, make the booking, and change the number of free places without thedata being changed in the meantime by another transaction.

Lock Mechanisms in the Database SystemThe database system automatically sets database locks when it receives change statements(INSERT, UPDATE, MODIFY, DELETE) from a program. Database locks are physical locks onthe database entries affected by these statements. You can only set a lock for an existingdatabase entry, since the lock mechanism uses a lock flag in the entry. These flags areautomatically deleted in each database commit. This means that database locks can never beset for longer than a single database LUW; in other words, a single dialog step in an R/3application program.

Physical locks in the database system are therefore insufficient for the requirements of an R/3transaction. Locks in the R/3 System must remain set for the duration of a whole SAP LUW, thatis, over several dialog steps. They must also be capable of being handled by different workprocesses and even different application servers. Consequently, each lock must apply on allservers in that R/3 System.

SAP LocksTo complement the SAP LUW concept, in which bundled database changes are made in a singledatabase LUW, the R/3 System also contains a lock mechanism, fully independent of databaselocks, that allows you to set a lock that spans several dialog steps. These locks are known asSAP locks.

The SAP lock concept is based on lock objects. Lock objects allow you to set an SAP lock foran entire application object. An application object consists of one or more entries in a databasetable, or entries from more than one database table that are linked using foreign keyrelationships.

Before you can set an SAP lock in an ABAP program, you must first create a lock object in theABAP Dictionary. A lock object definition contains the database tables and their key fields on thebasis of which you want to set a lock. When you create a lock object, the system automaticallygenerates two function modules with the names ENQUEUE_<lock object name> andDEQUEUE_<lock object name>. You can then set and release SAP locks in your ABAPprogram by calling these function modules in a CALL FUNCTION statement.

Page 91: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

The R/3 Lock Concept

December 1999 1323

Screen100

Screen200

Screen300

Screenx

CALL FUNCTION'ENQUEUE…'

Save

COMMIT WORK

DatabaseUpdates

SAP LUW

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 locktable for the entire R/3 System in its shared memory.

SAPgui SAPgui

Dispatcher Dispatcher

DialogWP

DialogWP

EnqueueWP

EnqueueTable

Database Management System

Application Data

MessageServer

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

Page 92: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

The R/3 Lock Concept

1324 December 1999

reflected in the return code sy-subrc. The following diagram shows the components of the R/3System that are involved in setting a lock.

Unlike the database, which sets physical locks, the SAP lock mechanism sets logical locks. Thismeans 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. Thelock 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 ofdatabase LUWs. It is released either implicitly when the database update or the SAPtransaction ends, or explicitly, using the corresponding dequeue function module. Youcan use a special parameter in the update function module to set the exact point at whichthe 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 writtento 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 thatuse 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 inthe lock table.

Lock TypesThere 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 arereading it. They prevent other programs from setting an exclusive lock (write lock) tochange the object. It does not, however, prevent other programs from setting further readlocks.

• Exclusive lock

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

Lock DurationWhen you set a lock, you should bear in mind that if it remains set for a long time, the availabilityof the object to other transactions is reduced. Whether or not this is acceptable depends on thenature of the task your program is performing.

Remember in particular that setting too many shared locks without good reason can have aconsiderable effect on programs that work with database tables. If several programs runningconcurrently all set a shared lock for the same application object in the system, it can make italmost impossible to set an exclusive lock, since the program that needs to set that lock will beunable to find any time when there are no locks at all set for that object. Conversely, a singleexclusive lock prevents all other programs from reading the locked object.

Page 93: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

The R/3 Lock Concept

December 1999 1325

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

Page 94: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Example Transaction: SAP Locking

1326 December 1999

Example Transaction: SAP LockingÜbernahme [Extern]

The following example transaction shows how you can lock and unlock database entries using alock object. It lets the user request a given flight (on screen 100) and display or update it (onscreen 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_ESFLIGHTand DEQUEUE_ESFLIGHT to lock and unlock the object.

For more information about creating lock objects and the corresponding function modules, referto the Lock objects section of the ABAP Dictionary documentation.

The PAI processing for screen 100 in this transaction processes the user input and prepares forthe requested action (Change or Display). If the user chooses Change, the program locks therelevant 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'EXPORTINGMANDT = SY-MANDTCARRID = SPFLI-CARRIDCONNID = SPFLI-CONNID

EXCEPTIONSFOREIGN_LOCK = 1SYSTEM_FAILURE = 2OTHERS = 3.

IF SY-SUBRC NE 0.MESSAGE ID SY-MSGID

TYPE 'E'NUMBER SY-MSGNOWITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

Page 95: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Example Transaction: SAP Locking

December 1999 1327

ENDIF....

The ENQUEUE function module can trigger the following exceptions:

FOREIGN_LOCK determines whether a conflicting lock already exists. The system variable SY-MSGV1 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 fortechnical reasons.

At the end of a transaction, the locks are released automatically. However, there are exceptions ifyou have called update routines within the transaction. You can release a lock explicitly by callingthe corresponding DEQUEUE module. As the programmer, you must decide for yourself thepoint at which it makes most sense to release the locks (for example, to make the data availableto other transactions).

If you need to use the DEQUEUE function module call several times in a program, it makes goodsense to write it in a subroutine, which you then call as required.

The subroutine UNLOCK_FLIGHT calls the DEQUEUE function module for the lock objectESFLIGHT:FORM UNLOCK_FLIGHT.

CALL FUNCTION 'DEQUEUE_ESFLIGHT'EXPORTING

MANDT = SY-MANDTCARRID = SPFLI-CARRIDCONNID = SPFLI-CONNID

EXCEPTIONSOTHERS = 1.

SET SCREEN 100.ENDFORM.

You might use this for the BACK and EXIT functions in a PAI module for screen 200 in thisexample transaction. In the program, the system checks whether the user leaves the screenwithout having saved his or her changes. If so, the PROMPT_AND_SAVE routine sends areminder, and gives the user the opportunity to save the changes. The flight can be unlocked bycalling 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'....

Page 96: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Update Techniques

1328 December 1999

Update TechniquesThe main update technique for bundling database changes in a single database LUW is to useCALL FUNCTION... IN UPDATE TASK. This section describes various ways of updating thedatabase.

A program can send an update request using COMMIT WORK

• To the update work process, where it is processed asynchronously. The program does notwait 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 thework 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 theupdate is finished (Local Update [Page 1334].)

Page 97: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Asynchronous Update

December 1999 1329

Asynchronous UpdateA 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 programreaches a COMMIT WORK statement, any function modules from CALL FUNCTION... INUPDATE TASK statements are released for processing in an update work process. The dialogprocess does not wait for the update to finish. This kind of update is called asynchronous update.

Screen100

Screen200

Screen300

Screenx

CALL FUNCTION'ENQUEUE…'

Save

COMMIT WORK

Dialog part of SAP LUW

DatabaseUpdates

Updatepart ofSAPLUWCALL FUNCTION

IN UPDATE TASK

The following diagram shows a typical asynchronous update:

Page 98: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Asynchronous Update

1330 December 1999

SAPgui SAPgui

Dispatcher Dispatcher

DialogWP

DialogWP

EnqueueWP

Database Management System

MessageServer

Application Data Data (VBLOG)

UpdateWP

ApplicationServer 1

Application Server 21

4

23 6 5

7

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. Thisstarts the following procedure in the ABAP program:

1. Firstly, the program locks the database entry against other users, using the enqueue workprocess (or the message server in the case of a distributed system). This generates an entryin the lock table. The user is informed whether the update was successful, or whether thelock 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 userhas created a new entry, the program checks whether a record with the same key valuesalready exists.

3. In the current dialog work process, the program calls a function module using CALLFUNCTION... IN UPDATE TASK, and this writes the change details as an entry in tableVBLOG.

4. When the program is finished (maybe after further dialog steps), a COMMIT WORKstatement starts the final part of the SAP LUW. The work process that is processing thecurrent dialog step starts an update work process.

5. Based on the information passed to it from the dialog work process, the update work processreads 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 thereturn message from the database. If the update was successful, the update work processtriggers a database commit after the last database change and deletes the log entries fromtable 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 aSAPoffice 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.

Page 99: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Asynchronous Update

December 1999 1331

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

Page 100: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Updating Asynchronously in Steps

1332 December 1999

Updating Asynchronously in StepsWhen you process a VBLOG entry asynchronously, you can do it in two update steps. Thisallows you to divide the contents of the update into primary and secondary steps. The primarystep is called V1, the secondary step V2. The V1 and V2 steps of a log entry are processed inseparate database LUWs. The entries in the lock table are usually deleted once the V1 step hasbeen processed. There is no locking for the V2 step. Dividing up the update process allows youto separate time-critical updates that require database locks from less critical data updates thatdo not need locks. V2 steps receive lower priority from the dispatcher than V1 steps. Thisensures that the time- and lock-critical updates are processed quickly, even when the system isbusy.

If an error occurs during the V1 processing, the database rollback applies to all V1 steps in thelog 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 notreversed.

The system marks rolled-back function modules as error functions in the update task log. Theerror can then be corrected and the function restarted later. To access the update task log,choose Tools → Administration → Monitoring → Update. For further information aboutupdate administration, see the Managing Updating section of the BC System Servicesdocumentation.

Page 101: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Synchronous Update

December 1999 1333

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

Screen100

Screen200

Screen300

Screenx

CALL FUNCTION'ENQUEUE…'

Save

COMMIT WORKAND WAIT

Dialog part of SAP LUW

DatabaseUpdates

Updatepart ofSAPLUWCALL FUNCTION

IN UPDATE TASK

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

Page 102: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Local Update

1334 December 1999

Local UpdateIn a local update, the update program is run by the same work process that processed therequest. The dialog user has to wait for the update to finish before entering further data. This kindof update is useful when you want to reduce the amount of access to the database. Thedisadvantage of local updates is their parallel nature. The updates can be processed by manydifferent work processes, unlike asynchronous or synchronous update, where the update isserialized 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. Thisstatement sets a “local update switch”. When it is set, the system interprets CALL FUNCTION INUPDATE TASK as a request for local update. The update is processed in the same work processas the dialog step containing the COMMIT WORK. The transaction waits for the update to finishbefore continuing.

As an example, suppose you have a program that uses asynchronous update that you normallyrun in dialog mode. However, this time you want to run it in the background. Since the systemresponse time is irrelevant when you are running the program in the background, and you onlywant the program to continue processing when the update has actually finished, you can set theSET UPDATE TASK LOCAL switch in the program. You can then use a system variable to checkat 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 orROLLBACK WORK. You therefore need to include a SET UPDATE TASK LOCAL statement atthe beginning of each SAP LUW.

If you reset data within the local update, the ROLLBACK WORK statement applies to both thedialog and the update part of the transaction, since no new SAP LUW is started for the update.

Page 103: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Creating Update Function Modules

December 1999 1335

Creating Update Function ModulesTo create a function module, you first need to start the Function Builder. Choose Tools → ABAPWorkbench, Function Builder. For more information about creating function modules, refer to theABAP Workbench Tools [Extern] documentation.

To be able to call a function module in an update work process, you must flag it in the FunctionBuilder. When you create the function module, set the Process Type attribute to one of thefollowing values:

• Update with immediate start

Set this option for high priority (“V1”) functions that run in a shared (SAP LUW). Thesefunctions 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). Thesefunctions 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 InterfaceFunction modules that run in the update task have a limited interface:

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

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

Page 104: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Calling Update Functions

1336 December 1999

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

• COMMIT WORK

This is the standard form, which specifies asynchronous processing. Your program doesnot wait for the requested functions to finish processing.

• COMMIT WORK AND WAIT

This form specifies synchronous processing. The commit statement waits for therequested functions to finish processing. Control returns to your program after all highpriority (V1) function modules have run successfully.

The AND WAIT form is convenient for switching old programs to synchronous processingwithout having to re-write the code. Functionally, using AND WAIT for update-taskupdates is just the same as dialog-task updates with PERFORM ON COMMIT.

Parameter Values at ExecutionIn ABAP, you can call update-task function modules in two different ways. The way you choosedetermines 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 timeof 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.

Page 105: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Calling Update Functions Directly

December 1999 1337

Calling Update Functions DirectlyTo 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 nextCOMMIT WORK statement is reached. The parameter values used to execute thefunction 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 firsttime, with value 1 in PAR, the second time with value 2 in PAR.

Page 106: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Adding Update Task Calls to a Subroutine

1338 December 1999

Adding Update Task Calls to a SubroutineYou can also put the CALL FUNCTION IN UPDATE TASK into a subroutine and call thesubroutine with:PERFORM SUBROUT ON COMMIT.

If you choose this method, the subroutine is executed at the commit. Thus the request to run thefunction in the update task is also logged during commit processing. As a result, the parametervalues 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 PERFORMON COMMIT statements. This is because a given function module, logged with thesame 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 CallUpdate Modules.

Page 107: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Special LUW Considerations

December 1999 1339

Special LUW ConsiderationsIn the update task queue, the system identifies all function modules belonging to the sametransaction [Page 1313] (SAP LUW) by assigning them a common update key. At the nextCOMMIT WORK, the update task reads the queue and processes all requests with thepredefined update key.

If your program calls an update-task function module, the request to execute the module (or thesubroutine 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 areincluded 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]

Page 108: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Transactions That Call Update Function Modules

1340 December 1999

Transactions That Call Update Function ModulesIf your program calls another program that itself calls an update function module, you should beaware 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 theold update key.

If the called program does not contain its own COMMIT WORK, the database update requestsare not processed, and the update function modules are not called. In the following example, F1,F2, and F3 are update function modules:

Transaktion ZABCABAP/4 Programm

CALL FUNCTION ´F1´ IN UPDATE TASK ...

CALL TRANSACTION ZABC ...

CALL FUNCTION ´F3´ IN UPDATE TASK ...

COMMIT WORK....

CALL FUNCTION ´F2´ IN UPDATE TASK ...

LEAVE.

...

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

Page 109: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Dialog Modules that Call UpdateFunction Modules

December 1999 1341

Dialog Modules that Call Update Function ModulesUnlike transactions and executable programs (reports), dialog modules do not start a new SAPLUW. Calls to update-task function modules from a dialog module use the same update key asthe ones in the calling program. The result is that calls to update function modules from a dialogmodule 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 thedatabase (for example, with UPDATE).However, it does not start the update task.The function modules are not actually executed until a COMMIT WORK statementoccurs in the calling program.

If you use dialog modules, try to avoid including calls to update function modules insubroutines called with PERFORM ON COMMIT. In general, any occurrence ofPERFORM ON COMMIT (with or without update-task function calls) in a dialogmodule can cause problems.

This is because dialog modules have their own roll area, which disappears when themodule finishes. Consequently, all local data (including data used for parametervalues when calling an update function module) disappears as soon as the commit inthe main program is reached.

If you must call an update function module in a subroutine in a dialog module, youmust ensure that the values of the actual parameters still exist when the update-taskfunction actually runs. To do this, you can store the required values with EXPORTTO MEMORY and then import them back into the main program (IMPORT FROMMEMORY) before the COMMIT WORK statement.

Page 110: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Error Handling for Bundled Updates

1342 December 1999

Error Handling for Bundled UpdatesRuntime errors can occur during execution of bundled updates. How are they handled? Ingeneral, 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 WORKAND 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 antermination message (MESSAGE type ‘A’). Also, the ROLLBACK WORK statement automaticallysignals 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 arenot 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 rolledback.

− 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 TASKDESTINATION)

− Background-task updates already executed for the current DESTINATION are not rolledback.

Page 111: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Error Handling for Bundled Updates

December 1999 1343

− 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 decidewhether to resubmit the requests at a later time.

For further information about RFC processing, refer to the Remote Communications[Extern] documentation.

Page 112: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Objects

1344 December 1999

ABAP ObjectsVererbung [Page 1380]

Class- und Interface-Pools [Page 1411]

GeneralWhat are ABAP Objects? [Page 1348]

What is Object Orientation? [Page 1345]

Object Orientation in ABAPFrom Function Groups to Objects [Page 1349]

Classes [Page 1353]

Object Handling [Page 1360]

Interfaces [Page 1390]

Using ABAP ObjectsDeclaring and Calling Methods [Page 1365]

Triggering and Handling Events [Page 1397]

Page 113: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

What is Object Orientation?

December 1999 1345

What is Object Orientation?Object orientation (OO), or to be more precise, object-oriented programming, is a problem-solving 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 ofthis introduction to ABAP Objects. This documentation introduces a selection of terms that areused universally in object orientation and also occur in ABAP Objects. In subsequent sections, itgoes on to discuss in more detail how these terms are used in ABAP Objects. The end of thissection contains a list of further reading, with a selection of titles about object orientation.

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

ClassesClasses describe objects. From a technical point of view, objects are runtime instancesof a class. In theory, you can create any number of objects based on a single class. Eachinstance (object) of a class has a unique identity and its own set of values for itsattributes.

Object ReferencesIn a program, you identify and address objects using unique object references. Objectreferences allow you to access the attributes and methods of an object.

In object-oriented programming, objects usually have the following properties:

EncapsulationObjects 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 objectitself.

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

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

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

Page 114: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

What is Object Orientation?

1346 December 1999

• Complex software systems become easier to understand, since object-orientedstructuring provides a closer representation of reality than other programmingtechniques.

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

• Through polymorphism and inheritance, object-oriented programming allows you toreuse individual components.

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

Achieving these goals requires:

• Object-oriented programming languages

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

• Object-oriented tools

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

• Object-oriented modeling

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

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

Further ReadingThere are many books about object orientation, object-oriented programming languages,object-oriented analysis and design, project management for OO projects, patterns andframeworks, and so on. This is a small selection of good books covering the most importanttopics:

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

Page 115: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

What is Object Orientation?

December 1999 1347

• Grady Booch, Object Solutions: Managing the Object-Oriented Project, Addison-Wesley Pub Co (1995), ISBN: 0805305947A good book about all of the non-technical aspects of OO that are equally important foreffective 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: 0201325632An excellent book about UML (Unified Modeling Language - the new standardized OOlanguage and notation for modeling). Assumes knowledge and experience of objectorientation.

• Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns.Elements of Reusable Object-Oriented Software, Addison-Wesley Pub Co (1998),ISBN: 0201634988Provides 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 ofObject-Oriented Programming, Prentice Hall (1996), ISBN: 0138469652A collection of articles addressing the many questions and problems of OO analysis anddesign, implementation, dependency management, and so on. Highly recommended.

NotesIf you are new to object-orientation, you should read Scott Ambler’s ‘The Object Primer’ andthen acquire some practical experience of your own. You should definitely use the CRCtechniques described by Ambler and Fowler for object-oriented analysis and design. Afterthis, 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 inwhich things should be done, which phases should be finished at what time, how to divide upand 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 beredefined for the object-oriented world, and the opportunities that this has produced aresignificant. For further information about how to use OO in project management, see GradyBrooch’s book ‘Object solutions’, or the chapter entitles ‘An outline development process’ fromMartin Fowler’s book.

There are, of course, many other good books about object orientation. The above list does notclaim either to be complete, or necessarily to recommend the best books available.

Page 116: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

What are ABAP Objects?

1348 December 1999

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

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

The Object-oriented Language ExtensionABAP Objects is a complete set of object-oriented statements that has been introduced into theABAP language. This object-oriented extension of ABAP builds on the existing language, and isfully 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 theobject-oriented paradigm, is a programming model that unites data and functions in objects. Therest of the ABAP language is primarily intended for structured programming, where data is storedin 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 iscompatible with external object interfaces such as DCOM and CORBA. The implementation ofobject-oriented elements in the kernel of the ABAP language has considerably increasedresponse 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.

Page 117: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

From Function Groups to Objects

December 1999 1349

From Function Groups to ObjectsAt the center of any object-oriented model are objects, which contain attributes (data) andmethods (functions). Objects should enable programmers to map a real problem and itsproposed software solution on a one-to-one basis. Typical objects in a business environmentare, for example, ‘customer’, ‘Order’, or ‘Invoice’. From Release 3.1 onwards, the BusinessObject Repository (BOR) has contained examples of such objects. The object model of ABAPObjects, the object-oriented extension of ABAP, is compatible with the object model of theBOR.

Before R/3 Release 4.0, the nearest equivalent of objects in ABAP were function modules andfunction groups. Suppose we have a function group for processing orders. The attributes of anorder correspond to the global data of the function group, while the individual functionmodules represent actions that manipulate that data (methods). This means that the actualorder data is encapsulated in the function group, and is never directly addressed, but insteadonly through the function modules. In this way, the function modules can ensure that the datais consistent.

When you run an ABAP program, the system starts a new internal session. The internal sessionhas a memory area that contains the ABAP program and its associated data. When you call afunction module, an instance of its function group plus its data, is loaded into the memory areaof the internal session. An ABAP program can load several instances by calling function modulesfrom different function groups.

Hauptmodus eines GUI-Fensters

Interner Modus eines ABAP-Programms

ABAP-Programm

Funktionsgruppe 1

Daten...

Funktions-bausteine …

Funktionsgruppe n

Daten...

Funktions-bausteine …

Page 118: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

From Function Groups to Objects

1350 December 1999

The instance of a function group in the memory area of the internal session almost represents anobject in the sense of object orientation. (See also the definition in the section What is ObjectOrientation? [Page 1345].. When you call a function module, the calling program uses theinstance of a function group, based on its description in the Function Builder. The programcannot access the data in the function group directly, but only through the function module. Thefunction modules and their parameters are the interface between the function group and theuser.

The main difference between real object orientation and function groups is that although aprogram can work with the instances of several function groups at the same time, it cannot workwith several instances of a single function group. Suppose a program wanted to use severalindependent counters, or process several orders at the same time. In this case, you would haveto adapt the function group to include instance administration, for example, by using numbers todifferentiate between the instances.

In practice, this is very awkward. Consequently, the data is usually stored in the callingprogram, and the function modules are called to work with it (structured programming). Oneproblem is, for example, that all users of the function module must use the same datastructures as the function group itself. Changing the internal data structure of a function groupaffects many users, and it is often difficult to predict the implications. The only way to avoidthis is to rely heavily on interfaces and a technique that guarantees that the internal structuresof instances will remain hidden, allowing you to change them later without causing anyproblems.

This requirement is met by object orientation. ABAP Objects allows you to define data andfunctions in classes instead of function groups. Using classes, an ABAP program can workwith any number of instances (objects) based on the same template.

Hauptmodus eines GUI-Fensters

Interner Modus eines ABAP-Programms

ABAP-Programm

n. Instanz, Klasse n

Daten...

Schnittstelle …

1. Instanz, Klasse nn. Instanz, Klasse 1

Daten...

Schnittstelle …

1. Instanz, Klasse 1

Schnitt-stelle …

Daten...

Schnitt-stelle …

Daten...

Page 119: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

From Function Groups to Objects

December 1999 1351

Instead of loading a single instance of a function group into memory implicitly when a functionmodule is called, the ABAP program can now generate the instances of classes explicitly usingthe new ABAP statement CREATE OBJECT. The individual instances represent unique objects.You address these using object references. The object references allow the ABAP program toaccess the interfaces of the instances.

The following sections contain more information about classes, objects, interfaces, and objectreferences in ABAP Objects.

Page 120: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Example

1352 December 1999

ExampleThe following example shows the object-oriented aspect of function groups in the simple caseof 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 withthe field. Two of the function modules have input and output parameters. These formthe 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 variableNUMBER will have the value 8.

The program itself cannot access the COUNT field in the function group. Operationson this field are fully encapsulated in the function module. The program can onlycommunicate with the function group by calling its function modules.

Page 121: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Classes

December 1999 1353

ClassesLIKE-Zusatz [Page 117]

Classes are templates for objects. Conversely, you can say that the type of an object is the sameas its class. A class is an abstract description of an object. You could say that it is a set ofinstructions for building an object. The attributes of objects are defined by the components ofthe class, which describe the state and behavior of objects.

Local and Global ClassesClasses in ABAP Objects can be declared either globally or locally. You define global classesand interfaces in the Class Builder (Transaction SE24) in the ABAP Workbench. They are storedcentrally in class pools [Page 1411] in the class library in the R/3 Repository. All of the ABAPprograms in an R/3 System can access the global classes. Local classes are defined within anABAP program. Local classes and interfaces can only be used in the program in which they aredefined. When you use a class in an ABAP program, the system first searches for a local classwith the specified name. If it does not find one, it then looks for a global class. Apart from thevisibility 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 todefine the outwardly visible components so that it fits into that program. Global classes, on theother hand, must be able to be used anywhere. This means that certain restrictions apply whenyou define the interface of a global class, since the system must be able to guarantee that anyprogram using an object of a global class can recognize the data type of each interfaceparameter.

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 ClassesLocal 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, animplementation 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. Whenyou define local classes, the declaration part belongs to the global program data. You shouldtherefore place it at the beginning of the program.

If you declare methods in the declaration part of a class, you must also write an implementationpart 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. Theimplementation part of a local class is a processing block. Subsequent coding that is not itselfpart of a processing block is therefore not accessible.

Page 122: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Classes

1354 December 1999

Structure of a ClassThe 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 ComponentsThe components of a class make up its contents. All components are declared in the declarationpart of the class. The components define the attributes of the objects in a class. When you definethe class, each component is assigned to one of the three visibility sections, which define theexternal interface of the class. All of the components of a class are visible within the class. Allcomponents are in the same namespace. This means that all components of the class must havenames that are unique within the class.

There are two kinds of components in a class - those that exist separately for each object in theclass, 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 notinstance-specific are called static components.

In ABAP Objects, classes can define the following components. Since all components that youcan declare in classes can also be declared in interfaces, the following descriptions apply equallyto interfaces.

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

Instance AttributesThe contents of instance attributes define the instance-specific state of an object. You declarethem using the DATA statement.

Static AttributesThe contents of static attributes define the state of the class that is valid for all instances of theclass. Static attributes exist once for each class. You declare them using the CLASS-DATAstatement. 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 anobject, the change is visible in all other objects in the class.

MethodsMethods are internal procedures in a class that define the behavior of an object. They canaccess 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 callingthem, and receive values back from them The private attributes of a class can only be changedby methods in the same class.

Page 123: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Classes

December 1999 1355

The definition and parameter interface of a method is similar to that of function modules. Youdefine a method <met> in the definition part of a class and implement it in the implementationpart 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 ABAPprocedures (subroutines and function modules). You call methods using the CALL METHODstatement.

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

Static MethodsYou declare static methods using the CLASS-METHODS statement. They can only access staticattributes and trigger static events.

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

EventsObjects 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 istriggered, any number of event handler methods can be called. The link between the trigger andthe handler is not established until runtime. In a normal method call, the calling programdetermines the methods that it wants to call. These methods must exist. With events, the handlerdetermines the events to which it wants to react. There does not have to be a handler methodregistered for every event.

The events of a class can be triggered in the methods of the same class using the RAISEEVENT statement. You can declare a method of the same or a different class as an eventhandler 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. Theseparameters 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 SETHANDLER statement. The trigger and handlers can be objects or classes, depending onwhether you have instance or static events and event handler methods. When an event istriggered, the corresponding event handler methods are executed in all registered handlingclasses.

Instance EventsYou declare instance events using the EVENTS statement. An instance event can only betriggered in an instance method.

Page 124: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Classes

1356 December 1999

Static EventsYou declare static events using the CLASS-EVENTS statement. All methods (instance and staticmethods) can trigger static events. Static events are the only type of event that can be triggeredin a static method.

See also Triggering and Handling Events [Page 1397].

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

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

Visibility SectionsYou 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 betweenthe class and its users. Each component of a class must be assigned to one of the visibilitysections.

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

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

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

EncapsulationThe 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

Page 125: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Classes

December 1999 1357

components, and try to declare as few public components as possible. The public components ofglobal 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 anobject and its users. If you want to encapsulate the state of an object fully, you cannot declareany public attributes. As well as defining the visibility of an attribute, you can also protect it fromchanges using the READ-ONLY addition.

See also:Overview Graphic [Page 1358]

Example [Page 1359]

Page 126: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Overview Graphic

1358 December 1999

Overview GraphicClasses

All users

Klasse C1

Privatecomponents

A2,M2,E2,…

Methodimplementations

Subclasses of C1

Protected components A3, M3, E3, …

Publiccomponents

A1,M1,E1,…

CLASS C1 DEFINITION.PUBLIC SECTION.DATA: A1 …METHODS: M1 …EVENTS: E1 …

PROTECTED SECTION.DATA: A2 …METHODS: M2 …EVENTS: E2 …

PRIVATE SECTION.DATA: A3 …METHODS: M3 …EVENTS: E3 …

ENDCLASS.

CLASS C1 IMPLEMENTATION.

METHOD M1. … ENDMETHOD.

METHOD M2. … ENDMETHOD.

METHOD M3. … ENDMETHOD.

ENDCLASS.

The left-hand side of the illustration shows the declaration and implementation parts of a localclass C1. The right-hand side illustrates the structure of the class with the components in theirrespective visibility areas, and the implementation of the methods.

The public components of the class form the interface between the class and its users. Theprotected components are an interface to the subclasses of C1. The private components are notvisible externally, and are fully encapsulated in the class. The methods in the implementation parthave unrestricted access to all components of the class.

Page 127: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Classes - Introductory Example

December 1999 1359

Classes - Introductory ExampleVon Funktionsgruppen zu Objekten [Page 1349]

The following simple example uses ABAP Objects to program a counter. For comparison, seealso 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 theprivate 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 cancreate instances of the class C_COUNTER.

Page 128: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Object Handling

1360 December 1999

Object HandlingDatenreferenzen [Page 220]

Interfaces [Page 1390]

Vererbung [Page 1380]

Interfaces [Page 1390]

LIKE-Zusatz [Page 117]

ObjectsObjects are instances of classes. Each object has a unique identity and its own attributes. Alltransient 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 ReferencesTo access an object from an ABAP program, you use object references. Object references arepointers to objects. In ABAP, they are always contained in reference variables.

Reference variablesReference variables contain references. A reference variable is either initial or contains areference to an existing object. The identity of an object depends on its reference. A referencevariable that points to an object knows the identity of that object. Users cannot access the identityof the object directly.

Reference variables in ABAP are treated like other elementary data objects. This means that areference variable can occur as a component of a structure or internal table as well as on its own.

Data Types for ReferencesABAP contains a predefined data type for references, comparable to the data types for structuresor 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, theobject reference). There are two principal types of references: Class references and interfacereferences (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 variablewith 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

Page 129: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Object Handling

December 1999 1361

Creating ObjectsBefore you can create an object for a class, you need to declare a reference variable withreference 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 ObjectsPrograms can only access the instance components of an object using references in referencevariables. 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 isalso possible to address the static components of a class before an object has been created.

• Addressing a static attribute <attr>: <class>=><attr>

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

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 accessattributes in methods from within an object even if they are obscured by local attributes of themethod.

Creating More Than One Instance of a ClassIn a program, you can create any number of objects from the same class. The objects are fullyindependent of each other. Each one has its own identity within the program and its ownattributes. Each CREATE OBJECT statement generates a new object, whose identity is definedby its unique object reference.

Assigning ReferencesYou can assign references to different reference variables using the MOVE statement. In thisway, you can make the references in several reference variables point to the same object. Whenyou assign a reference to a different reference variable, their types must be either compatible orconvertible.

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 writethe statement

<cref1> = <cref2>

the two class references <cref1> and <cref2> must have the same type, that is, they must eitherrefer to the same class, or the class of <cref1> must be the predefined empty class OBJECT.

Page 130: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Object Handling

1362 December 1999

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

Object LifetimeAn object exists for as long as it is being used in the program. An object is in use by a programfor as long as at least one reference points to it, or at least one method of the object is registeredas an event handler.

As soon as there are no more references to an object, and so long as none of its methods areregistered as event handlers, it is deleted by the automatic memory management (garbagecollection). 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]

Page 131: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Overview Graphic

December 1999 1363

Overview GraphicObjects as Instances of a Class

Class C1

Privatecomponents

Methodimplementations

Protected components…

Publiccomponents

Internal session of an ABAP program

Schnittstelle …

C1<1>

Schnittstelle …

C1<3>

Schnittstelle …

C1<2>

Class Instances of the class

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

Page 132: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Objects - Introductory Example

1364 December 1999

Objects - Introductory ExampleKlassen [Page 1353]

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

[Extern]

Page 133: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Declaring and Calling Methods

December 1999 1365

Declaring and Calling MethodsGET REFERENCE [Page 223]

This section contains explains how to work with methods in ABAP Objects. For precise details ofthe relevant ABAP statements, refer to the corresponding keyword documentation in the ABAPEditor. The example [Page 1368] shows how to declare, implement, and call methods.

Declaring MethodsYou can declare methods in the declaration part of a class or in an interface. To declare instancemethods, 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 additionsIMPORTING, EXPORTING, CHANGING, and RETURNING. The additions define the input,output, and input/output parameters, and the return code. They also define the attributes of theinterface 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 functionmodules, the default way of passing a parameter in a method is by reference. To pass aparameter 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 formethods that return a single output value. If you use it, you cannot use EXPORTING orCHANGING parameters.

As in function modules, you can use exception parameters (EXCEPTIONS) to allow the user toreact to error situations when the method is executed.

Implementing MethodsYou 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 behavelike local variables within the method implementation. You can define additional local variableswithin a method using the DATA statement.

As in function modules, you can use the RAISE <exception> and MESSAGE RAISINGstatements to handle error situations.

Page 134: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Declaring and Calling Methods

1366 December 1999

When you implement a static method, remember that it can only work with the static attributes ofyour class. Instance methods can work with both static and instance attributes.

Calling MethodsTo 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 fromwhere you are calling it. Within the implementation part of a class, you can call the methods ofthe 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. Visibleinstance 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. Visibleinstance 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 theEXPORTING or CHANGING addition in the CALL METHOD statement. You can (but do not haveto) import the output parameters into your program using the IMPORTING or RECEIVINGaddition. Equally, you can (but do not have to) handle any exceptions triggered by the exceptionsusing 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 theleft-hand side of the equals sign. The actual parameters are always on the right. The equals signis not an assignment operator in this context; it merely serves to assign program variables to theinterface parameters of the method.

If the interface of a method consists only of a single IMPORTING parameter, you can use thefollowing 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 followingshortened form of the method call:

CALL METHOD <method>(....<ii> =.<fi>...).

Each actual parameter <fi> is passed to the corresponding formal parameter <ii>.

Page 135: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Declaring and Calling Methods

December 1999 1367

Event Handler MethodsEvent handler methods are special methods that cannot all be called using the CALL METHODstatement. Instead, they are triggered using events. You define a method as an event handlermethod 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]

ConstructorsConstructors are special methods that cannot be called using CALL METHOD. Instead, they arecalled automatically by the system to set the starting state of a new object or class. There are twotypes of constructors - instance constructors and static constructors. Constructors are methodswith 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. Youdeclare 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 theinstance constructor once for each instance of the class, directly after the object has beencreated in the CREATE OBJECT statement. You can pass the input parameters of the instanceconstructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in theCREATE OBJECT statement.

The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. Youdeclare 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 hasno parameters. The system calls the static constructor once for each class, before the class isaccessed for the first time. The static constructor cannot therefore access the components of itsown class.

The methods example [Page 1368] shows how to use instance and static constructors.

Page 136: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Methods in ABAP Objects - Example

1368 December 1999

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

OverviewThis example uses three classes called C_TEAM, C_BIKER, and C_BICYCLE. A user (aprogram) can create objects of the class C_TEAM. On a selection screen, the class C_TEAMasks 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 thereare members in the team. Each instance of the class C_BIKER creates an instances of the classC_BICYCLE.

Each instance of the class C_TEAM can communicate with the program user through aninteractive list. The program user can choose individual team members for actions. Theinstances of the class C_BIKER allow the program user to choose the action on a furtherselection screen.

Page 137: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Methods in ABAP Objects - Example

December 1999 1369

C_TEAM<3>

C_TEAM<2>

C_TEAM<1>

C_ BICYCLE <4>

C_ BICYCLE<3>

C_ BICYCLE<2>

C_BICYCLE<1>

C_ BIKER<4>

C_ BIKER<3>

C_BIKER<2>

C_BIKER<1>

......

...

Benutzerinteraktion:

Referenzvariablen und Instanzen:

Page 138: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Methods in ABAP Objects - Example

1370 December 1999

Constraints

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

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

• ULINE

• SKIP

• NEW-LINE

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

Declarations

This example is implemented using local classes, since selection screens belong to an ABAPprogram, and cannot be defined or called in global classes. Below are the definitions of the twoselection 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.

Page 139: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Methods in ABAP Objects - Example

December 1999 1371

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.

Page 140: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Methods in ABAP Objects - Example

1372 December 1999

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 IEXCEPTIONS 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 onlybe changed by their methods. The class C_TEAM contains a static constructorCLASS_CONSTRUCTOR. C_TEAM and C_BIKER both contain instance constructors.

ImplementationsThe implementation parts of the classes contain the implementations of all of the methodsdeclared in the corresponding declaration parts. The interfaces of the methods have alreadybeen defined in the declarations. In the implementations, the interface parameters behave likelocal data.

Methods of Class C_TEAMThe following methods are implemented in the sectionCLASS C_TEAM IMPLEMENTATION.

...ENDCLASS.

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

Page 141: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Methods in ABAP Objects - Example

December 1999 1373

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

CONSTRUCTORMETHOD 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, andassigns the corresponding number to the instance attribute ID of each instance of the class.

CREATE_TEAMMETHOD 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 areference variable with a reference to an instance of the class. It is used to create instances ofthe class C_BIKER, using the private reference variable BIKER in the class C_TEAM. You mustpass both input parameters for the instance constructor of class C_BIKER in the CREATEOBJECT statement. The references to the newly-created instances are inserted into the privateinternal table BIKER_TAB. After the method has been executed, each line of the internal tablecontains a reference to an instance of the class C_BIKER. These references are only visiblewithin 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 usesthe work area STATUS_LINE to append its output parameter LINE to the private internal tableSTATUS_LIST.

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

Page 142: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Methods in ABAP Objects - Example

1374 December 1999

The public instance method SELECTION can be called by any user of the class containing areference variable with a reference to an instance of the class. It selects all of the lines in thecurrent list in which the checkbox in the first column is selected. For these lines, the systemcopies the corresponding reference variables from the table BIKER_TAB into an additionalprivate internal table BIKER_SELECTION. SELECTION then calls the private methodWRITE_LIST, which displays the list.

EXECUTIONMETHOD 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 areference variable with a reference to an instance of the class. The method calls the two methodsSELECT_ACTION and STATUS_LINE for each instance of the class C_BIKER for which there isa reference in the table BIKER_SELECTION. The line of the table STATUS_LIST with the samekey as the component ID in the work area STATUS_LINE is overwritten and displayed by theprivate method WRITE_LIST.

WRITE_LISTMETHOD 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 classC_TEAM. It is used to display the private internal table STATUS_LIST on the basic list (SY-LSIND = 0) of the program.

Methods of Class C_BIKERThe following methods are implemented in the sectionCLASS C_BIKER IMPLEMENTATION.

...

Page 143: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Methods in ABAP Objects - Example

December 1999 1375

ENDCLASS.

CONSTRUCTORMETHOD 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 iscreated. 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 inthe 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 newinstance of the class C_BIKER. The reference in the private reference variable BIKE of eachinstance of C_BIKER points to a corresponding instance of the class C_BICYCLE. No externaluser can address these instances of the class C_BICYCLE.

SELECT_ACTIONMETHOD 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 containinga reference variable with a reference to an instance of the class. The method calls the selectionscreen 200 and analyzes the user input. After this, it calls the private method BIKER_ACTION ofthe same class. The method call uses the shortened form to pass the actual parameterACTIVITY to the formal parameter ACTION.

BIKER_ACTIONMETHOD BIKER_ACTION.CASE ACTION.WHEN -1 OR 1.CALL METHOD BIKE->CHANGE_GEAR

EXPORTING CHANGE = ACTIONRECEIVING GEAR = GEAR_STATUS

Page 144: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Methods in ABAP Objects - Example

1376 December 1999

EXCEPTIONS GEAR_MAX = 1GEAR_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 classC_BIKER. The method calls other methods in the instance of the class C_BICYCLE to which thereference in the reference variable BIKE is pointing, depending on the value in the inputparameter ACTION.

STATUS_LINEMETHOD 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 areference variable with a reference to an instance of the class. It fills the structured outputparameter LINE with the current attribute values of the corresponding instance.

Methods of Class C_BICYCLEThe following methods are implemented in the sectionCLASS C_BICYCLE IMPLEMENTATION.

...ENDCLASS.

DRIVEMETHOD DRIVE.SPEED = SPEED + GEAR * 10.VELOCITY = SPEED.

ENDMETHOD.

Page 145: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Methods in ABAP Objects - Example

December 1999 1377

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

STOPMETHOD STOP.SPEED = 0.VELOCITY = SPEED.

ENDMETHOD.

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

CHANGE_GEARMETHOD 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 areference variable with a reference to an instance of the class. The method changes the value ofthe private attribute GEAR. Since the formal parameter with the same name obscures theattribute in the method, the attribute has to be addressed using the self-reference ME->GEAR.

Using the Classes in a ProgramThe following program shows how the above classes can be used in a program. Thedeclarations of the selection screens and local classes, and the implementations of the methodsmust 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.

Page 146: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Methods in ABAP Objects - Example

1378 December 1999

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.

*******************************************************************

Page 147: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Methods in ABAP Objects - Example

December 1999 1379

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

When the user chooses a function, the event AT USER-COMMAND is triggered and publicmethods 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.

Page 148: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Inheritance

1380 December 1999

InheritanceInheritance allows you to derive a new class from an existing class. You do this using theINHERITING 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. Theoriginal 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 thesuperclass. However, only the public and protected components of the superclass are visible inthe subclass. Although the private components of the superclass exist in the subclass, they arenot visible. You can declare private components in a subclass that have the same names asprivate 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 thesuperclass. However, you can add new components to the subclass. This allows you to turn thesubclass into a specialized version of the superclass. If a subclass is itself the superclass offurther 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 superclassis itself the subclass of another class, all of the classes involved form an inheritance tree, whosedegree of specialization increases with each new hierarchical level you add. Conversely, theclasses become more generalized until you reach the root node of the inheritance tree. The rootnode of all inheritance trees in ABAP Objects is the predefined empty class OBJECT. This is themost generalized class possible, since it contains neither attributes nor methods. When youdefine a new class, you do not have to specify it explicitly as the superclass - the relationship isalways implicitly defined. Within an inheritance tree, two adjacent nodes are the directsuperclass or direct subclass of one another. Other related nodes are referred to as superclassesand subclasses. The component declarations in a subclass are distributed across all levels ofthe inheritance tree.

Redefining MethodsAll subclasses contain the components of all classes between themselves and the root node inan inheritance tree. The visibility of a component cannot be changed. However, you can use theREDEFINITION addition in the METHODS statement to redefine an inherited public or protectedinstance method in a subclass and make its function more specialized. When you redefine amethod, you cannot change its interface. The method retains the same name and interface, buthas a new implementation.

The method declaration and implementation in the superclass is not affected when you redefinethe method in a subclass. The implementation of the redefinition in the subclass obscures theoriginal implementation in the superclass.

Any reference that points to an object of the subclass uses the redefined method, even if thereference was defined with reference to the superclass. This particularly applies to the self-reference 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

Page 149: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Inheritance

December 1999 1381

the original method M2 to be called, and calling M1 from an instance of the subclass will causethe redefined method M2 to be called.

Within a redefine method, you can use the pseudoreference SUPER-> to access the obscuredmethod. This enables you to use the existing function of the method in the superclass withouthaving to recode it in the subclass.

Abstract and Final Methods and ClassesThe ABSTRACT and FINAL additions to the METHODS and CLASS statements allow you todefine 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. Theyconclude an inheritance tree.

References to Subclasses and PolymorphismReference variables defined with reference to a superclass or an interface defined with referenceto it can also contain references to any of its subclasses. Since subclasses contain all of thecomponents of all of their superclasses, and given that the interfaces of methods cannot bechanged, a reference variable defined with reference to a superclass or an interface implementedby a superclass can contain references to instances of any of its subclasses. In particular, youcan define the target variable with reference to the generic class OBJECT.

When you create an object using the CREATE OBJECT statement and a reference variabletyped with reference to a subclass, you can use the TYPE addition to create an instance of asubclass, 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 thesuperclass to which the reference variable refers. However, it cannot address any specializationimplemented in the subclass. If you use a dynamic method call, you can address all componentsof the class.

If you redefine an instance method in one or more subclasses, you can use a single referencevariable to call different implementations of the method, depending on the position in theinheritance tree at which the referenced object occurs. This concept that different classes canhave the same interface and therefore be addressed using reference variables with a single typeis called polymorphism.

Namespace for ComponentsSubclasses 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 protectedcomponents within an inheritance tree belong to the same namespace, and consequently musthave unique names. The names of private components, on the other hand, must only be uniquewithin their class.

When you redefine methods, the new implementation of the method obscures the method of thesuperclass with the same name. However, the new definition replaces the previous methodimplementation, so the name is still unique. You can use the pseudoreference SUPER-> toaccess a method definition in a superclass that has been obscured by a redefinition in asubclass.

Page 150: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Inheritance

1382 December 1999

Inheritance and Static AttributesLike all components, static attributes only exist once in each inheritance tree. A subclass canaccess the public and protected static attributes of all of its superclasses. Conversely, asuperclass shares its public and protected static attributes with all of its subclasses. In terms ofinheritance, static attributes are not assigned to a single class, but to a part of the inheritancetree. You can change them from outside the class using the class component selector with anyclass name, or within any class in which they are shared. They are visible in all classes in theinheritance tree.

When you address a static attribute that belongs to part of an inheritance tree, you alwaysaddress the class in which the attribute is declared, irrespective of the class you specify in theclass selector. This is particularly important when you call the static constructors of classes ininheritance. Static constructors are executed the first time you address a class. If you address astatic attribute declared in a superclass using the class name of a subclass, only the staticconstructor of the superclass is executed.

Inheritance and ConstructorsThere are special rules governing constructors in inheritance.

Instance ConstructorsEvery class has an instance constructor called CONSTRUCTOR. This is an exception to the rulethat states that component names within an inheritance tree must be unique. However, theinstance constructors of the various classes in an inheritance tree are fully independent of oneanother. You cannot redefine the instance constructor of a superclass in a subclass, neither canyou 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 usingCREATE 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 toensure that the instance constructors of all of its superclasses are also called. To do this, theinstance constructor of each subclass must contain a CALL METHOD SUPER->CONSTRUCTOR statement. The only exception to this rule are direct subclasses of the rootnode OBJECT.

In superclasses without an explicitly-defined instance constructor, the implicit instanceconstructor is called. This automatically ensures that the instance constructor of the immediatesuperclass is called.

When you call an instance constructor, you must supply values for all of its non-optional interfaceparameters. There are various ways of doing this:

• Using CREATE OBJECT

If the class that you are instantiating has an instance constructor with an interface, youmust 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 mustlook in the inheritance tree for the next-highest superclass with an explicit instanceconstructor. If this has an interface, you must supply values using EXPORTING.Otherwise, you do not have to pass any values.

Page 151: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Inheritance

December 1999 1383

• Using CALL METHOD SUPER->CONSTRUCTOR

If the direct superclass has an instance constructor with an interface, you must passvalues to it using EXPORTING.

If the direct superclass has an instance constructor without an interface, you do not passany parameters.

If the direct superclass does not have an explicit instance constructor, you must look inthe 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 nothave to pass any values.

In both CREATE OBJECT and CALL METHOD SUPER->CONSTRUCTOR, you must look at thenext-available explicit instance constructor and, if it has an interface, pass values to it. The sameapplies to exception handling for instance constructors. When you work with inheritance, youneed an precise knowledge of the entire inheritance tree. When you instantiate a class at thebottom of the inheritance tree, you may need to pass parameters to the constructor of a classthat 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 astatic method, that is, it cannot access the instance attributes of its class. You cannot addressinstance attributes until after the call. Use the statements before the call to determine the actualparameters for the interface of the instance constructor of the superclass. You can only usestatic attributes or local data to do this.

When you instantiate a subclass, the instance constructors are called hierarchically. The firstnesting level in which you can address instance attributes is the highest-level superclass. Whenyou return to the constructors of the lower-level classes, you can also successively address theirinstance attributes.

In a constructor method, the methods of the subclasses of the class are not visible. If aninstance constructor calls an instance method of the same class using the implicit self-referenceME->, the method is called as it is implemented in the class of the instance constructor, and notin any redefined form that may occur in the subclass you want to instantiate. This is an exceptionto the rule that states that when you call instance methods, the system always calls the methodas it is implemented in the class to whose instance the reference is pointing.

Static ConstructorsEvery class has a static constructor called CLASS_CONSTRUCTOR. As far as the namespacewithin 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 havebeen executed. A static constructor may only be called once per program. Therefore, when youfirst address a subclass, the system looks for the next-highest superclass whose staticconstructor has not yet been executed. It executes the static constructor of that class, followedby those of all classes between that class and the subclass you addressed.

See also:

Overview Graphics [Page 1385]

Page 152: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Inheritance

1384 December 1999

Inheritance: Introductory Example [Page 1388]

Page 153: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Inheritance: Overview Graphic

December 1999 1385

Inheritance: Overview GraphicInheritance: Overview

Class c1

CLASS c1 DEFINITION INHERITING FROM ......

ENDCLASS.

CLASS c1 IMPLEMENTATION....

ENDCLASS.

CLASS c2 DEFINITION INHERITING FROM c1....

ENDCLASS.

CLASS c2 IMPLEMENTATION....

ENDCLASS.

Class c2

Class OBJECT

Class ...

...

...

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

Page 154: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Inheritance: Overview Graphic

1386 December 1999

Single Inheritance

C1 ...

OBJECT

C2...

...

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

Inheritance and Reference Variables

n<class3>class1

CREF3

CREF2

CREF1

class2

class3

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

Page 155: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Inheritance: Overview Graphic

December 1999 1387

class3. All three can point to the object. However, CREF1 can only address the publiccomponents of class1. CREF2 can address the public components of class1 and class2. CREF3can 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 definedwith reference to the superclass to address objects with different method implementations. Whenyou address the superclass, the method has the original implementation, but when you addressthe subclass, the method has the new implementation. Using a single reference variable to callidentically-named methods that behave differently is called polymorphism.

Page 156: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Inheritance: Introductory Example

1388 December 1999

Inheritance: Introductory ExampleThe following simple example shows the principle of inheritance within ABAP Objects. It is basedon the Simple Introduction to Classes [Page 1359]. A new class counter_ten inherits from theexisting 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.

Page 157: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Inheritance: Introductory Example

December 1999 1389

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 methodINCREMENT. To do this, you must change the visibility of the COUNT attribute fromPRIVATE to PROTECTED. The redefined method calls the obscured method of thesuperclass using the pseudoreference SUPER->. The redefined method is aspecialization of the inherited method.

The example instantiates the subclass. The reference variable pointing to it has thetype of the superclass. When the INCREMENT method is called using thesuperclass reference, the system executes the redefined method from the subclass.

Page 158: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Interfaces

1390 December 1999

InterfacesEinführendes Beispiel zu Interfaces [Page 1395]

Classes, their instances (objects), and access to objects using reference variables form thebasics 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 implementsolutions using ABAP Objects.

However, it is often necessary for similar classes to provide similar functions that are codeddifferently in each class but which should provide a uniform point of contact for the user. Forexample, you might have two similar classes, savings account and check account, both of whichhave a method for calculating end of year charges. The interfaces and names of the methods arethe same, but the actual implementation is different. The user of the classes and their instancesmust also be able to run the end of year method for all accounts, without having to worry aboutthe actual type of each individual account.

ABAP Objects makes this possible by using interfaces. Interfaces are independent structures thatyou can implement in a class to extend the scope of that class. The class-specific scope of aclass is defined by its components and visibility sections. For example, the public components ofa class define its public scope, since all of its attributes and method parameters can beaddressed by all users. The protected components of a class define its scope with regard to itssubclasses. (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. Thisallows users to address different classes via a universal point of contact. Interfaces, along withinheritance, provide one of the pillars of polymorphism, since they allow a single method withinan interface to behave differently in different classes.

Defining InterfacesLike classes, you can define interfaces either globally in the R/3 Repository or locally in an ABAPprogram. 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> isenclosed in the statements:

INTERFACE <intf>.

...

ENDINTERFACE.

The definition contains the declaration for all components (attributes, methods, events) of theinterface. You can define the same components in an interface as in a class. The components ofinterfaces do not have to be assigned individually to a visibility section, since they automaticallybelong to the public section of the class in which the interface is implemented. Interfaces do nothave an implementation part, since their methods are implemented in the class that implementsthe interface.

Implementing InterfacesUnlike classes, interfaces do not have instances. Instead, interfaces are implemented by classes.To implement an interface in a class, use the statement

INTERFACES <intf>.

Page 159: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Interfaces

December 1999 1391

in the declaration part of the class. This statement may only appear in the public section of theclass.

When you implement an interface in a class, the components of the interface are added to theother components in the public section. A component <icomp> of an interface <intf> can beaddressed 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 implementationpart 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 thesame set of components. However, the methods of the interface can be implemented differentlyin 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 thepublic scope of each class by the same set of components. If a class does not have any class-specific public components, the interfaces define the entire public face of the class.

Interface ReferencesReference 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 withreference to an interface. This kind of reference variable can contain references to objects ofclasses that implement the corresponding interface.

To define an interface reference, use the addition TYPE REF TO <intf> in the TYPES or DATAstatement. <intf> must be an interface that has been declared to the program before the actualreference declaration occurs. A reference variable with the type interface reference is called ainterface reference variable, or interface reference for short.

An interface reference <iref> allows a user to use the form <iref>-><icomp> to address all visibleinterface components <icomp> of the object to which the object reference is pointing. It allowsthe user to access all of the components of the object that were added to its definition by theimplementation of the interface.

Addressing Objects Using Interface ReferencesTo 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 thefollowing 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>, youcan 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>

Page 160: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Interfaces

1392 December 1999

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 nameto 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 - CastingLike class references, you can assign interface references to different reference variables. Youcan 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 interfacereference <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 castingoperator (?=). The casting operator replaces the assignment operator (=). In the MOVE... ? TOstatement, or when you use the casting operator, there is no static type check. Instead, thesystem checks at runtime whether the object reference in the source variable points to an objectto 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 sameclass as the type of the class variable <cref>.

See also:Overview Graphics [Page 1394]

Page 161: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Interfaces

December 1999 1393

Page 162: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Overview Graphics

1394 December 1999

Overview GraphicsInterfaces

All users

Class C1

Privatecomponents

Methodimplementations

Subclasses of C1

Protected components …

PubliccomponentsA1,...

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

PROTECTED SECTION.…

PRIVATE SECTION.…

ENDCLASS.

CLASS C1 IMPLEMENTATION.

METHOD I1~M1.…

ENDMETHOD.…

ENDCLASS.

INTERFACE I1.DATA: A1 …METHODS: M1 …EVENTS: E1 …

ENDINTERFACE.

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

[Extern] [Extern]

The left-hand side of the diagram shows the definition of a local interface I1 and the declarationand implementation parts of a local class C1 that implements the interface I1 in its publicsection. The interface method I1~M1 is implemented in the class. You cannot implementinterfaces in the other visibility sections.

The right-hand side illustrates the structure of the class with the components in their respectivevisibility areas, and the implementation of the methods. The interface components extend thepublic scope of the class. All users can access the public components specific to the class andthose of the interface.

Page 163: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Interfaces - Introductory Example

December 1999 1395

Interfaces - Introductory ExampleThe following simple example shows how you can use an interface to implement two countersthat are different, but can be addressed in the same way. See also the example in the Classessection.

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.

Page 164: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Interfaces - Introductory Example

1396 December 1999

ENDMETHOD.ENDCLASS.

The interface I_COUNTER contains three methods SET_COUNTER,INCREMENT_COUNTER, and GET_COUNTER. The classes C_COUNTER1 andC_COUNTER2 implement the interface in the public section. Both classes mustimplement the three interface methods in their implementation part. C_COUNTER1is a class for counters that can have any starting value and are then increased byone. 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 bothcases.

The following sections explain how a user can use an interface reference to addressthe objects of both classes:

[Extern]

Page 165: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Triggering and Handling Events

December 1999 1397

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 triggersand trigger events, to which other methods - the handlers - react. This means that the handlermethods are executed when the event occurs.

This section contains explains how to work with events in ABAP Objects. For precise details ofthe relevant ABAP statements, refer to the corresponding keyword documentation in the ABAPEditor.

Triggering EventsTo trigger an event, a class must

• Declare the event in its declaration part

• Trigger the event in one of its methods

Declaring EventsYou declare events in the declaration part of a class or in an interface. To declare instanceevents, 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 thatare passed to the event handler. The parameters are always passed by value. Instance eventsalways contain the implicit parameter SENDER, which has the type of a reference to the type orthe interface in which the event is declared.

Triggering EventsAn instance event in a class can be triggered by any method in the class. Static events can betriggered 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 correspondingactual parameter <fi> in the EXPORTING addition. The self-reference ME is automaticallypassed to the implicit parameter SENDER.

Handling EventsEvents 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.

Page 166: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Triggering and Handling Events

1398 December 1999

Declaring Event Handler MethodsAny 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 eventhandler 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 thedeclaration 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 RAISEEVENT statement. If you want the implicit parameter SENDER to be used as well, you must listit in the interface. This parameter allows an instance event handler to access the trigger, forexample, 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 theclass itself are, in principle, able to handle an event <evt> triggered in a method.

Registering Event Handler MethodsTo allow an event handler method to react to an event, you must determine at runtime the triggerto 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 differenttypes 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 aboveapplies.

For an instance event, you must use the FOR addition to specify the instance for which you wantto register the handler. You can either specify a single instance as the trigger, using a referencevariable <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 whenyou register the handler.

You cannot use the FOR addition for static events:

SET HANDLER... <hi>...

Page 167: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Triggering and Handling Events

December 1999 1399

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

Timing of Event HandlingAfter the RAISE EVENT statement, all registered handler methods are executed before the nextstatement 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 thepossibility 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 handlersare registered dynamically, you should not assume that they will be processed in a particularorder. Instead, you should program as though all event handlers will be executed simultaneously.

Page 168: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Overview Graphic

1400 December 1999

Overview GraphicSuppose we have two classes, C1 and C2:

CLASS C2 DEFINITION.

PUBLIC SECTION.METHODS: M2

FOR EVENT E1 OF C1IMPORTING P1.

PRIVATE SECTION.DATA A2 TYPE I.

ENDCLASS.

CLASS C2 IMPLEMENTATION.

METHOD M2.A2 = P1....

ENDMETHOD.

ENDCLASS.

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 trigger Event handler

The class C1 contains an event E1, which is triggered by the method M1. Class C2 contains amethod M2, which can handle event E1 of class C1.

The following diagram illustrates handler registration:

Page 169: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Overview Graphic

December 1999 1401

R1 H1

H2

C2<1>

C2<2>

E1

….M2

M2

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.

C1<1>

Registering handlers

The program creates an instance of the class C1 and two instances of the class C2. The valuesof 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 forwhich a handler method has been registered.

The handler table contains the names of the handler methods and references to the registeredinstances. The entries in the table are administered dynamically by the SET HANDLERstatement. A reference to an instance in a handler table is like a reference in a reference

Page 170: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Overview Graphic

1402 December 1999

variable. In other words, it counts as a use of the instance, and therefore directly affects itslifetime. In the above diagram, this means that the instances C2<1> and C2<2> are not deletedby the garbage collection, even if H1 and H2 are initialized, so long as their registration is notdeleted from the handler table.

For static events, the system creates an instance-independent handler table for the relevantclass.

When an event is triggered, the system looks in the corresponding event table and executes themethods in the appropriate instances (or in the corresponding class for a static handler method).

Page 171: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Events: Introductory Example

December 1999 1403

Events: Introductory ExampleThe following simple example shows the principle of events within ABAP Objects. It is based onthe Simple Introduction to Classes [Page 1359]. An event critical_value is declared and triggeredin 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 counterIMPORTING 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.

Page 172: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Events: Introductory Example

1404 December 1999

The class COUNTER implements a counter. It triggers the event CRITICAL_VALUEwhen a threshold value is exceeded, and displays the difference. HANDLER canhandle the exception in COUNTER. At runtime, the handler is registered for allreference variables that point to the object.

Page 173: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Events in ABAP Objects - Example

December 1999 1405

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

OverviewThis object works with the interactive list displayed below. Each user interaction triggers an eventin ABAP Objects. The list and its data is created in the class C_LIST. There is a class STATUSfor processing user actions. It triggers an event BUTTON_CLICKED in the AT USER-COMMANDevent. The event is handled in the class C_LIST. It contains an object of the class C_SHIP orC_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 ABAPObjects. However, to produce a simple test output, you can use the followingstatements:

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

• ULINE

• SKIP

• NEW-LINE

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

Declarations

Page 174: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Events in ABAP Objects - Example

1406 December 1999

This example is implemented using local interfaces and classes. Below are the declarations ofthe 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.

*----------------------------------------------------------------

Page 175: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Events in ABAP Objects - Example

December 1999 1407

CLASS C_LIST DEFINITION.

PUBLIC SECTION.

METHODS: FCODE_HANDLER FOR EVENT BUTTON_CLICKED OF STATUSIMPORTING FCODE,

LIST_CHANGE FOR EVENT SPEED_CHANGE OF I_VEHICLEIMPORTING 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 staticmethods and events.

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

Page 176: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Events in ABAP Objects - Example

1408 December 1999

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

Page 177: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Events in ABAP Objects - Example

December 1999 1409

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 eventBUTTON_CLICKED. The instance methods I_VEHICLE~DRIVE and I_VEHICLE~STOP triggerthe instance event I_VEHICLE~SPEED_CHANGE in the classes C_SHIP and C_TRUCK.

Using the Classes in a ProgramThe following program uses the above classes:REPORT OO_EVENTS_DEMO NO STANDARD PAGE HEADING.

Page 178: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Events in ABAP Objects - Example

1410 December 1999

****************************************************************** 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 methodFCODE_HANDLER of the object for the class event BUTTON_CLICKED, and the event handlermethod LIST_CHANGE for the event SPEED_CHANGE of all instances that implement theinterface I_VEHICLE.

Page 179: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Class Pools

December 1999 1411

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

Global Classes and InterfacesClasses and interfaces are both object types. You can define them either globally in the R/3Repository or locally in an ABAP program. If you define classes and interfaces globally, they arestored in special ABAP programs called class pools (type K) or interface pools (type J), whichserve as containers for the respective object types. Each class or interface pool contains thedefinition of a single class or interface. The programs are automatically generated by the ClassBuilder when you create a class or interface.

A class pool is comparable to a module pool or function group. It contains both declarative andexecutable ABAP statements, but cannot be started on its own. Instead, the system can onlyexecute the statements in the class pool on request, that is, when the CREATE OBJECTstatement occurs to create instances of the class.

Interface pools do not contain any executable statements. Instead, they are used as containersfor interface definitions. When you implement an interface in a class, the interface definition isimplicitly included in the class definition.

Structure of a Class PoolClass pools are structured as follows:

Page 180: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Class Pools

1412 December 1999

Definition part for types

TYPES …

CLASS …...

ENDCLASS.

INTERFACE …...

ENDINTERFACE.

Declaration part of class

CLASS … DEFINITION PUBLIC....

ENDCLASS.

Implementation part of class

CLASS … IMPLEMENTATION....

ENDCLASS.

Visibility

Class Pool

CLASS-POOL ...

Class pools contain a definition part for type declarations, and the declaration andimplementation parts of the class.

Differences From Other ABAP ProgramsClass 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. Thisdata is visible in all of the processing blocks in the program. Class pools, on the otherhand, have a definition part, in which you can define data and object types, but no dataobjects or field symbols. The types that you define in a class pool are only visible in theimplementation part of the global class.

• The only processing blocks that you can use are the declaration part and implementationpart of the global class. The implementation part may only implement the methodsdeclared 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 runtimeenvironment. No events occur, and you cannot call any dialog modules or procedures.

Page 181: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Class Pools

December 1999 1413

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

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

Local Classes in Class PoolsThe classes and interfaces that you define in the definition part of a class pool are not visibleexternally. Within the class pool, they have a similar function to local classes and interfaces inother 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 possiblemodularization unit in global classes. Local classes have roughly the same function for globalclasses as subroutines in function groups, but with the significant exception that they are notvisible externally.

Page 182: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Appendix

1414 December 1999

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]

Page 183: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Programs, Screens, and ProcessingBlocks

December 1999 1415

Programs, Screens, and Processing BlocksThis section contains a summary of possible ABAP programs, their screens, and their processingblocks.

Overview

ABAP program with particular type ABAP program with particular type

ABAP runtime environmentABAP runtime environment

Processingblock

Processingblock

Processingblock

Processingblock

Processingblocks

Processingblocks ...

Screens

ABAP programs consist of processing blocks, and can contain screens as components. Bothprocessing blocks and screens are controlled by the ABAP runtime environment.

ABAP ProgramsABAP has the following program types:

• Executable ProgramType 1; introduced with the REPORT statement; can be started by entering the programname or using a transaction code; can be called using SUBMIT; can have its ownscreens.

• Module PoolType M; introduced with the PROGRAM statement; can be started using a transactioncode; can be called using CALL TRANSACTION or LEAVE TO TRANSACTION; havetheir own screens.

• Function GroupType F; introduced with the FUNCTION-POOL statement; non-executable; container forfunction modules; can have its own screens.

Page 184: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Programs, Screens, and Processing Blocks

1416 December 1999

• Class DefinitionType K; introduced with the CLASS-POOL statement; non-executable; container forclasses; cannot (currently) have its own screens.

• Interface DefinitionType J; introduced with the CLASS-POOL statement; non-executable; container forinterfaces; cannot have its own screens.

• Subroutine PoolType S; introduced with the PROGRAM statement; non-executable; container forsubroutines; cannot have its own screens.

• Type GroupsType T; introduced with the TYPE-POOL statement; non-executable; container for typedefinitions; cannot have its own screens.

• Include ProgramType 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 theprograms in which the corresponding include statement occurs.

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

• ScreensDefined using the Screen Painter; can be combined into screen sequences; called usingCALL SCREEN or a transaction code; processed in dialog modules of the correspondingABAP program.

• Selection ScreenDefined within an ABAP program; called by the runtime environment or using the CALLSELECTION-SCREEN statement; processed in event blocks of the corresponding ABAPprogram.

• ListsDefined within an ABAP program; called by the runtime environment; processed in eventblocks of the corresponding ABAP program.

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

Processing BlocksAll 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 ABAPprogram, apart from its global data declarations, belong to a processing block.

ABAP contains the following processing blocks:

Page 185: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Programs, Screens, and ProcessingBlocks

December 1999 1417

Dialog ModuleDefined between the MODULE...ENDMODULE statements in type 1, M, and F programs; has nolocal data area and no parameter interface; called using the MODULE statement in screen flowlogic; processes screens.

Event BlockDefined by one of the event key words; no local data area and no parameter interface; reacts toevents in the ABAP runtime environment. (Exceptions: AT SELECTION-SCREEN and GET areimplemented internally using subroutines, and have a local data area).

We differentiate between:

• Reporting eventsINITIALIZATION

START-OF-SELECTION

GET

END-OF-SELECTION

Called by the ABAP runtime environment while a type 1 program is running; containapplication logic for report programs.

• Selection screen eventsAT 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 ina type 1, M, or F program; process selection screens.

• List eventsTOP-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 useraction on a list in a type 1, M, or F program.

Page 186: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Programs, Screens, and Processing Blocks

1418 December 1999

ProceduresABAP contains the following procedures. They have a local data area and a parameter interface:

• SubroutinesDefined by FORM...ENDFORM in any program except for type K; called using thePERFORM statement in any ABAP program.

• Function modulesDefined by FUNCTION...ENDFUNCTION in type F programs; called using CALLFUNCTION from any ABAP program.

• MethodsDefined by METHOD...ENDMETHOD in global classes in programs with type K, or inlocal classes in any ABAP program; called using CALL METHOD from any ABAPprogram for global classes, and, for local classes, from the program in which the class isdefined.

Page 187: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Introductory Statements for Programs

December 1999 1419

Introductory Statements for ProgramsEach 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 unitsthat 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 PROGRAMThe REPORT and PROGRAM statements currently have the same function. They allow you tospecify the message class of the program and the formatting options for its default list. Whethera program is executable or can only be started using a transaction code depends exclusively onthe program type and not on the statement that introduces it. However, executable programsshould always begin with a REPORT statement, and module pools always with a PROGRAMstatement. Subroutine pools (type S programs) should also always begin with a PROGRAMstatement.

FUNCTION-POOLThe introductory statement FUNCTION-POOL declares a program in which you can definefunction 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 ofthe calling program. For this reason, function groups (type F programs) must always begin with aFUNCTION-POOL statement. This is usually generated by the Function Builder. Type 1, M, or Sprograms should not begin with a FUNCTION-POOL statement, since they would then not sharecommon data areas with the caller. However, in exceptional cases, you can introduce a type 1 ortype M program with FUNCTION-POOL to ensure that externally-called subroutines can processtheir own screens. As in the REPORT and PROGRAM statements, you can specify the messageclass and standard list formatting options of the program in the FUNCTION-POOL statement.

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

Page 188: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Introductory Statements for Programs

1420 December 1999

generated automatically where required by the Class Builder - you should not insert it intoprograms manually.

TYPE-POOLThe introductory statement TYPE-POOL can only be used for type groups (type T programs). Aprogram introduced with the TYPE-POOL statement can only contain global type definitions andconstants declarations. The CLASS-POOL statement is generated automatically where requiredby the ABAP Dictionary - you should not insert it into programs manually.

Page 189: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Overview of ABAP Calls

December 1999 1421

Overview of ABAP CallsABAP programs can contain calls to various other program units. The units can be classifiedaccording 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]

Page 190: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Call Contexts

1422 December 1999

Call Contexts

Internal Calls [Page 1423]

External Procedure Calls [Page 1425]

External Program Calls [Page 1427]

Page 191: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Internal Calls

December 1999 1423

Internal CallsIn an internal call, the called unit is part of the calling program. The source code of the called unitis 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 thecalling program. You can use internal calls for procedures and subscreens.

Internal sessions

ABAP program

Processingblock

Subroutine

Function group(Type F)

Processingblock

Functionmodule

Class pool(Type K)

Method

Method

ProceduresAll procedures [Page 1432] - subroutines, function modules, and methods - can be calledinternally in the program in which they are defined.

• Using an internal call is the recommended and most frequently used method of calling asubroutine.

• Function modules can only be called internally if a function module calls another functionmodule 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 youuse a method of a local class in an ABAP program.

Page 192: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Internal Calls

1424 December 1999

ScreensAll of the screens [Page 1434] belonging to a program can be called internally. When you call ascreen, a screen sequence begins, in which the next screen is defined by the next screenspecified in the current screen.

The special screen types selection screen and list are only ever called internally. You should onlycall subscreens internally.

Page 193: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

External Procedure Calls

December 1999 1425

External Procedure CallsIn 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 callingprogram. 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 anexternal 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 programgroup. Furthermore, when you call methods externally, they and their class form their ownprogram group. Within a program group, interface work areas [Page 131] and the screens of thecalling 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)

Additional Program Group

Function group(Type F)

Main program(Type 1, M, S)

Class

Class pool(Type K)

FORMProcessingblock

FUNCTION FORM METHOD

Interface work areas Interface work areas

ProceduresAll procedures [Page 1432], that is, subroutines, function modules, and methods, can be calledexternally from any ABAP program.

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

Page 194: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

External Procedure Calls

1426 December 1999

be clear which interface work areas [Page 131] and screens will be used by anexternally-called subroutine.

• Function modules are intended for external procedure calls.

• Accessing an externally-visible method of a global class counts as an external procedurecall.

SubscreensYou can call a subscreen screen [Page 1434] externally by specifying an ABAP program otherthan the current program in the CALL SUBSCREEN statement. This program is treated in thesame way as in an external subroutine call. In other words, it is loaded into the program group ofthe calling program, or, if it is a function group, as its own program group in the same internalsession 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 canoccur with external subroutines.

Page 195: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

External Program Calls

December 1999 1427

External Program CallsIn 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. Anyprogram that can have its own screens can be called in an external program call. The mostusual external program calls are for executable programs and transactions assigned to a modulepool.

Internal session m

ABAP program

Processingblock

Internal session n

ExecutableABAP program

Verarbeitungs-blöcke

ABAP runtime environment

Internal session m

ABAP program

Processingblock

Internal session n

ABAP program with screens

ABAP runtime environment

Verarbeitungs-blöckeProcessing

blocks

Verarbeitungs-blöckeVerarbeitungs-

blöckeProcessingblocks

Page 196: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

External Program Calls

1428 December 1999

Executable ProgramsWhen you call an executable program, the program is loaded, and the ABAP runtimeenvironment calls the processors that control its flow.

TransactionsWhen you call a transaction, the program linked to the transaction code is loaded and its initialscreen is processed. The initial screen calls dialog modules in the called program, and thenbranches to its next screen.

Page 197: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Callable Units

December 1999 1429

Callable Units

ABAP Programs [Page 1430]

Procedures [Page 1432]

Screens and Screen Sequences [Page 1434]

Page 198: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Programs

1430 December 1999

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

Internal session m

ABAP program

Processingblock

Internal session n

ABAP program

Verarbeitungs-blöcke

Internal session m

ABAP program

Processingblock

Internal session m

ABAP program

Verarbeitungs-blöckeProcessing

blocks

Verarbeitungs-blöckeVerarbeitungs-

blöckeProcessingblocks

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

SUBMIT …LEAVE TO TRANSACTION ...

Executable ProgramsYou 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 thenew executable program <prog>. The internal session of the calling program is replaced by theinternal session of the new program. When the new program has finished, control returns to thepoint from which the calling program was started.

If you use the AND RETURN addition, the executable program <prog> is started in a newsession. The internal session of the calling program is returned, and control returns to the callingprogram after the new program has finished.

Page 199: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Programs

December 1999 1431

All Programs with ScreensYou can assign a transaction code to any screen of a program. Normally, you assign atransaction code to a single screen in a module pool (type M program). This then allows you tostart 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 transactioncode. This is called the initial screen.

If you use LEAVE TO TRANSACTION, the calling program terminates, and its internal session isreplaced 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, andthe 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 ProgramTo leave a program that you have called, use the ABAP statement

LEAVE PROGRAM.

Page 200: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Procedures

1432 December 1999

ProceduresCalled procedures (subroutines, function modules, and methods) always run in the sameinternal session as the calling program.

Internal session

ABAP program

Processingblock

PERFORM ...CALL FUNCTION …CALL METHOD ...

Procedure

ABAP program Function group Class pool

Subroutine Functionmodule

Method

SubroutinesYou call a subroutine using the

PERFORM <subr>[(<prog>)] ...

statement. If you omit the (<prog>) addition, the subroutine is called internally, that is, it belongsto the calling program and must not be loaded.

If you use the (<prog>) addition, the call is external, that is, the subroutine belongs to theprogram <prog>. When you call the subroutine, the entire program <prog> is loaded into theinternal session of the calling program (if it has not been already). The loaded program belongsto the program group of the calling program. However, if the subroutine belongs to a functiongroup, a new additional program group is created. The program group to which the externalsubroutine 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 ModulesYou call function modules using the

CALL FUNCTION <func> ...

statement. Function module calls are external unless a function module is called by anotherprocedure within the same function group. When you call a function module, its entire functiongroup is loaded into the internal session of the calling program (unless it has already been

Page 201: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Procedures

December 1999 1433

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

MethodsYou 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 sameclass. The class is not reloaded.

If you use <ref> or <class>, the method call applies to the method of the class specified throughthe object reference <ref> or the class name <class>. When you call the method, the entire classpool 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 sharedata and screens with the caller, and from which you cannot call external subroutines.

Leaving a Called ProcedureYou can leave a procedure using the

EXIT.

or

CHECK <logexp>.

statement.

Page 202: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Screens and Screen Sequences

1434 December 1999

Screens and Screen SequencesScreens and their flow logic, which together form dynamic programs, are instances that controlthe flow of an ABAP program by calling a series of dialog modules. Screens can be combinedinto sequences, where the next screen in the sequence can be defined either statically ordynamically. The simplest screen sequence is a single screen. The sequence starts when youcall its first screen. You can do this in a variety of ways.

Internal session m

ABAP program

Verarbeitungs-block

Internal session n

ABAP program

Verarbeitungs-blöckeVerarbeitungs-

blöckeProcessing

blocksVerarbeitungs-

blockProcessingblocks

CALL SCREEN ...

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

Calling Screens Internally from the Same ABAP ProgramIn 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 ofeach screen calls dialog modules in the program that called the screen.

When the screen sequence ends, control returns to the statement after the original CALLSCREEN statement.

Calling Screens as a TransactionA 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

Page 203: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

Screens and Screen Sequences

December 1999 1435

CALL TRANSACTION <tcod> ...

or

LEAVE TO TRANSACTION <tcod> ...

statement. The transaction starts with the initial screen that you specified when you defined thetransaction code. The program of the transaction is started in a new internal session, and hasits own SAP LUW. The screens in the screen sequence call the various dialog modules of themain program.

When the screen sequence is finished, control returns to the program that contained the CALLTRANSACTION statement. If you start a transaction using LEAVE TO TRANSACTION, controlreturns to the point from which the calling program was started.

Calling Screens as a Dialog ModuleA 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 SAPLUW. 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 encapsulatescreen sequences in function groups and call them from an appropriately-programmed functionmodule.

Leaving a Screen SequenceA screen sequence terminates when a screen ends and the defined next screen has the number0.

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 nextscreen is screen 0, the entire screen sequence concludes.

Special Single ScreensThere are three special types of screen:

Selection ScreenA selection screen is a special screen, created using ABAP statements. You can only call themusing the

CALL SELECTION-SCREEN <dynnr> ...

statement. The selection screen is processed (reaction to user input in the selection screenevents) in the calling program.

Page 204: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

Screens and Screen Sequences

1436 December 1999

ListEach screen in a screen sequence has a corresponding list system of twenty levels. You canstart 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 screenused for lists. This replaces the current screen. On this screen, you can display a basic list andup to 19 detail lists. List processing (reacting to user actions in list events) takes place in thecalling 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.

SubscreensIn the PBO event of the flow logic of a screen, you can call a subscreen using the followingstatement:

CALL SUBSCREEN <area> INCLUDING [<prog>] <dynnr>.

The screen of a subscreen that you call is placed in the subscreen area <area> on the mainscreen.

If you do not specify a program <prog>, the system uses a screen from the current ABAPprogram. 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 subroutinecall. In other words, it is loaded into the program group of the calling program, or, if it is a functiongroup, as its own program group in the same internal session as the calling ABAP program.

Page 205: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1437

ABAP Statement OverviewThe following is an alphabetical classification of the most important generally-released ABAPstatements.

A B C D E F G H I L M N O P R S T U W

A ADD for Single FieldsAdds two single fields.

SyntaxADD <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 FieldsAdds sequences of fields.

SyntaxADD <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 variantsallow you to restrict the fields to a partial sequence, to include <m> in the sum, or to perform theoperation for a sequence of consecutive fields.

ADD-CORRESPONDINGAdds components of structures.

SyntaxADD-CORRESPONDING <struc1> TO <struc2>.

Adds together all of the components of structures <struc1> and <struc2> that have identicalnames, and places the results in the corresponding components of <struc2>.

Page 206: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1438 December 1999

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

SyntaxALIASES <alias> FOR <intf~comp>.

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

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

SyntaxAPPEND <line>|LINES OF <jtab> TO <itab>.

Appends one line <line> or several lines of an internal table <jtab> to the index table <itab>.

ASSIGNAssigns a field to a field symbol.

SyntaxASSIGN <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 BlocksEvent keywords for defining event blocks for screen events.

SyntaxAT SELECTION-SCREEN...

AT LINE-SELECTION.

AT USER-COMMAND.

AT PFn.

User actions on selection screens or lists trigger events in the ABAP runtime environment. Theevent keywords define event blocks, which are called when the corresponding event occurs.

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

SyntaxAT NEW <f>.

Page 207: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1439

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. Thestatements between AT and ENDAT are executed whenever the corresponding control levelchange occurs.

AUTHORITY-CHECKChecks the authorization of a user.

SyntaxAUTHORITY-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 authorizationobject <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 thecorresponding authorization field.

B BACKRelative positioning for output in a list.

SyntaxBACK.

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

BREAK-POINTStarts the ABAP Debugger.

SyntaxBREAK-POINT.

Interrupts program execution and starts the Debugger. This allows you to test your programs byhalting them at any point.

Page 208: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1440 December 1999

C CALL CUSTOMER-FUNCTIONCalls a customer function module.

SyntaxCALL CUSTOMER-FUNCTION <func>...

Similar to CALL FUNCTION. The function module that it calls must be programmed and activatedby a customer using the modification concept.

CALL FUNCTIONCalls a function module.

SyntaxCALL 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 thetype of call that you use. You can also use update function modules in transactions, and callfunction modules asynchronously. The remaining additions are used for the parameter interfaceof the function module, in which you can specify actual parameters and determine how to handleexceptions.

CALL DIALOGCalls a dialog module.

SyntaxCALL 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 ofscreens. It does not have to be called using a transaction code, and runs in the same SAP LUWas the program that called it. The additions allow you to skip the first screen in the chain andpass actual parameters to and from the parameter interface of the dialog module.

Page 209: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1441

CALL METHODCalls a method in ABAP Objects.

SyntaxCALL 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 toand from the method and handle its exceptions.

CALL METHOD OFCalls a method in OLE2 Automation.

SyntaxCALL METHOD OF <obj> <m>.

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

CALL SCREENCalls a sequence of screens.

SyntaxCALL 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 thechain belong to the same ABAP program. The chain ends when a screen has the next screennumber 0. The additions allow you to call a single screen as a modal dialog box.

CALL SELECTION-SCREENCalls a selection screen.

SyntaxCALL 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 ATSELECTION-SCREEN events. The additions allow you to call a selection screen as a modaldialog box.

CALL TRANSACTIONCalls a transaction.

Page 210: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1442 December 1999

SyntaxCALL TRANSACTION <tcod>

[AND SKIP FIRST SCREEN][USING <itab>].

Calls the transaction <tcod> while retaining the data in the calling program. At the end of thetransaction, control returns to the point from which the transaction was called. The additionsallow you to skip the first screen of the transaction or pass an internal table for batch input to it.

CASEConditional branching.

SyntaxCASE <f>.

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

CATCHCatches runtime errors.

SyntaxCATCH SYSTEM-EXCEPTIONS <except1> = <rc1>... <exceptn> = <rcn>.

Introduces a CATCH area, which concludes with an ENDCATCH statement. If a catchableruntime error <excepti> occurs within this block, the current block terminates immediately, andthe program jumps directly to the corresponding ENDCATCH statement, filling SY-SUBRC with<rci>.

CHECKConditional termination of a loop pass or a processing block.

SyntaxCHECK <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 programis not currently processing a loop, the current processing block terminates. There are specialforms of the CHECK statement for use with selection tables and in GET event blocks.

CLASS - DeclarationDeclares a class in ABAP Objects.

Page 211: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1443

SyntaxCLASS <class> DEFINITION [PUBLIC]

[INHERITING FROM <superclass>][DEFERRED][LOAD].

This statement introduces the declaration part of a class <class>. The declaration part concludeswith ENDCLASS, and contains the declarations of all components in the class. The PUBLICaddition is generated by the Class Builder, and defines a global class in the class library. TheINHERITING FROM addition allows you to derive the class <class> from a superclass<superclass>. The DEFERRED addition declares the class before it is actually defined. TheLOAD addition loads a class explicitly from the class library.

CLASS – ImplementationImplementation of a class in ABAP Objects.

SyntaxCLASS <class> IMPLEMENTATION.

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

CLASS-DATADeclares static attributes of a class or interface.

SyntaxCLASS-DATA <a>...

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

CLASS-METHODSDeclares static methods of a class or interface.

SyntaxCLASS-METHODS <meth>...

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

CLASS-EVENTSDeclares static events of a class or interface.

Page 212: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1444 December 1999

SyntaxCLASS-EVENTS <evt>...

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

CLEARResets a variable to its initial value.

SyntaxCLEAR <f>.

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

CLOSE DATASETCloses a file.

SyntaxCLOSE DATASET <dsn>.

Closes a file <dsn> on the application server previously opened with the OPEN DATASETstatement.

CLOSE CURSORCloses a database cursor.

SyntaxCLOSE CURSOR <c>.

Closes a cursor opened using the OPEN CURSOR statement.

COLLECTInserts lines into an internal table in summarized form.

SyntaxCOLLECT <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 inserta new line. Instead, it adds the values from the numeric fields of the work area <line> to thevalues in the corresponding fields of the existing table entry.

Page 213: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1445

COMMITConcludes an SAP LUW.

SyntaxCOMMIT WORK [AND WAIT].

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

COMMUNICATIONAllows communication between programs.

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

COMPUTEPerforms numeric operations.

SyntaxCOMPUTE <n> = <expression>.

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

CONCATENATECombines a series of strings into a single string.

SyntaxCONCATENATE <c1>... <cn> INTO <c> [ SEPARATED BY <s> ].

The strings <c1> to <cn> are concatenated, and the result placed in <c>. The SEPARATED BYaddition allows you to specify a string <s> to be placed between the strings.

Page 214: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1446 December 1999

CONDENSERemoves spaces from a string.

SyntaxCONDENSE <c> [NO-GAPS].

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

CONSTANTSDeclares constant data objects.

SyntaxCONSTANTS <c>... VALUE [<val> | IS INITIAL]...

The syntax is similar to DATA, except that the VALUE addition is required, and that internaltables and deep structures cannot be declared as constants. The starting value that you assign inthe VALUE addition cannot be changed during the program.

CONTINUEEnds a loop pass.

SyntaxCONTINUE.

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

CONTEXTSDeclares a context.

SyntaxCONTEXTS <c>.

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

CONTROLSDefines a control.

SyntaxCONTROLS <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 tabstripcontrol.

Page 215: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1447

CONVERT for DatesConverts a data into an inverted date form.

SyntaxCONVERT 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 thesmaller numerical value.

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

SyntaxCONVERT 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 timestamp <tst> will be converted to the correct date <d> and time <t> for the time zone <tz>.

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

SyntaxCONVERT TEXT <text> INTO SORTABLE CODE <x>.

<text> must have type C and <x> must have type X. The string is then converted so that therelative order of the characters allows them to be sorted alphabetically in the current textenvironment.

CREATE OBJECT in ABAP ObjectsCreates an object in ABAP Objects.

SyntaxCREATE OBJECT <cref>.

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

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

Page 216: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1448 December 1999

SyntaxCREATE OBJECT <obj> <class>.

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

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

SyntaxDATA <f>... [TYPE <type>|LIKE <obj>]... [VALUE <val>].

Declares a variable <f> with the fully-defined data type <type> or the same data type as anotherdata object <obj>. The data type <type> can be D, F, I, T, a type defined locally in the programusing the TYPES statement, or a type from the ABAP Dictionary. The data object <obj> is a dataobject or line of an internal table that has already been defined. The VALUE addition allows youto specify a starting value.

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

SyntaxDATA <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 thefield. 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 notspecify a number of decimal places, it is set to none. If you do not specify a type, the systemuses the default type C.

SyntaxDATA <f> TYPE <itab>.

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

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

SyntaxDATA <f> TYPE REF TO <class>|<interface>.

Page 217: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1449

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

SyntaxDATA: BEGIN OF <structure>, ... <fi>..., ...END OF <structure>.

Combines the variables <fi> to form the structure <structure>. You can address the individualcomponents of a structure by placing a hyphen between the structure name and the componentname: <structure>-<fi>.

SyntaxDATA <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 AreasDeclares shared data areas in a program.

SyntaxDATA: 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 oneprogram. These data areas use the same memory addresses for all programs that are loadedinto the same internal session.

DEFINEDefines a macro.

SyntaxDEFINE <macro>.

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

DELETE for FilesDeletes files on the application server.

SyntaxDELETE DATASET <dsn>.

Page 218: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1450 December 1999

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

DELETE for Database Table EntriesDeletes entries from database tables.

SyntaxDELETE FROM <dbtab> WHERE <cond>.

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

SyntaxDELETE <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 thedatabase table with the same primary key as one of the lines in the internal table <itab>. Thework area <wa> or the lines of the internal table <itab> must be at least as long as the primarykey of the database table and have the same alignment.

DELETE for Cluster Database TablesDeletes data clusters from cluster database tables.

SyntaxDELETE FROM DATABASE <dbtab>(<ar>) ID <key>.

Deletes the entire data cluster from the area <ar> with the name <key> from the cluster databasetable <dbtab>.

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

SyntaxDELETE FROM SHARED BUFFER <dbtab>(<ar>) ID <key>.

Deletes the data cluster for the area <ar> with the name <key> stored in the cross-transactionapplication buffer for the table <dbtab>.

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

SyntaxDELETE TABLE <itab> FROM <wa>.

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

Page 219: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1451

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

SyntaxDELETE <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 ineach expression must be a component of the line structure.

SyntaxDELETE ADJACENT DUPLICATE ENTRIES FROM <itab> [COMPARING... ].

Deletes adjacent duplicate entries, either by comparing the key fields or the comparison fieldsspecified explicitly in the COMPARING addition.

DELETE for Lines from Index TablesDeletes lines from index tables.

SyntaxDELETE <itab> [INDEX <idx>].

If you use the INDEX option, deletes the line with the index <idx> from the table <itab>. If you donot use the INDEX option, the statement can only be used within a LOOP … ENDLOOPconstruction. In this case, it deletes the current line.

SyntaxDELETE <itab> [FROM <n1>] [TO <n2>] [WHERE <cond>].

Deletes all rows from <itab> with index between <n1 > and <n 2 > an which satisfy the WHEREcondition. If you do not use the FROM addition, the system deletes lines starting at the beginningof 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 firstoperand in each expression must be a component of the line structure of the internal table.

DEMANDRetrieves values from a context instance.

SyntaxDEMAND <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 MESSAGESaddition allows you to control how messages from the context are handled in the program.

DESCRIBE DISTANCEDetermines the distance between two fields.

Page 220: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1452 December 1999

SyntaxDESCRIBE DISTANCE BETWEEN <f1> AND <f2> INTO <f3>.

Writes the distance in bytes between fields <f1> and <f2> to <f3>, always including the length ofthe field that occurs first in memory.

DESCRIBE FIELDDescribes the attributes of a field.

SyntaxDESCRIBE 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 thecorresponding variables. You can use any number of additions in a single statement.

DESCRIBE LISTDescribes the attributes of a list.

SyntaxDESCRIBE 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 ofpages, a line of a list on a given page, or various attributes of a page to variables.

DESCRIBE TABLEDescribes the attributes of an internal table.

SyntaxDESCRIBE TABLE [LINES <l>] [OCCURS<n>] [KIND <k>].

Depending on the additions you use, writes the number of lines occupied, the value specified forthe INITIAL SIZE of the table, or the table type into a corresponding variable.

DIVIDEDivides one field by another.

SyntaxDIVIDE <n> BY <m>.

Page 221: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1453

Divides the content of <n> by <m>, and places the result in <n>. The equivalent of n = n / m.

DIVIDE-CORRESPONDINGDivides matching components of structures.

SyntaxDIVIDE-CORRESPONDING <struc1> BY <struc2>.

Divides all matching components of the structures <struc1> and <struc2> and places the resultsinto the corresponding components of <struc1>.

DOIntroduces a loop.

SyntaxDO [<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 allowsyou to process a sequence of fields the same distance apart in memory.

E EDITOR-CALLLoads an ABAP program or internal table into a text editor.

SyntaxEDITOR-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 itusing standard editor functions.

ELSEIntroduces a statement block in an IF control structure.

SyntaxELSE.

If the logical expression in an IF statement is false, ELSE introduces the statement block to beexecuted instead.

Page 222: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1454 December 1999

ELSEIFIntroduces a statement block in an IF control structure.

SyntaxELSEIF <logexp>.

If the logical expression in the preceding IF is false and <logexp> is true, ELSEIF introduces thestatement block that will be executed.

END-OF-DEFINITIONConcludes a macro definition.

SyntaxEND-OF-DEFINITION.

This statement concludes a macro definition introduced with DEFINITION.

END-OF-PAGEEvent keyword for defining an event block for a list event.

SyntaxEND-OF-PAGE.

Whenever the page footer is reached while a list is being created, the runtime environmenttriggers the END-OF-PAGE event, and the corresponding event block is executed.

END-OF-SELECTIONEvent keyword for defining an event block for a reporting event.

SyntaxEND-OF-SELECTION.

Once a logical database has read all of the required lines and passed them to the executableprogram, the runtime environment triggers the END-OF-SELECTION event, and thecorresponding event block is executed.

ENDATConcludes a statement block in control level processing.

SyntaxENDAT.

The statement concludes a control level processing block introduced with the AT statement.

Page 223: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1455

ENDCASEConcludes a CASE control structure.

SyntaxENDCASE.

This statement concludes a control structure introduced with the CASE statement.

ENDCATCHConcludes a CATCH area.

SyntaxENDCATCH.

The statement concludes an exception handling area introduced with CATCH.

ENDCLASSConcludes a class definition.

SyntaxENDCLASS.

This statement concludes a class declaration or implementation introduced with CLASS.

ENDDOConcludes a DO loop.

SyntaxENDDO.

This statement concludes a loop introduced with DO.

ENDEXECConcludes a Native SQL statement.

SyntaxENDEXEC.

This statement concludes a Native SQL statement introduced with EXEC SQL.

ENDFORMConcludes a subroutine.

Page 224: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1456 December 1999

SyntaxENDFORM.

This statement concludes a subroutine definition introduced with FORM.

ENDFUNCTIONConcludes a function module.

SyntaxENDFUNCTION.

This statement concludes a function module introduced with FUNCTION.

ENDIFConcludes an IF control structure.

SyntaxENDIF.

This statement concludes a control structure introduced using IF.

ENDINTERFACEConcludes an interface definition.

SyntaxENDINTERFACE.

This statement concludes an interface definition introduced with INTERFACE.

ENDLOOPConcludes a loop.

SyntaxENDLOOP.

This statement concludes a loop introduced with LOOP.

ENDMETHODConcludes a method.

SyntaxENDMETHOD.

This statement concludes a method implementation introduced with METHOD.

Page 225: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1457

ENDMODULEConcludes a dialog module.

SyntaxENDMODULE.

This statement concludes a dialog module introduced with MODULE.

ENDONConcludes a conditional statement block.

SyntaxENDON.

This statement concludes a conditional statement block introduced with ON CHANGE.

ENDPROVIDEConcludes a PROVIDE loop.

SyntaxENDPROVIDE.

This statement concludes a loop introduced with PROVIDE.

ENDSELECTConcludes a SELECT loop.

SyntaxENDSELECT.

This statement concludes a loop introduced with SELECT.

ENDWHILEConcludes a WHILE loop.

SyntaxENDWHILE.

This statement concludes a loop introduced with WHILE.

EVENTSDefines events in classes or interfaces.

Page 226: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1458 December 1999

SyntaxEVENTS <evt> EXPORTING.. VALUE(<ei>) TYPE type [OPTIONAL]...

The event <evt> can be declared in the declaration part of a class or within an interfacedefinition, and may have EXPORTING parameters that are passed to the event handler. Theparameters are always passed by value.

EXEC SQLIntroduces a Native SQL statement.

SyntaxEXEC SQL [PERFORMING <form>].

Between EXEC SQL and the ENDEXEC statement, you can include a database-specific NativeSQL statement. The PERFORMING addition allows you to pass a multiple-line selection line byline to a subroutine.

EXITTerminates a loop or processing block.

SyntaxEXIT.

Within a loop: The entire loop is terminated, and processing continues with the first statementfollowing the loop.

Outside a loop: Terminates the current processing block.

In a reporting event: Jumps directly to the output list.

EXIT FROM STEP-LOOPEnds a step loop.

SyntaxEXIT FROM STEP-LOOP.

Terminates step loop processing. A step loop is a way of displaying a table on a screen.

EXIT FROM SQLTerminates Native SQL processing.

SyntaxEXIT FROM SQL.

This statement may occur within a subroutine called using the PERFORMING addition in theEXEC SQL statement. The entire subroutine is processed, but no more subsequent lines of theselection are processed.

Page 227: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1459

EXPORTExports a data cluster.

SyntaxEXPORT... <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 datacluster in the cross-program ABAP memory of the current internal session, in a cluster databasetable <dbtab>, or in the cross-transaction application buffer of the table <dbtab>.

EXTRACTCreates an extract dataset and adds lines to it.

SyntaxEXTRACT <fg>.

The first EXTRACT statement in a program creates an extract dataset and adds the first entry toit. Each subsequent EXTRACT statement adds a new entry. Each extract entry contains thefields of the field group <fg> and, at the beginning, the fields of the field group HEADER as a sortkey.

F FETCHUses a cursor to read entries from a database table.

SyntaxFETCH NEXT CURSOR <c> INTO <target>.

If the cursor <c> is linked with a selection in a database table, FETCH writes the next line of theselection into the flat target area <target>.

FIELD-GROUPSDeclares a field group for an extract dataset.

SyntaxFIELD-GROUPS <fg>.

Declares the field group <fg>. Field groups define the line structure of an extract dataset. Youcan define a special field group called HEADER as the sort key. When you fill the extract dataset,the HEADER field group precedes each entry.

Page 228: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1460 December 1999

FIELD-SYMBOLSDeclares a field symbol.

SyntaxFIELD-SYMBOLS <FS> [<type>|STRUCTURE <s> DEFAULT <wa>].

Field symbols are placeholders or symbolic names for fields. The pointed brackets in the name ofa field symbol are part of its syntax. The <type> addition allows you to specify a type. TheSTRUCTURE addition imposes a structure on the data object assigned to the field symbol.

FORMDefines a subroutine.

SyntaxFORM <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 parameterinterface. The subroutine definition is concluded with the ENDFORM statement.

FORMATSets formatting options for list output.

SyntaxFORMAT... <optioni> [ON|OFF]...

The formatting options <optioni> (color, for example) apply to all subsequent list output until theyare disabled with the OFF option.

FREEReleases memory space.

SyntaxFREE <itab>.

FREE MEMORY ID(<key>).

FREE OBJECT <obj>.

This statement deletes an internal table, a data cluster in ABAP memory, or an external object inOLE2 Automation, depending on the form of the statement used. It also releases the memoryoccupied by the object.

Page 229: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1461

FUNCTIONDefines a function module.

SyntaxFUNCTION <func>.

Introduces the function module <func>. This statement does not have to be entered in the ABAPEditor, but is automatically generated by the Function Builder in the ABAP Workbench. Thefunction module definition is concluded with the ENDFUNCTION statement.

FUNCTION-POOLIntroduces a function group.

SyntaxFUNCTION-POOL.

The first statement in a function group. This statement does not have to be entered by hand, butis generated automatically by the Function Builder in the ABAP Workbench. A function group isan ABAP program that contains function modules.

G GETEvent keyword that defines event blocks for reporting events.

SyntaxGET <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 correspondingevent block is executed. The FIELDS addition allows you to specify explicitly the columns of thenode that the logical database should retrieve.

GET BITReads an individual bit.

SyntaxGET BIT <n> OF <f> INTO <g>.

Reads the bit at position <n> of the hexadecimal field <f> into the field <b>.

GET CURSORDetermines the cursor position on a screen or in an interactive list event.

Page 230: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1462 December 1999

SyntaxGET 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 lengthof a field or line into the corresponding variables.

GET LOCALE LANGUAGEFinds out the current text environment.

SyntaxGET LOCALE LANGUAGE <lg> COUNTY <c> MODIFIER <m>.

Returns the current language, country ID and any modifier into the corresponding variables.

GET PARAMETERFinds out the value of a SPA/GPA parameter.

SyntaxGET PARAMETER ID <pid> FIELD <f>.

Places the value of the SPA/GPA parameter <pid> from the user-specific SAP memory into thevariable <f>.

GET PF-STATUSFinds out the current GUI status.

SyntaxGET PF-STATUS <f> [PROGRAM <prog>] [EXCLUDING <itab>].

Returns the name of the current GUI status (the same as SY-PFKEY) into the variable <f>. ThePROGRAM addition writes the name of the ABAP program to which the status belongs into thevariable <prog>. The EXCLUDING addition returns a list of all currently inactive function codesinto the internal table <itab>.

GET PROPERTYFinds out a property of an OLE2 Automation object.

Page 231: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1463

SyntaxGET PROPERTY OF <obj> <p> = <f>.

Returns the property <p> of an external OLE2 Automation object to the variable <f>.

GET RUN TIME FIELDMeasures the runtime in microseconds.

SyntaxGET RUN TIME FIELD <f>.

The first time the statement is executed, the variable <f> is set to zero. In each further call, theruntime since the first call is written to <f>.

GET TIMESynchronizes the time.

SyntaxGET TIME [FIELD <f>].

Refreshes the system fields SY-UZEIT, SY-DATUM, SY-TIMLO, SY-DATLO, and SY-ZONLO. Ifyou use the FIELD addition, the variable <f> is filled with the current time.

GET TIME STAMP FIELDReturns a time stamp.

SyntaxGET 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 HIDEStores information about list lines.

SyntaxHIDE <f>.

During list creation, this statement stores the contents of the field <f> and the current line numberin the internal HIDE area. When the cursor is positioned on a line in an interactive list event, thestored value is returned to the field <f>.

Page 232: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1464 December 1999

I IFConditional branching.

Introduces a new branch.

SyntaxIF <logexp>.

Opens an IF control structure that must be concluded with ENDIF. The system evaluates thelogical expression <logexp>, and processes different statement blocks depending on the result.

IMPORTImports a data cluster.

SyntaxIMPORT... <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 thecross-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 DIRECTORYCreates the directory of a data cluster from a cluster database.

SyntaxIMPORT 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 TODATABASE.

INCLUDEInserts an include program in another program.

SyntaxINCLUDE <incl>.

This has the same effect as inserting the source code of the include program <incl> at the sameposition in the program as the INCLUDE statement. Includes are not loaded dynamically at

Page 233: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1465

runtime, but are automatically expanded when the program is loaded. An include must have theprogram type I.

INCLUDE STRUCTUREIncludes a structure within another.

SyntaxINCLUDE STRUCTURE <s>|TYPE <t>.

Adopts the structure of an ABAP Dictionary structure <s> or a structured data type <t> as part ofa new structure declared using DATA BEGIN OF …

INITIALIZATIONEvent keyword that defines an event block for a reporting event.

SyntaxINITIALIZATION.

Only occurs in executable programs. The ABAP runtime environment triggers theINITIALIZATION event before the selection screen is processed, at which point thecorresponding event block is processed.

INSERT for Database TablesInserts lines into a database table.

SyntaxINSERT <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 thedatabase table <dbtab>. The addition ACCEPTING DUPLICATE KEYS prevents a runtime errorfrom occurring if two entries have the same primary key. Instead, it merely discards the duplicate.

INSERT for Field GroupsDefines the structure of field groups for extract datasets.

SyntaxINSERT <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 TableInserts lines in an internal table of any type.

Page 234: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1466 December 1999

SyntaxINSERT <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 TablesInserts lines in index tables.

SyntaxINSERT <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 beinserted using the FROM and TO additions. If you omit the INDEX addition, you can only use thestatement within a LOOP construction. In this case, the new line is inserted before the currentline.

INSERT for ProgramsInserts ABAP programs into the program library.

SyntaxINSERT REPORT <prog> FROM <itab>.

The lines of the internal table <itab> are added to the program library as the program <prog>.

INTERFACEDefines an interface in ABAP Objects.

SyntaxINTERFACE <ifac> [DEFERRED]

[LOAD].

Introduces the definition of the interface <interface>. The definition concludes withENDINTERFACE, and contains the declaration of all of the components in the interface. You canuse the DEFERRED addition to declare the interface before you actually define it. The LOADaddition loads the interface definition explicitly from the class library.

INTERFACESImplements interfaces in a class.

SyntaxINTERFACES <ifac>.

Page 235: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1467

Used in a class declaration: This statement adds the components of the interface to the existingclass definition.

Used in an interface definition: Forms a compound interface.

L LEAVE for ScreensLeaves a screen.

SyntaxLEAVE SCREEN.

Terminates the current screen and calls the next screen. The next screen can either be definedstatically in the screen attributes or set dynamically using the SET SCREEN statement.

SyntaxLEAVE TO SCREEN <scr>.

Terminates the current screen and calls the dynamically-defined next screen <scr>.

LEAVE for Lists During Screen ProcessingSwitches between screen and list processing.

SyntaxLEAVE TO LIST-PROCESSING [AND RETURN TO SCREEN <scr>].

This statement allows you to create and display a list while processing a series of screens. Theaddition allows you to specify the next screen (to which you return after the list has beendisplayed). If you do not use the addition, screen processing resumes with the PBO of the currentscreen.

SyntaxLEAVE LIST-PROCESSING.

Allows you to switch back explicitly from list processing to screen processing.

LEAVE for ProgramsTerminates an ABAP program.

SyntaxLEAVE [PROGRAM].

Terminates the current program and returns to the point from which it was called.

SyntaxLEAVE TO TRANSACTION <tcod> [AND SKIP FIRST SCREEN].

Page 236: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1468 December 1999

Terminates the current program and starts a new transaction <tcod>. The addition allows you toskip the initial screen of the transaction.

LOCALProtects global data against changes.

SyntaxLOCAL <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 ExtractsStarts a loop through an extract dataset.

SyntaxLOOP.

Loops through an extract dataset. The loop is concluded with ENDLOOP. When the LOOPstatement is executed, the system finishes creating the extract dataset, and loops through all ofits entries. One entry is read in each loop pass. The values of the extracted data are placed inthe output fields of the field group within the loop.

LOOP Through Internal TablesStarts a loop through an internal table.

SyntaxLOOP 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 tothe field symbol <FS>, or not assigned at all. The first operand in each part of <logexp> must bea component of the internal table. The pointed brackets in the field symbol name are part of itssyntax.

With index tables, you can use the additions FROM <n> and TO <n> to restrict the lines that areread by specifying an index range.

LOOP Through Screen FieldsStarts a loop through the special table SCREEN.

Page 237: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1469

SyntaxLOOP AT SCREEN...

Similar to a loop through an internal table. The system table SCREEN contains the names andattributes of all of the fields on the current screen.

M MESSAGEOutputs a message.

SyntaxMESSAGE <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 typedetermines how the message is displayed, and how the program reacts. The WITH additionallows you to fill placeholders in the message text. The RAISING addition in function modulesand methods allows you to terminate the procedure and trigger the exception <exception>.

METHODIntroduces the implementation of a method in a class.

SyntaxMETHOD <meth>.

Only occurs in the implementation part of classes. This statement begins a statement block thatmust be concluded with ENDMETHOD. You do not have to specify any interface parameters,since these are defined in the method declaration.

METHODSDeclares methods in classes and interfaces.

SyntaxMETHODS <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. Theadditions define the parameter interface and exceptions of the method. The function of themethod must be implemented using the METHOD statement.

Page 238: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1470 December 1999

MODIFY for Database TablesInserts or changes lines in database tables.

SyntaxMODIFY <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 primarykey. Works like UPDATE if a line already exists with the same primary key.

MODIFY for All Internal TablesChanges the contents of lines in any type of internal table.

SyntaxMODIFY 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 tochange.

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 istrue. The first operand in each comparison of the logical expression must be a component of theline structure.

MODIFY for Index TablesChanges the contents of lines in index tables.

SyntaxMODIFY <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 theINDEX addition, you can only use the statement within a LOOP. This changes the current line.

MODIFY for ListsChanges a line of a list.

SyntaxMODIFY 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>

Page 239: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1471

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 SCREENChanges the table SCREEN.

SyntaxMODIFY SCREEN...

Like changing an internal table. This statement allows you to change the attributes of fields onthe current screen.

MODULEIntroduces a dialog module.

SyntaxMODULE <mod> OUTPUT |[INPUT].

Introduces the dialog module <mod>. The OUTPUT and INPUT additions designate the moduleas a PBO or PAI module respectively. Each module must conclude with the ENDMODULEstatement.

MOVEAssigns values.

SyntaxMOVE <f1> TO <f2>.

Assigns the contents of the data object <f1> to the variable <f2>, with automatic type conversionif necessary. Equivalent to <f2> = <f1>.

MOVE-CORRESPONDINGAssigns values between identically-named components of structures.

SyntaxMOVE-CORRESPONDING <struc1> TO <struc2>.

The contents of the components of the structure <struc1> are assigned to the identically-namedcomponents of the structure <struc2>.

MULTIPLYMultiplies two individual fields.

Page 240: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1472 December 1999

SyntaxMULTIPLY <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-CORRESPONDINGMultiplies components of structures.

SyntaxMULTIPLY-CORRESPONDING <struc1> BY <struc2>.

Multiplies all of the identically-named components of <struc1> and <struc2> and places theresults in the components in <struc1>.

N NEW-LINEInserts a line break in a list.

SyntaxNEW-LINE [NO-SCROLLING|SCROLLING].

Positions the list output on a new line. The NO-SCROLLING addition locks the line againsthorizontal scrolling. To lift the lock, use the SCROLLING addition.

NEW-PAGEInserts a page break in a list.

SyntaxNEW-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 controlhow the page header is displayed, the length and width of the page, and the print output.

NODESDeclares an interface work area.

SyntaxNODES <node>.

Page 241: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1473

Declares a variable with the same data type and the same name as a data type from the ABAPDictionary. Structures in main programs and subroutines declared with nodes use a commondata area. This statement is used in conjunction with logical databases.

O ON CHANGEIntroduces a branch.

SyntaxON CHANGE OF <f> [OR <f1> OR <f2>...].

Opens an ON control structure, concluded with ENDON. The statement block is executedwhenever the contents of the field <f> or one of the other fields <fi> has changed since thestatement was last executed.

OPEN CURSOROpens a database cursor.

SyntaxOPEN CURSOR [WITH HOLD] <c> FOR SELECT <result> FROM <source> [WHERE <condition>] [GROUP BY <fields>] [HAVING <cond>] [ORDER BY <fields>].

Opens a cursor <c> with type CURSOR for a SELECT statement. All of the clauses of theSELECT statement apart from the INTO clause can be used. The INTO clause is set in theFETCH statement. If you use the WITH HOLD addition, the cursor is not closed when a databasecommit occurs.

OPEN DATASETOpens a file.

SyntaxOPEN 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 forreading or writing, whether the contents are to be interpreted in binary or character form, theposition in the file, the location to which an operating system can be written, and allow you toexecute an operating system command.

Page 242: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1474 December 1999

OVERLAYOverlays a character string with another.

SyntaxOVERLAY <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 spacesare overwritten.

P PACKConverts type C variables into type P.

SyntaxPACK <f> TO <g>.

Packs the string <f> and places it in the field <g>. This can be reversed with the UNPACKstatement.

PARAMETERSDeclares parameters for a selection screen.

SyntaxPARAMETERS <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 alsocreates an input field for <p> on the relevant selection screen. You can use the additions todefine default values, accept lowercase input, define the field as required, check values, define acheckbox or radio button, prevent the field from being displayed on the selection screen, ormodify the field.

PERFORMCalls a subroutine.

Page 243: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1475

SyntaxPERFORM <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 FOUNDaddition prevents a runtime error from occurring if the subroutine does not exist. You must usethe USING and CHANGING additions to supply values to the interface parameters of thesubroutine. The ON COMMIT addition delays the execution of the subroutine until the nextCOMMIT WORK statement.

POSITIONAbsolute positioning of the output on a list.

SyntaxPOSITION <col>.

Positions the list output in column <col>.

PRINT-CONTROL for Print FormatSpecifies the print format.

SyntaxPRINT-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 LinesCreates index lines in the spool file.

SyntaxPRINT-CONTROL INDEX-LINE <f>.

Writes the contents of the field <f> into an index line at the end of the current print line. The indexline is not printed. In optical archiving, the spool system separates the lists into a data file and adescription file containing the index lines.

PRIVATEDefines the private section of a class.

Page 244: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1476 December 1999

SyntaxPRIVATE SECTION.

Introduces the declaration of all of the components of a class that are only visible in the classitself.

PROGRAMIntroduces a program.

SyntaxPROGRAM <prog>...

The first statement in some ABAP programs. Equivalent of REPORT.

PROTECTEDDefines the protected section of a class.

SyntaxPROTECTED SECTION.

Introduces the declaration of all of the components of a class that are only visible in the class andits subclasses.

PROVIDELoops through internal tables at given intervals.

SyntaxPROVIDE <f1>... <fn> FROM <itab1>

<g1>... <gm> FROM <itab2>... FROM <itabn>... BETWEEN <f> AND <g>.

The contents of the specified fields of the internal tables <itab1> … <itabn> are placed in theirheader lines. Then, the processing block between PROVIDE and ENDPROVIDE is executed foreach interval.

PUBLICDefines the public section of a class.

SyntaxPUBLIC SECTION.

Introduces the declaration of all components of a class that are visible in the class, itssubclasses, and for all users.

Page 245: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1477

PUTTriggers a GET event.

SyntaxPUT <node>.

Only occurs in logical databases. Branches the program flow according to the structure of thelogical database.

R RAISE for ExceptionsTriggers an exception.

SyntaxRAISE <except>.

Only occurs in function modules and methods. Terminates the procedure and triggers theexception <except>.

RAISE for EventsTriggers an event in ABAP Objects.

SyntaxRAISE EVENT <evt>.

Only occurs in methods. The event <evt> is triggered, and this calls all of the handler methodsregistered for it.

RANGESDeclares a RANGES table.

SyntaxRANGES <rangetab> FOR <f>.

Declares a RANGES table for the field <f>. RANGES tables have the same data type as aselection table, but they do not have input fields on a selection screen.

READ for FilesReads a file.

SyntaxREAD DATASET <dsn> INTO <f> [LENGTH <len>].

Page 246: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1478 December 1999

Reads the contents of the file <dsn> on the application server to the variable <f>. The number ofbytes transferred can be written to <len>.

READ for any Internal TableReads a line from any internal table.

SyntaxREAD 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 thework area <wa>, the line with the key specified in the TABLE KEY addition, the line thatcorresponds 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 thefield symbol <FS>. If you assign the line to a work area, you can compare field contents andspecify the fields that you want to transport.

READ for Index TablesReads a line of an index table.

SyntaxREAD TABLE <itab> INDEX <idx> INTO <wa>... | ASSIGNING <FS>.

Reads the line with the index <idx>. The result is available as described above.

READ for ListsReads the contents of a line from a list.

SyntaxREAD 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 beenselected by the user. The addition specifies the fields that you want to read, and the target fieldsinto 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 ProgramsReads ABAP programs from the program library.

Page 247: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1479

SyntaxREAD REPORT <prog> INTO <itab>.

Copies the lines of the program <prog> into the internal table <itab>.

RECEIVEReceives results from an asynchronous function module call.

SyntaxRECEIVE RESULTS FROM FUNCTION <func> [KEEPING TASK]

[IMPORTING ... fi = ai... ][TABLES ... fi = ai... ][EXCEPTIONS... ei = ri... ]

Occurs in special subroutines to receive IMPORTING and TABLES parameters from functionmodules called using the STARTING NEW TASK addition.

REFRESHInitializes an internal table.

SyntaxREFRESH <itab>.

Resets the internal table <itab> to its initial value, that is, deletes all of its lines.

REFRESH CONTROLInitializes a control.

SyntaxREFRESH CONTROL <ctrl> FROM SCREEN <scr>.

The control <ctrl> defined in the CONTROLS statement is reset with the initial values specifiedfor screen <scr>.

REJECTTerminates a GET processing block.

SyntaxREJECT [<dbtab>].

Stops processing the current line of the node of the logical database. If you specify <dbtab>, thelogical database reads the next line of the node <dbtab>, otherwise the next line of the currentnode.

Page 248: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1480 December 1999

REPLACEReplaces strings in fields with another string.

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

REPORTIntroduces a program.

SyntaxREPORT <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 DEFININGDATABASE 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.

RESERVEConditional page break in a list.

SyntaxRESERVE <n> LINES.

Executes a page break on the current page if less than <n> lines are free between the currentline and the page footer.

ROLLBACKUndoes the changes in a SAP LUW.

SyntaxROLLBACK WORK.

Undoes all changes within a database LUW to the beginning of the LUW. The registered updatemodules are not executed, and the record entry is deleted from table VBLOG.

Page 249: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1481

S SCROLLScrolls in a list.

SyntaxSCROLL 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 canscroll by window, page, columns, or to the left- or right-hand edge of the list.

SEARCHSearches for a string.

SyntaxSEARCH <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 thesystem field SY-FDPOS. The additions allow you to hide intermediate characters, search fromand to a particular position, and convert the found string into uppercase.

SELECTReads data from the database.

SyntaxSELECT <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 clauseDefines the structure of the selection.

Page 250: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1482 December 1999

SyntaxSELECT [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 linesusing the DISTINCT addition. To select the entire line, use *, otherwise, you can specifyindividual columns <si>. For individual columns, you can use aggregate functions <agg>, andassign alternative column names <ai>.

INTO clauseDefines 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 youuse the CORRESPONDING FIELDS addition, data is only selected if there is an identically-named field in the target area. If you use APPENDING instead of INTO, the data is appended toan internal table instead of overwriting the existing contents. PACKAGE SIZE allows you tooverwrite or extend the internal table in a series of packages. The data type of the target areamust be appropriate for the selection in the SELECT clause.

FROM clauseSpecifies the database tables from which the data in the selection in the SELECT clause is to beread.

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 linktables with conditions <cond>, where <tab> is a single table or itself a join condition. You canspecify individual database tables either statically or dynamically, and you can replace theirnames with an alternative <alias>. You can bypass automatic client handling with the CLIENTSPECIFIED addition, and SAP buffering with BYPASSING BUFFER. You can also restrict thenumber of lines read from the table using the UP TO <n> ROWS addition.

WHERE clauseRestricts 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 foreach line of the internal table <itab> as long as <cond> contains a field of the internal table as an

Page 251: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1483

operand. For each line of the internal table, the lines from the database table meeting thecondition are selected. The result set is the union of the individual selections resulting from eachline.

GROUP BY clauseGroups lines in the selection

Syntax... GROUP BY <s1> <s2>

Groups lines with the same contents in the specified columns. Uses aggregate functions for allother columns in each group. All columns listed in the SELECT clause that do not appear in theGROUP BY addition must be specified in aggregate expressions.

HAVING clauseRestricts the number of line groups.

Syntax... HAVING <cond>

Like the WHERE clause, but can only be used in conjunction with a GROUP BY clause. Appliesconditions to aggregate expressions to reduce the number of groups selected.

ORDER BY clauseSorts 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 contentsof the fields listed.

SELECT-OPTIONSDeclares selection criteria for a selection screen.

SyntaxSELECT-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 thecorresponding selection screen. The additions allow you to set a default value, accept input inlowercase, define a required field, suppress or modify the display on the selection screen, restrict

Page 252: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1484 December 1999

the selection table to a line or a selection to a single field, or prevent input from being passed to alogical database.

SELECTION-SCREEN for Selection Screen FormattingFormats a selection screen.

SyntaxSELECTION-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 andblocks, and create pushbuttons.

SELECTION-SCREEN for Defining Selection ScreensDefines selection screens.

SyntaxSELECTION-SCREEN BEGIN OF <numb> [TITLE <tit>] [AS WINDOW]. ...SELECTION-SCREEN END OF <numb>.

Defines a selection screen with the screen number <numb>. All PARAMETERS, SELECT-OPTIONS, and SELECTION-SCREEN statements within the SELECTION-SCREEN BEGIN OF… END OF block belong to the selection screen <numb>. The TITLE addition allows you todefine a title for the selection screen. The AS WINDOW addition allows you to define theselection screen as a modal dialog box.

SELECTION-SCREEN for Selection Screen VersionsDefines selection screen versions.

Page 253: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1485

SyntaxSELECTION-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 standardselection screen.

SELECTION-SCREEN for Logical DatabasesProvides special functions in conjunction with logical databases.

SyntaxSELECTION-SCREEN DYNAMIC SELECTIONS | FIELD SELECTION FOR NODE|TABLE <node>.

Can only be used in logical databases. Declares a node as accepting dynamic selections or fieldselections.

SET BITSets an individual bit.

SyntaxSET 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> mustbe 0 or 1.

SET BLANK LINESAllows blank lines in lists.

SyntaxSET BLANK LINES ON|OFF.

Prevents blank lines created in WRITE statements from being suppressed in list output.

SET COUNTRYSets the output format

SyntaxSET COUNTRY <c>.

Sets the output formats for numeric and date fields for the country with the ID <c>.

Page 254: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1486 December 1999

SET CURSORSets the cursor on the screen.

SyntaxSET 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 CHECKAffects the extended program check.

SyntaxSET EXTENDED CHECK ON|OFF.

Switches the extended program check (SLIN) on or off, suppressing the correspondingmessages.

SET HANDLERRegisters event handlers in ABAP Objects.

SyntaxSET 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 additionto register handlers for instance events.

SET HOLD DATASets a screen attribute.

SyntaxSET HOLD DATA ON|OFF.

Sets the screen attribute “Hold data” from the program.

SET LANGUAGESets the display language.

SyntaxSET LANGUAGE <lg>.

All text symbols are refreshed with the contents of the text pool in language <lg>.

Page 255: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1487

SET LEFT SCROLL BOUNDARYSets the left-hand boundary for horizontal scrolling.

SyntaxSET LEFT SCROLL-BOUNDARY [COLUMN <col>].

Sets the current output position or the position <col> as the left-hand edge of the scrollable areaon the current list page.

SET LOCALE LANGUAGESets the text environment.

SyntaxSET 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 MARGINSets 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-handedge and <y> rows from the top edge of the page.

SET PARAMETERSets a SPA/GPA parameter.

SyntaxSET PARAMETER ID <pid> FIELD <f>.

Copies the value of the field <f> into the SPA/GPA parameter <pid> in the user-specific SAPmemory.

SET PF-STATUSSets the GUI status.

SyntaxSET PF-STATUS <stat> [EXCLUDING <f>|<itab>] [IMMEDIATELY] [OF PROGRAM <prog>].

Sets the GUI status <stat> for the subsequent screens. The EXCLUDING addition allows you todeactivate functions dynamically. The IMMEDIATELY addition sets the GUI status of the list

Page 256: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1488 December 1999

currently displayed. The OF PROGRAM addition allows you to use a GUI status from anotherprogram.

SET PROPERTYSets a property of an OLE2 Automation object.

SyntaxGET PROPERTY OF <obj> <p> = <f>.

Sets the property <p> of an external OLE2 Automation object to <f>.

SET RUN TIME ANALYZERControls the runtime analysis.

SyntaxSET RUN TIME ANALYZER ON|OFF.

The runtime analysis only measures the runtime of the statements in the block between SETRUN TIME ANALYZER ON and OFF.

SET RUN TIME CLOCKSets the clock accuracy for runtime analysis.

SyntaxSET RUN TIME CLOCK RESOLUTION HIGH|LOW.

Sets the accuracy of the runtime to low accuracy with long measurement interval or highaccuracy with shorter measurement interval.

SET SCREENSets the next screen.

SyntaxSET SCREEN <scr>.

Temporarily overwrites the statically-defined next screen with <scr>. <scr> is processed after thecurrent screen.

SET TITLEBARSets the screen title.

SyntaxSET TITLEBAR <t> [OF PROGRAM <prog>] [WITH <g1 >... <g9>].

Page 257: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1489

Sets the title <t> for the subsequent screens. The OF PROGRAM addition allows you to use atitle from another program. The WITH addition fills any placeholders in the title.

SET UPDATE TASK LOCALSwitches on local update.

SyntaxSET UPDATE TASK LOCAL.

Updates are processed in the current work process.

SET USER-COMMANDTriggers a list event.

SyntaxSET USER-COMMAND <fc>.

Triggers a list event with the function code <fc> and calls the corresponding event block.

SHIFTShifts strings.

SyntaxSHIFT <c> [BY <n> PLACES] [LEFT|RIGHT|CIRCULAR].

Shifts the field <c> by one or <n> places. The additions allow you to specify the direction, andhow the empty spaces are dealt with.

SKIP for Blank LinesCreates blank lines on the output list.

SyntaxSKIP [<n>].

Creates <n> blank lines after the current line in a list. If you omit <n>, inserts one line.

SKIP for PositioningAbsolute positioning for output on a list.

SyntaxSKIP TO LINE <lin>.

Positions the list output in line <lin>.

Page 258: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1490 December 1999

SORT for ExtractsSorts an extract dataset.

SyntaxSORT [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, theextract is sorted by the key specified in the HEADER field group. The BY addition allows you tospecify a different sort key. The other additions specify whether you want to sort in ascending ordescending order, and whether strings should be sorted alphabetically.

SORT for Internal TablesSorts internal tables.

SyntaxSORT <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 BYaddition allows you to specify a different sort key. The remaining additions allow you to specifywhether you want to sort in ascending or descending order, and whether strings should be sortedalphabetically.

SPLITSplits a character string.

SyntaxSPLIT <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-SELECTIONEvent keyword that defines an event block for a reporting event.

SyntaxSTART-OF-SELECTION.

After the selection screen has been processed, the runtime environment triggers the START-OF-SELECTION event and processes the corresponding event block.

Page 259: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1491

STATICSDefines static variables.

SyntaxSTATICS <f>...

Like DATA. Retains the value of a local variable beyond the runtime of the procedure in which itoccurs.

STOPExits a reporting event.

SyntaxSTOP.

Can only occur in event blocks for reporting events. Leaves the block and jumps to END-OF-SELECTION.

SUBMITCalls an executable program.

SyntaxSUBMIT <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 isterminated, otherwise, the data from the current program is retained, and processing returns tothe calling program when <rep> has finished running. The other additions control the selectionscreen and set attributes of the default list in the called program.

SUBTRACT for Single FieldsSubtracts two single fields.

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

Page 260: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1492 December 1999

SUBTRACT-CORRESPONDINGSubtracts components of structures.

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

SUMCalculates sums of groups.

SyntaxSUM.

Can only be used in loops through internal tables. Calculates the sums of the numeric fields in alllines of the current control level and writes the results to the corresponding fields in the workarea.

SUPPLYFills context instances with values.

SyntaxSUPPLY <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 DIALOGPrevents the current screen from being displayed.

SyntaxSUPPRESS DIALOG.

Can only occur in a PBO dialog module. The screen is not displayed, but its flow logic is stillprocessed.

T TABLESDeclares an interface work area.

SyntaxTABLES <dbtab>.

Page 261: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1493

Declares a structure with the same data type and name as a database table, a view, or astructure from the ABAP Dictionary. Structures declared using TABLES in main programs andsubroutines use a common data area.

TOP-OF-PAGEEvent keyword for defining an event block for a list event.

SyntaxTOP-OF-PAGE [DURING LINE-SELECTION].

Whenever a new page begins while a standard list is being created, the runtime environmenttriggers the TOP-OF-PAGE event and the corresponding event block is executed. The additionDURING LINE-SELECTION has the same function, but for detail lists.

TRANSFERWrites data to a file.

SyntaxTRANSFER <f> TO [LENGTH <len>].

Writes the field <f> to the file <dsn> on the application server. The LENGTH addition specifiesthe length <len> of the data you want to transfer.

TRANSLATEConverts characters in strings.

SyntaxTRANSLATE <c> TO UPPER|LOWER CASE |USING <r>.

The characters of the string <c> are converted into upper- or lowercase, or according to asubstitution rule specified in <r>.

TYPE-POOLIntroduces a type group.

SyntaxTYPE-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 anABAP program containing type definitions and constant declarations that can then be used inseveral different programs.

Page 262: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1494 December 1999

TYPE-POOLSDeclares the types and constants of a type group to a program.

SyntaxTYPE-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 TypesDefines a simple field type.

SyntaxTYPES <t>[(<length>)] [TYPE <type>|LIKE <obj>] [DECIMALS <dec>].

Defines the internal data type <t> in the program with length <len>, reference to the ABAPDictionary type <type> or a data object <obj>, and, where appropriate, with <dec> decimalplaces.

SyntaxTYPES <t> TYPE REF TO <class>|<interface>.

Defines the internal data type <t> in the program with reference to the class <class> or theinterface <interface>.

TYPES for Aggregate TypesDefines aggregated types.

SyntaxTYPES: BEGIN OF <structure>, ... <ti>..., ... END OF <structure>.

Combines the data types <ti> to form the structure <structure>. You can address the individualcomponents of a structure in a program using a hyphen between the structure name and thecomponent name as follows: <structure>-<ti>.

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

Page 263: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1495

U ULINEPlaces a horizontal line on the output list.

SyntaxULINE [AT [/][<pos>][(<len>)]].

Without additions, generates a new line on the current list and fills it with a horizontal line. Theadditions allow you to insert a line break and specify the starting position and length of the line.

UNPACKConverts variables from type P to type C.

SyntaxUNPACK <f> TO <g>.

Unpacks the packed field <f> and places it in the string <g> with leading zeros. The opposite ofPACK.

UPDATEModifies lines in database tables.

SyntaxUPDATE <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. TheWHERE addition determines the lines that are updated. If you omit the WHERE addition, all linesare updated.

SyntaxUPDATE <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 withthe same primary key as a line in the internal table <itab> with the corresponding line of itab. Thework area <wa> or the lines of the table <itab> must have at least the same length and the samealignment as the line structure of the database table.

W WHENIntroduces a statement block in a CASE control structure.

Page 264: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Statement Overview

1496 December 1999

SyntaxWHEN <f1> [OR <f2> OR...] | OTHERS.

The statement block after a WHEN statement is executed if the contents of the field <f> in theCASE statement are the same as those of one of the fields<f i>. Processing then resumes after the ENDCASE statement. The WHEN OTHERS statementblock is executed if the contents of <f> do not correspond to any of the fields <fi>.

WHILEIntroduces a loop.

SyntaxWHILE <logexp> [VARY <f> FROM <f1> NEXT <f2>].

Introduces a statement block that is concluded with ENDWHILE. The statement block betweenWHILE and ENDWHILE is repeated for as long as the expression <logexp> is true, or until atermination statement such as CHECK or EXIT occurs. The VARY addition allows you to processfields that are a uniform distance apart within memory.

WINDOWDisplays a list as a modal dialog box.

SyntaxWINDOW 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 bottomright-hand corner is positioned at column <x2> and line <y2> (if specified).

WRITECreates list output.

SyntaxWRITE [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 thelength 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 QUICKINFOaddition allows you to assign a quickinfo <g> to the field.

WRITE TOAssigns strings.

Page 265: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Statement Overview

December 1999 1497

SyntaxWRITE <f1> TO <f2> [<format>].

Converts the contents of the data object <f1> to type C and assigns the resulting string to thevariable <f2>. You can use the same formatting options available in the WRITE statement.

Page 266: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP System Fields

1498 December 1999

ABAP System FieldsThe ABAP system fields are active in all ABAP programs. They are filled by the runtimeenvironment, and you can query their values in a program to find out particular states of thesystem. Although they are variables, you should not assign your own values to them, since thismay overwrite information that is important for the normal running of the program. However, thereare some isolated cases in which you may need to overwrite a system variable. For example, byassigning 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 structureSYST. To address them in an ABAP program, use the form SY-<fieldname>. Within screen flowlogic, you can also use the form SYST-<fieldname>.

System Fields in Alphabetical Order

System Fields in Thematic Order

System Fields in Alphabetical OrderThe following table contains an alphabetical list of the fields in the ABAP Dictionary structureSYST.

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 ABAPprogram, but you must not change it.

The system field is set by the runtime environment. You can both use and change itsvalue 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 theruntime 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 inABAP programs.

“Name” stands for the component name. “Type” and “Length” are the ABAP Dictionary type andlength 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 J K L M N O P Q R S T U V W X Y Z

Name Type Length Use DescriptionABCDE CHAR 26 Constants Alphabet (A,B,C,...)

Page 267: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1499

APPLI RAW 2 Obsolete

BATCH CHAR 1 Backgroundprocessing

Is program running in the background?

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 Is program running in the background?

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 externalprocedure

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

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 10 Database access Number of database rows processed

DBNAM CHAR 20 ABAP program Logical database linked to the program

Page 268: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1500 December 1999

DBSYS CHAR 10 R/3 System Name of the central database 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 10 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 10 Loops Current loop pass

INPUT CHAR 1 Internal

LANGU LANG 1 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 10 Processing lists Index of the chosen list

LOCDB CHAR 1 Obsolete

LOCOP CHAR 1 Obsolete

LOOPC INT4 10 Screens Number of lines visible in the table

Page 269: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1501

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 MARGINstatement

MANDT CLNT 3 R/3 System Current client

MARKY CHAR 1 Obsolete

MAROW INT4 10 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 Current page

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

Page 270: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1502 December 1999

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 Output immediately

PRINI NUMC 1 Internal

PRLOG CHAR 1 Internal

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 Current main 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 10 Screens Number of columns

SFNAM CHAR 30 Obsolete

SFOFF INT4 10 Internal

SLSET CHAR 14 Selection screens Variant name

SPONO NUMC 10 Printing lists Spool number

SPONR NUMC 10 Obsolete

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

Page 271: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1503

SUBCS CHAR 1 Internal

SUBRC INT4 10 Return code Return code following an ABAPstatement

SUBTY RAW 1 Internal

SYSID CHAR 8 R/3 System Name of the R/3 System

TABID CHAR 8 Internal

TABIX INT4 10 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 Initial memory requirement

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

Page 272: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1504 December 1999

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 6 Date and time Current application server time

VLINE CHAR 1 Constants Vertical line

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 Flag for standard page header

XCODE CHAR 70 Internal

XFORM CHAR 30 Internal

XPROG CHAR 40 Internal

ZONLO CHAR 6 Date and time User’s time zone

System Fields in Thematic OrderThe 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

Page 273: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1505

• 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 InformationInformation About the Current R/3 SystemSY-DBSYSCentral database system (such as INFORMIX or ORACLE)

SY-HOSTApplication server (such as HS0333, PAWDF087 …)

SY-OPSYSOperating system of the application server (such as HP-UX, SINIX)

SY-SAPRLR/3 Release in use (such as 30D, 46A, …)

SY-SYSIDR/3 System name (such as B20, I47, ...)

Page 274: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1506 December 1999

Information About the Current Terminal SessionSY-LANGUOne-character language key with the user’s logon language (such as D, E, F…)

SY-MANDTClient 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 theWHERE clause.

SY-MODNOIndex of the external sessions. The first session has the index zero. The value is increased byone 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 thecount further. Sessions started using CALL TRANSACTION … STARTING NEW TASK beginagain at 0.

SY-UNAMEUsername of the current user, such as KELLERH, BC400-01…

Information About Current Date and TimeThe following system fields are always set automatically. The GET TIME statement synchronizesthe time on the application server with the time on the database server and writes it to the fieldSY-UZEIT. SY-DATUM and the system fields for the local timezone (SY-TIMLO, SY-DATLO, andSY-ZONLO) are also reset.

SY-DATLOUser’s local date, for example 19981129, 19990628, …

SY-DATUMCurrent application server date, for example 19981130, 19990627, …

SY-DAYSTX during summertime, otherwise space.

SY-FDAYWFactory calendar day of the week: Monday = 1 … Friday = 5.

SY-TIMLOUser’s local time, for example 154353, 225312, …

SY-TZONETime difference in seconds between local time and Greenwich Mean Time (UTC), for example,360, 10800.

SY-UZEITCurrent application server time. for example 164353, 215312, …

Page 275: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1507

SY-ZONLOUser’s time zone, for example, EST, UTC, …

Information About the Current ABAP ProgramSY-CALLDX if the program was started using CALL TRANSACTION, CALL DIALOG, or SUBMIT … [ANDRETURN]. Space if the program was started using LEAVE TO TRANSACTION or using atransaction code from a screen. SY-CALLD is always space when a batch input session is beingprocessed.

SY-CPROGThe name of the calling program in an external routine, otherwise the name of the currentprogram.

SY-DBNAMThe name of the logical database linked to an executable program.

SY-DYNGRScreen group to which the current screen belongs. You can assign several screens to onescreen group, for example, to allow you to modify them all identically.

SY-DYNNRNumber of the current screen. During selection screen processing, SY-DYNNR contains thescreen number of the current selection screen. During list processing, it contains the number ofthe container screen. During subscreen processing, SY-DYNNR contains the number of thesubscreen. This also applies to tabstrip controls.

SY-LDBPGIn executable programs, the database program of the associated logical database.

SY-REPIDName of the current ABAP program. For externally-called procedures, it is the name of the mainprogram of the procedure. If you pass SY-REPID as an actual parameter to an externalprocedure, the formal parameter does not contain the name of the caller, but that of the mainprogram of the procedure. To avoid this, assign SY-REPID to an auxiliary variable and use that inthe call, or use the system field SY-CPROG.

SY-TCODEThe current transaction code.

Background ProcessingSY-BATCHX if the ABAP program is running in the background, otherwise space

Page 276: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1508 December 1999

Batch InputSY-BINPTX while a batch input session is running and when an ABAP program is called using CALLTRANSACTION USING, otherwise space.

• OPTIONS FROM in the CALL TRANSACTION USING statement can set SY-BINPT to spaceeither 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 ProgrammingConstantsSY-ABCDEContains the alphabet. You can use this field with offset to retrieve a letter of the alphabetregardless of codepage.

SY-ULINEContains a horizontal line with length 255 that you can use when creating lists.

SY-VLINEContains a vertical line (|) that you can use when creating lists.

LoopsSY-INDEXIn a DO or WHILE loop, SY-INDEX contains the number of loop passes including the currentpass.

StringsSY-FDPOSLocation of hit in string operations.

• When you use CO,CN, CA, NA, CS, NS, CP, and NP, offset values are assigned to SY-FDPOS depending on the search result.

• SEARCH … FOR … sets SY-FDPOS to the offset of the search string.

Internal TablesSY-TABIXCurrent line of an internal table. SY-TABIX is set by the statements below, but only for indextables. 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 theoverall number of entries in the table.

Page 277: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1509

• COLLECT sets SY-TABIX to the index of the existing or inserted line in the table. If the tablehas 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 isset 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 onemore than the total number of lines. SY-INDEX is undefined if a linear search fails to returnan entry.

• SEARCH <itab> FOR sets SY-TABIX to the index of the table line in which the search stringis found.

SY-TFILLAfter the statements DESCRIBE TABLE, LOOP AT, and READ TABLE, SY-TFILL contains thenumber of lines in the relevant internal table.

SY-TLENGAfter the statements DESCRIBE TABLE, LOOP AT, and READ TABLE, SY-TLENG contains thelength of the lines in the relevant internal table.

SY-TOCCUAfter the statements DESCRIBE TABLE, LOOP AT, and READ TABLE, SY-TLENG contains theinitial amount of memory allocated to the relevant internal table.

Database AccessSY-DBCNTSQL statements set SY-DBCNT to the number of table entries processed. In an Open SQLSELECT loop, SY-DBCNT is not set until after the ENDSELECT statement. In Native SQL, SY-DBCNT 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 CodeSY-SUBRCReturn code, set by the following ABAP statements. As a rule, if SY-SUBRC = 0, the statementwas 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 authorizationfailure.

Page 278: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1510 December 1999

• CALL DIALOG with USING sets SY-SUBRC to 0 if the processing is successful, otherwise toa 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, and4 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 asystem 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 avalue 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 handledin 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 valueother 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 SY-SUBRC 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 8depending on the cause of the error.

• LOOP sets SY-SUBRC to 0 if there is at least one pass through the extract. Otherwise, it isset to a value other than 0.

Page 279: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1511

• 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 avalue 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 beexecuted 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 valueother 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 4or 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, dependingon the context and cause of the error.

• REPLACE sets SY-SUBRC to 0 if the search string was replaced, otherwise to a value otherthan 0.

• SCROLL sets SY-SUBRC to 0 if the scrolling within the list was successful, otherwise to 4 or8, 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 inSELECT 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.

Page 280: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1512 December 1999

ScreensScreensA 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-CUCOLHorizontal cursor position. Counter begins at column 2.

SY-CUROWVertical cursor position. Counter begins at line 1.

SY-DATARX if at least one input field on the screen was changed by the user or other data transport,otherwise space.

SY-LOOPCNumber of lines currently displayed in a table control.

SY-PFKEYGUI status of the current screen. This can be set in the PBO event using the SET PF-STATUSstatement.

SY-SCOLSNumber of columns on the current screen.

SY-SROWSNumber of rows on the current screen.

SY-STEPLIndex of the current line in a table control. This is set in each loop pass. SY-STEPL does nothave a meaningful value outside the loop (for example, during the POV event for a table line).

SY-TITLEText that appears in the title bar of the screen. This is the program name for selection screensand lists, and SAP R/3 otherwise. Can be set using the SET TITLEBAR statement.

SY-UCOMMFunction code that triggered the PAI event. There is a unique function code assigned to everyfunction that triggers the PAI event with one exception: ENTER triggers the PAI, and variousfunction 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 theENTER key, this function code is passed to SY-UCOMM.

Page 281: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1513

• If there is no entry in the command field and there is no function key assigned to the ENTERkey, the content of SY-UCOMM remains unchanged.

Selection ScreensSY-SLSETVariant used to fill the selection screen.

Creating ListsWhen you create a list, you can use the following system fields to control navigation. They helpyou to ensure that output statements do not overwrite existing output, or that data is not writtenoutside the list. The system fields SY-COLNO and SY-LINNO always contain the current outputposition, and they are reset by each output statement. The other system fields contain othervalues used for creating lists.

SY-COLNOCurrent column during list creation. The counter begins at 1. The field is set by the followingoutput 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, anysubsequent output statements are ignored.

• NEW-LINE sets SY-COLNO to 1.

• NEW-PAGE sets SY-COLNO to 1.

SY-LINCTPage length of the list. For a default list of indefinite length, SY-LINCT is 0. If the page length isdefined, SY-LINCT has that value.

• LINE-COUNT in the REPORT, PROGRAM, or FUNCTION POOL statement sets SY-LINCTfor the current program.

• LINE-COUNT in the SUBMIT statement sets SY-LINCT for the program called in thestatement.

SY-LINNOCurrent line during list creation. The counter begins at 1, and includes the page header. SY-LINNO 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 withRESERVE, 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 thepage, the statement is ignored.

Page 282: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1514 December 1999

SY-LINSZLine width in the list. The default value is the default window width. SY-LINSZ = SY-SCOLS, forSY-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 NEW-PAGE statement.

• LINE-SIZE in the REPORT, PROGRAM, or FUNCTION POOL statement sets SY-LINSZ forthe current program.

• LINE-SIZE in the SUBMIT statement sets SY-LINSZ for the program called in the statement.

SY-PAGNOCurrent 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 boththe current page and the intended next page.

• NEW-SECTION in the statement NEW-PAGE PRINT ON sets SY-PAGNO to 1.

SY-TVAR0 ... SY-TVAR9You can assign values to these variables in your programs. Their contents replace theplaceholders in the list and column headers of the program in the TOP-OF-PAGE event.

SY-WTITLThe REPORT, PROGRAM, and FUNCTION-POOL statements set this variable to N if you usethe NO STANDARD PAGE HEADING addition. Otherwise, it has the value space. NEW-PAGEdoes not set SY-WTITL.

List ProcessingThe following system fields are filled at each interactive list event and at the READ LINEstatement:

SY-CPAGEPage number of the topmost page in the display of the list on which the event was triggered. Thecounter begins at 1.

SY-LILLILine at which the event was triggered. The counter begins at 1 and includes the page header.

SY-LISELContents of the line in which the event was triggered (restricted to the first 255 characters).

SY-LISTIIndex of the list in which the event was triggered.

SY-LSINDIndex of the list currently being created. The basic list has SY-LSIND = 0, detail lists have SY-LSIND > 0. The field is automatically increased by one in each interactive list event. You maychange the value of SY-LSIND yourself in the program to enable you to navigate between lists.

Page 283: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1515

Changes to SY-LSIND do not take effect until the end of a list event. It is therefore a good idea toplace the relevant statement at the end of the corresponding processing block.

SY-LSTATProgram-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-STACONumber of the first displayed column of the list from which the event was triggered. The counterbegins at 1.

SY-STARONumber of the topmost displayed line of the topmost displayed page of the list from which theevent was triggered. The counter begins at 1, not including the page header.

Printing ListsWhen you print lists, the spool and runtime systems require certain internal information that is setin the following system fields when you start printing.

SY-CALLRContains a value indicating where printing was started, for example, NEW-PAGE for program-controlled printing, or RSDBRUNT for printing from a selection screen.

SY-PRDSNContains the name of the spool file during printing.

SY-SPONOContains the spool number during printing.

SY-MAROW, SY-MACOLThe SET MARGIN statement fills the system fields SY-MAROW and SY-MACOL. Thesedetermine the number of lines in the top margin and the number of columns in the left-handmargin respectively.

Print ParametersThe print parameters are passed to the spool system by the runtime environment, using astructure with the ABAP Dictionary type PRI_PARAMS. Before this structure existed, systemfields were used instead. When you start printing, some of the fields from PRI_PARAMS are stillwritten into system fields with the same names. However, you should not use these system fieldsyourself.

MessagesWhen 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 thecalling program if it is to handle the exception.

Page 284: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1516 December 1999

SY-MSGIDSY-MSGID contains the message class

SY-MSGNOSY-MSGNO contains the message number

SY-MSGTYSY-MSGTY contains the message type

SY-MSGV1,…,SY-MSGV4SY-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_LOCKexception 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 messagethat occurs during the screen chain is returned in the fields SY-MSGID, SY-MSGTY, SY-MSGNO, and SY-MSGV1 ... SY-MSGV4.

• In Remote Function Call (RFC), error messages are retrieved from the remote system andplaced 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 typeX occurs.

Internal System FieldsInternal system fields are exclusively for internal use in the ABAP runtime environment and thesystem kernel. They must not be overwritten in any circumstances, and should also not be readin ABAP programs.

SY-CFWAEUndocumented

SY-CHWAEUndocumented

SY-DEBUGUndocumented

SY-DSNAMFile name for spool output

SY-ENTRYUndocumented

Page 285: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1517

SY-FFILEFlat file (USING/GENERATING DATASET).

SY-FLENGLength of a field

SY-FODECNumber of decimal places in a field

SY-FOLENOutput length of a field

SY-FTYPEData type of a field

SY-GROUPBundling

SY-INPUTUndocumented

SY-LPASSUndocumented

SY-NEWPAUndocumented

SY-NRPAGUndocumented

SY-ONCOMUndocumented

SY-PAUTHUndocumented

SY-PLAYOUndocumented

SY-PLAYPUndocumented

SY-PNWPAUndocumented

SY-PRI40Undocumented

Page 286: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1518 December 1999

SY-PRINIUndocumented

SY-PRLOGUndocumented

SY-REPI2Undocumented

SY-RSTRTUndocumented

SY-SFOFFUndocumented

SY-SUBCSCall status of an executable program

SY-SUBTYCall type of an executable program

SY-TABIDUndocumented

SY-TLOPCUndocumented

SY-TSTISUndocumented

SY-XCODEExtended function code, filled by user actions on a list (like SY-UCOMM). Before the length ofSY-UCOMM was extended from 4 to 70 characters, SY-XCODE was used internally toaccommodate long entries in the command field. You should always use SY-UCOMM inapplication programs.

SY-XFORMSYSTEM-EXIT subroutine.

SY-XPROGSYSTEM-EXIT program.

Page 287: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1519

Obsolete System FieldsSome of the system fields in the R/3 System were originally adopted from R/2, but are no longerfilled with values. They are obsolete, and must not (indeed cannot) be used.

SY-APPLIR/2 - ID for the SAP applications installed. Not filled in R/3.

SY-BATZDR/2 - flag for daily background scheduling. Not filled in R/3.

SY-BATZMR/2 - flag for monthly background scheduling. Not filled in R/3.

SY-BATZOR/2 - flag for one-time background scheduling. Not filled in R/3.

SY-BATZSR/2 - flag for immediate background scheduling. Not filled in R/3.

SY-BATZWR/2 - flag for weekly background scheduling. Not filled in R/3.

SY-BREP4R/2 - root name of the report requesting background processing. Not filled in R/3.

SY-BSPLDR/2 - flag for spool output from background processing. Not filled in R/3.

SY-CCURSR/2 - exchange rate and result field for CURRENCY CONVERSION. Not filled in R/3.

SY-CCURTR/2 - table exchange rate for CURRENCY CONVERSION. Not filled in R/3.

SY-CDATER/2 - exchange rate date for CURRENCY CONVERSION. Not filled in R/3.

SY-CTABLR/2 - exchange rate table for CURRENCY CONVERSION. Not filled in R/3.

SY-CTYPER/2 - exchange rate type for CURRENCY CONVERSION. Not filled in R/3.

SY-DCSYSDialog system of the R/2 System. Not filled in R/3.

Page 288: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

System Fields in Alphabetical Order

1520 December 1999

SY-FMKEYFormerly the current function code menu. Not filled in R/3.

SY-LOCDBLocal database. Not implemented.

SY-LOCOPLocal database operation. Not implemented.

SY-MACDBFormerly the file name for matchcode access. Not filled in R/3.

SY-MARKYCurrent line letter for the MARK statement. The MARK statement will not be supported for muchlonger.

SY-TMAXLFormerly the maximum number of entries in an internal table. Not filled in R/3.

SY-TFDSNFormerly the name of an external storage file for extracts. Not filled in R/3.

SY-PAGCTR/2 - the maximum number of pages per list. Not filled in R/3.

SY-PREFXABAP prefix for background jobs. Not filled in R/3.

SY-SFNAMUndocumented

SY-SPONRIn R/2, you could process spool files with the TRANSFER statement, which also set SY-SPONR.Not filled in R/3.

SY-TNAMEFormerly the name of an internal table following access. Not filled in R/3.

SY-TTABCFormerly the index of the last line of an internal table to be read. Not filled in R/3.

SY-TTABIFormerly the offset of internal tables in the roll area. Not filled in R/3.

SY-TPAGIFormerly flagged whether an internal table had been moved to the paging area. Not filled in R/3.

Page 289: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

System Fields in Alphabetical Order

December 1999 1521

SY-WAERSFormerly the company code currency after reading a posting segment. Not filled in R/3.

SY-WILLIR/2 - the number of the list line selected from a detail list. Use SY-LILLI instead.

SY-WINCOR/2 - cursor position on a detail list. Use SY-CUCOL instead.

SY-WINDIR/2 - index of the list for a detail list. Use SY-LSIND instead.

SY-WINROR/2 - cursor position for a detail list. Use SY-CUROW instead.

SY-WINSLR/2 - contents of the selected line for detail list in a window. Use SY-LISEL instead.

SY-WINX1R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

SY-WINX2R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

SY-WINY1R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

SY-WINY2R/2 - window coordinates for a detail list in a window. No corresponding field in R/3.

Page 290: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1522 December 1999

ABAP Glossary

A

ABAPAdvanced Business Application Language. The SAP programming language for applicationprogramming.

ABAP DictionaryCentral information repository for application and system data. The ABAPDictionary contains data definitions (metadata) that allow you to describe allof the data structures in the system (like tables, views, and data types) inone place. This eliminates redundancy.

ABAP EditorTool in the ABAP Workbench in which you enter the source code of ABAP programs and checktheir syntax. You can also navigate from the ABAP Editor to the other tools in the ABAPWorkbench.

ABAP MemoryABAP Memory is a memory area in the internal session (roll area) of an ABAP program. Datawithin this area is retained within a sequence of program calls, allowing you to pass databetween programs that call one another. It is also possible to pass data between sessionsusing SAP Memory.

ABAP ObjectsThe ABAP runtime environment or the object-oriented extension of ABAP. ABAP Objects usesclasses to create objects.

ABAP ProcessorThe ABAP processor executes the processing logic of the application program, andcommunicates with the database interface.

ABAP Query Allows you to create simple reports without having to know any ABAP.

ABAP WorkbenchThe ABAP Workbench is a fully-fledged development environment for applications in the ABAPlanguage. With it, you can create, edit, test, and organize application developments. It contains arange of tools including the Screen Painter, ABAP Editor, and Repository Browser.

Page 291: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1523

Aggregated Data TypesData types built up of a series of single field types. An aggregated data type can be astructure or an internal table. With aggregated types, you can either access the whole object orindividual fields.

Application LogicGeneric term for the parts of application programs that process application-relevant data.

Actual ParameterWhen you pass parameters to a procedure, the actual parameters are the parameters that youpass from the program. They are passed to the formal parameters within the routine.

Application ServerThe level within the client/server architecture in which application logic runs.

AttributeA component of a class in ABAP Objects. Attributes contain the data of a class. They are usedby the methods of classes.

BBackground ProcessingProgram processing without user dialogs.

Bottom-UpDevelopment method that starts with the lowest components in a hierarchy and becomes moregeneralized 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 ofother business software suites.

CCastingA reference assignment in ABAP Objects. It is checked for correctness at runtime, not in thesyntax check.

ClassTemplate for objects in ABAP Objects. You can define classes either locally in an ABAPprogram, or globally using the Class Builder in the ABAP Workbench. You can either define anew class from first principles, or derive one using inheritance. Classes can implementinterfaces.

Page 292: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1524 December 1999

Class BuilderABAP Workbench tool used to create classes and interfaces.

Class ReferenceData type of a reference variable or object reference that allows you to access all of the visiblecomponents of an class.

ClientA unit within an R/3 System that is complete in a legal and organizational sense, and which hasits own user masters and own tables.

Client HandlingUsers working in a particular client are only allowed to use certain transactions, as specified inthe 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 ArchitectureAn architecture in which data and applications are distributed over different hosts in order tomake the most efficient use of each host’s resources.

ClusterAn object-oriented collection of tables.

CommentExplanatory notes in the source code of a program that make it easier to understand. This makessubsequent maintenance and support easier. You can make a whole line into a comment byplacing a * at the beginning of the line. Alternatively, if you place a " anywhere in a line, the restof that line becomes a comment.

Company CodeA legally-independent unit within a client that has its own fiscal year end.

ConstantA data object declared statically with a declarative statement. They allow you to store data undera particular name within the memory area of a program. The value of a constant must be definedwhen you declare it. It cannot subsequently be changed.

ContainerA file containing several programming units that all have the same type. For example, you canhave a container for subroutines.

ContextsA technique for avoiding repeated database access or calculations with data in a program. Youcreate 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 orcalculated using the key field values.

Page 293: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1525

Control LevelsA series of lines in an internal table or extract dataset that forms a group based on the contentsof one or more of its fields.

Control Level ProcessingUsed in an internal table or extract dataset to form groups of entries.

DData Control Language (DCL)Statements for authorization and consistency checks. Not used in the R/3 System, since thesystem is itself responsible for checking data.

Data Definition Language (DDL)Language for defining the attributes of a database management system and creating andadministering database tables. It is not contained in Open SQL.

Data DictionarySee ABAP Dictionary.

Data Manipulation Language (DML)Statements for reading and changing data in database tables.

DatabaseSet of data that is part of a database system and is managed by the database managementsystem.

Database CommitA 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 allexecuted (commit) or all canceled (rollback).

Database RollbackA ROLLBACK WORK in a relational database system.

Database CursorA mechanism for passing data from the database to an ABAP program. An open cursor is linkedto a multiple-line selection in the database table for which it was opened. You can place the linesof the selection one by one into a flat target object and process them.

Page 294: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1526 December 1999

Database InterfaceThe part of a work process that links it to the database. It converts Open SQL into StandardSQL, and allows the application server to communicate with the database.

Database ServerHost on which the database is installed.

Database TableMost databases that are used for business applications are based on the relational databasemodel, in which the real world is represented by tables.

Data ElementDescribes 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 ObjectName for an instance of a data type in ABAP. A data object occupies a field in memory.

Data TypeDescribes the technical attributes of a data object. ABAP uses the data type of a field tointerpret its contents. There are single field types, aggregated types, and object types.

Declaration PartPart of every program or procedure. It contains data, selection screen, and class definitionsthat are visible throughout the program or procedure.

Deep StructureA structure that contains an internal table as a component.

Deep TablesAn internal table whose line type is a deep structure.

Dialog ModuleStatement block that describes the different states (PBO, PAI, user input) of a screen. A modulepool contains a set of dialog modules.

Dialog ProgramA program that contains (or consists entirely of) dialog modules.

DispatcherLink between work processes and users. It receives user interaction from the SAPgui, and directsit to a free work process.

Page 295: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1527

DomainSpecifies the technical attributes of a data element - its data type, length, possible values, andappearance on the screen. Each data element has an underlying domain. A single domain canbe the basis for several data elements. Domains are objects in the ABAP Dictionary.

Double Byte Character SetTwo byte code system for extensive character sets such as Japanese or Chinese.

EElementary TypesThere 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 packednumber (P). You can use these types as the basis for further types that you create either locallyin a program or globally in the ABAP Dictionary.

EncapsulationProperty of objects in object-oriented programming. Each object has an external interface. Theimplementation of the object is encapsulated, that is, invisible externally.

Event BlockA series of statements that are processed when a particular event occurs when a program runsor in selection screen and list processing. Each event block begins with an event keyword, andends at the introductory keyword of the next event block.

ExtractSequential dataset in the memory area of a program. An extract dataset consists of a sequenceof 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.

FFieldArea in memory with address and length. Data objects in ABAP occupy fields. The contents of afield are interpreted according to the data type of the relevant data object.

Field SymbolPlaceholder or symbolic name for a field. Field symbols do not occupy any space, but insteadpoint to a data object.

Flat StructureStructure consisting only of elementary data types.

Page 296: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1528 December 1999

Flow LogicSee Screen Flow Logic.

Foreign KeyOne or more fields in a table that occur as key fields in another table.

Formal ParameterPlaceholder for passing values to a procedure. Formal parameters declare the number andtypes of the actual parameters that will be passed to the procedure.

Forward NavigationForward navigation allows you to access an object by double-clicking its name in the source codeof an ABAP program or in an object list.

Function BuilderABAP Workbench tool used to create, display, modify, and delete function modules andfunction groups.

Function GroupProgram with type F that contains function modules. Created using the Function Builder.

Function LibraryLibrary of existing function modules in the ABAP Workbench.

Function ModuleProcedure that can only be created within a type F program, but which can be called from anyABAP program within the R/3 System. You create them using the Function Builder in theABAP Workbench. A function module has a defined parameter interface.

GGatewayThis is the interface for the R/3 communication protocols (RFC, CPI/C). It can communicate withother application servers in the same R/3 System, with other R/3 Systems, with R/2 Systems,or with non-SAP systems.

Generic AttributesAttributes that are not fully typed. The missing attributes are specified dynamically at runtime.

Global DataData that is visible throughout a program (and also in procedures that it calls).

Page 297: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1529

GUI StatusEach screen has a GUI status. The status is a collection of interactive interface elements thatallows the user to select functions. A GUI Status is an independent development object within anABAP program. You create and edit them using the Menu Painter in the ABAP Workbench.

GUI TitleTitle of a screen that appears in the title bar of the window. A GUI title is an independentdevelopment object within an ABAP program. You create and edit them using the Menu Painterin the ABAP Workbench.

HHashed TableAn internal table whose entries you can access by specifying the key. The system manages thetable using a hash algorithm. The advantage of this is that the search overhead does notincrease with the size of the table.

Header LineWork area for table access. You can place the successive lines of an internal table into theheader line and process them.

IInclude ProgramA technique for modularizing the source code. Program with type I. Allows you to reuse codein different programs. The source code of an include program is fully incorporated into the sourcecode of the program in which the include statement occurs.

Index TableAn internal table for which the system maintains a linear index. You can use the index to accessentries in the table. There are two kinds of index tables: Standard tables and sorted tables.

InheritanceA special way of defining a class. You can use an existing class to derive a new class. Derivedclasses (subclasses) inherit the attributes and methods of the original class (superclass).They may also have new methods, or redefine existing ones.

InterfacePart of a class definition in ABAP Objects. You can define interfaces either locally in an ABAPprogram, or globally using the Class Builder in the ABAP Workbench. Classes canimplement interfaces. They then adopt all of the components of the interface. The class mustimplement all of the methods of the interface itself.

Page 298: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1530 December 1999

Interface ReferenceData type of a reference variable or object reference that allows you to access all of the visiblecomponents of an interface.

Interface Work Area A special data object that you use to pass data between screens or logical databases andABAP programs.

Internal TablesData object consisting of a set of lines with the same data type. There are different access typesfor internal tables: Sorted and unsorted index tables, and hashed tables, and also different linetypes: Vectors, “real” tables, with flat structures, and deep tables. You should use internaltables whenever you need to use structured data within a program.

JJoinA technique for linking two or more tables. The tables involved must have at least one commoncolumn.

KKernelRuntime environment for all R/3 applications. It is independent of hardware, operating system,and database. Has the following functions: Running applications, administration of users andprocesses, database access, communication with other applications, control and administrationof the R/3 System.

Key Selected fields of a table used to identify table records. A key may be either unique or non-unique.

LListLists 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 includeinput fields in a list.

Page 299: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1531

LiteralData object, without a name, that you create in the source code of a program. It is fully defined byits value. You cannot change the value of a literal.

Local DataData that is only visible in the current program (including its subroutines) or procedure.

Logical Database BuilderTool in the ABAP Workbench for creating and editing logical databases.

Logical DatabaseAn ABAP program that retrieves data from various database tables. The dataset covered by alogical database program is sometimes referred to itself as the logical database. The lines of therelevant tables are passed one by one to the program that is using the logical database. You canuse a logical database with any number of executable programs.

MMacroA technique for modularizing the source code. The DEFINE statement introduces a set ofstatements 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 PainterA tool in the ABAP Workbench that allows you to create menus and assign functions to functionkeys and pushbuttons.

MetadataData that describes other data. Data definitions are metadata. They are stored in the ABAPDictionary.

MethodA procedure that is a component of a class in ABAP Objects. Methods represent the functionsof a class. They work with the attributes. Methods can only be defined in the implementationparts of classes.

ModularizationSplitting a program into various parts (modules). There are two kinds of modules - those that areincluded in the source code of the program when it is generated (macros (local) or includeprograms (global)), and those that are called as independent modules at runtime. These areknown as procedures. Modularization makes large programs easier to understand and maintain,and reduces the amount of redundancy.

Module PoolType M program containing the dialog modules of the screens in the program.

Page 300: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1532 December 1999

NNative SQLAn access method that uses database-specific statements. Native SQL statements are notinterpreted, and are passed to the database without any checks. You should not use Native SQLstatements, since they are database-specific (your program will no longer be portable), andABAP does not check to ensure that the statements are correct.

Nested StructureA structure that itself contains a structure as a component.

OObjectA piece of code containing data (attributes) and providing services (methods). Objects areinstances of classes in ABAP Objects.

Object ReferenceObject references are used to access the attributes and methods of an object in ABAP Objects.Object references are contained in reference variables.

Object TypesObject types are used to describe objects. They contain both data and functions. Classes andinterfaces are both object types. They are part of ABAP Objects.

Open SQLA set of statements that allows you to access the database from an ABAP program. Open SQLstatements are fully portable to any of the database platforms supported by SAP. Open SQL is asubset of Standard SQL (without the DDL part), but also contains SAP-specific extensions.

PParameter1. A data object in a program whose value can either be entered by the user at runtime or bepassed from another program.2. A value passed when you call a procedure or program from another program. See also actualparameter and formal parameter.

Page 301: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1533

Parameter InterfaceA method by which programs and the procedures that they call can exchange data. When youwrite subroutines or procedures, you define formal parameters, which define the type,number, and order of the actual parameters that should be passed.

PolymorphismAn attribute of objects in object-oriented programming. Identically-named methods behavedifferently in different classes.

Presentation ServerThe host that receives input from the user and presents output from the system.

ProcedureA modularization technique. Unlike source code modules (macros, includeprograms), procedures have interfaces for data transfer. ABAP contains thefollowing 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 haschosen a function on the screen.

Process Before Output (PBO)The part of the screen flow logic that determines the processing steps that occur before ascreen is displayed.

Processing BlockAny ABAP statement that does not belong to the declaration part, that is, the event blocks,dialog modules, and procedures.

Processing LogicProcessing logic implements the business functions of the R/3 System. It is contained in ABAPprograms.

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 onlybe programmed within a function group. You create them using the Function Builderin the ABAP Workbench.

- Type K: Class definitions, containers for global classes in ABAP Objects. You createthem using the Class Builder in the ABAP Workbench.

Page 302: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1534 December 1999

- Type J: Interface definitions, containers for global interfaces in ABAP Objects. Youcreate 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 asprograms, screens, and function modules.

RABAX A program in the ABAP runtime environment that catches runtime errors and triggers a shortdump.

Reference See object reference.

Reference Variable Data object that contains an object reference. The data type of a reference variables can be aclass reference or an interface reference.

Remote Function Call (RFC) An interface protocol based on CPI-C that allows programs in different systems to communicatewith one another. External applications and tools can use ABAP functions, and the R/3 Systemcan 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 adevelopment 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.

Page 303: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1535

Runtime ErrorError that occurs while a program is running, often because the error could not be determinedstatically by the syntax check.

Runtime EnvironmentUmbrella 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 runapplications and enter and display data.

SAP LUW A logical unit consisting of dialog steps, whose changes are written to the database in a singledatabase LUW.

SAP Memory This is a memory area to which all sessions within a SAPgui have access. You can use SAPmemory either to pass data from one program to another within a session (as with ABAPmemory) or to pass data from one session to another.

SAP Transaction A dialog-driven program, or any program started using a transaction code.

ScreenA screen (also referred to sometimes as a dynamic program or “dynpro”) consists of the screenitself and the flow logic, which controls how the screen is processed. You create both the screenand its flow logic in the Screen Painter.

Screen Flow LogicThe screen flow logic consists of PBO and PAI, and controls most user interaction. The R/3Basis 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 ProcessorThe screen processor executes the screen flow logic. It takes control of communication betweenthe work process and the SAPgui, calls processing logic modules, and passes the contents ofthe screen fields back to the program for processing.

Screen TableTable on a screen, created using the step loop or table control technique.

Page 304: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1536 December 1999

Screen TypeThere 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 arenot 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 inthe Repository Browser or the Logical Database Builder in the ABAP Workbench.

SessionThe R/3 window in the SAPgui represents a session. After logging on, the user can open up tofive further sessions (R/3 windows) within the single SAPgui. These behave almost likeindependent SAPguis.

Shared Memory The memory area shared by all work processes.

Short DumpThe text that accompanies a runtime error. This should enable you to find and correct the error.

Single Field TypeA data type in ABAP whose data objects occupy a single field. Elementary types andreferences 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 theRepository Browser in the ABAP Workbench.

SQL Report An executable program that does not use a logical database. Instead, it defines its ownselection 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 TableAn unsorted index table.

Page 305: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1537

StatementA line of an ABAP program. ABAP contains the following kinds of statements: declarativestatements, control statements, call statements, operational statements, database statements,and modularization statements.

StructureA structure is a logically-connected set of fields. It is a data object containing a sequence of anydata 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.

SubclassThe resulting class when you use inheritance to derive a class from a superclass.

SubqueryA special Open SQL selection statement that you can use under certain conditions to form anextra query.

SubroutineA procedure that you define in a program using the FORM statement, and which you can callany number of times from any ABAP program using the PERFORM statement. When you call thesubroutine, you can pass parameters to it. Subroutines are normally used locally, that is, calledin the same program in which they are defined.

SuperclassThe class from which a subclass is derived in inheritance.

TText PoolA set of texts belonging to a program. You address them using text symbols in the sourcecode. The text pool can be translated into other languages.

Text SymbolA data object that is generated when you start a program from the text pool of the program.

Top-DownA development method that starts with the highest level of a hierarchy and becomes morespecialized as the development project goes on. The opposite of bottom-up.

TransactionA set of work steps that belong together. In the context of database changes, the term stands fora change of state in the database. It is also used as an abbreviation of SAP transaction.

Page 306: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1538 December 1999

Transaction CodeA sequence of letters and digits that starts an SAP transaction when you enter it in thecommand 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 RepositoryBrowser. They are linked to an ABAP program and an initial screen.

Transparent TableYou 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 notused, since they cannot be read using Open SQL.

U

VVariableA named data object that you can declare statically using declarative statements, or dynamicallywhile a program is running. They allow you to store changeable data under a particular namewithin the memory area of a program.

VectorAn internal table whose line type is an elementary type.

ViewA virtual table that does not contain any data, but instead provides an application-oriented view ofone or more ABAP Dictionary tables.

WWork Process (Dialog)Consists of a screen processor, ABAP processor, and database interface. Part of anapplication server, it executes the dialog steps of application programs.

Page 307: Sap bc abap programming 1999  05 05

SAP AG BC - ABAP Programming

ABAP Glossary

December 1999 1539

X

Y

Z

Page 308: Sap bc abap programming 1999  05 05

BC - ABAP Programming SAP AG

ABAP Glossary

1540 December 1999

Syntax ConventionsThe conventions for syntax statements in this documentation are as follows:

Key DefinitionSTATEMENT 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: fieldsymbols).

[] Square brackets indicate that you can use none, one, or more of the enclosedoptions. Do not include the brackets in your option.

| A bar between two options indicates that you can use either one or the other ofthe 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 candisregard case when you type keywords in your program. WRITE is the same as Write is thesame as write.

Output on the output screen is either shown as a screen shot or in the following format:

Screen output.