Calling Programs and Passing Data Lesson Twenty Five



There are two ways of starting an ABAP program from another ABAP program that is already running:

By interrupting the current program to run the new one - the called program is executed, and afterwards, processing returns to the program that called it.By terminating the current program and then running the new one.Complete ABAP programs within a single user session can only run sequentially. We refer to this technique as using synchronous calls.

If you want to run functions in parallel, you must use function modules.The way in which main memory is organized from the program's point of view can be represented easily in the above model. There is a distinction between internal and external sessions:

Generally, an external session corresponds to an R/3 window. You create new external sessions by choosing System Create session or entering /o in the command field. You can have up to six external sessions open simultaneously in one terminal session.External sessions are subdivided into internal sessions . Each program that you run occupies its own internal session. Each external session can contain up to nine internal sessions.

The data in a program is only visible within that internal session, so it is only visible to the program.The following pages illustrate how the stack inside an external session changes with various program calls.When you insert a program, the system creates a new internal session, which contains the new program context.The new session is placed on the stack The program context of the calling program also remains on the stack.

When the called program finishes, its internal session (the top one in the stack) is deleted.Processing is resumed in the next-highest internal session in the stack.When you end a program and start a new one, there is a difference between calling an executable program and calling a transaction.If you start an executable program using its program name, the internal session of the program you are ending (the top one) is removed.

The system creates a new internal session, which contains the program context of the called program. The new session is placed on the stack. Any program contexts that already existed are retained. The topmost internal session on the stack is replaced.If you start a program using its transaction code (if one is assigned), all of the existing internal sessions are removed from the stack.The system creates a new internal session, which contains the program context of the called program.

After the call, the ABAP memory is reset.When you call a function module, the ABAP runtime system checks whether you have already called a function module from the same function group in the current program.If this is not the case, the system loads the relevant function group into the internal session of the calling program. Its global data is initialized and the LOAD-OF-PROGRAM event is triggered.

If your program had already used a function module from the same function group before the call, the function group is already resident in the internal session, and the new call can access the same global data. We say that the function group remains active until the end of the program that called it.

The data is only visible in the corresponding program - each program can only address its own data, even if there are identically-named objects in both programs. The same applies when the stack is extended. If a program is added to the stack that calls a function module from a function group already called by another program, the function group is loaded again into the new internal session.The system creates new copies of its data objects, initializes them, and, as before, they are only visible within the function group, and only in the internal session in which the function group was loaded.

To start an executable (type 1) program, use the SUBMIT statement.If you use the VIA SELECTION-SCREEN addition, the system displays the standard selection screen of the program (if one has been defined).

If you use the AND RETURN addition, the system resumes processing with the first statement after the SUBMIT statement once the called program has finished.For further information, refer to the documentation for the SUBMIT statement.When you use the LEAVE TO TRANSACTION '' statement, the system terminates the current program and starts the transaction with transaction code . The statement is the equivalent of entering /n in the command field.

CALL TRANSACTION '' allows you to insert an ABAP program with a transaction code into the call chain.To terminate an ABAP program, use the LEAVE PROGRAM statement. If the statement occurs in a program that you called using CALL TRANSACTION '' or SUBMIT AND RETURN, the system resumes processing at the next statement after the call in the calling program. In all other cases, the user returns to the application menu from which he or she started the program.

If you use the …AND SKIP FIRST SCREEN addition, the system does not display the screen contents of the first screen in the transaction. However, it does process the flow logic.If you started a transaction using CALL TRANSACTION that uses update techniques, you can use the UPDATE… addition to specify the update technique (asynchronous (default), synchronous, or local) that the program should use.

There are various ways of passing data to programs running in separate internal sessions:

You can use

The interface of the called program (usually a standard selection screen)
ABAP memory
SAP memory
Database tables
Local files on your presentation server

Function modules have an interface that the calling program and the function module use to exchange data. Subroutines also use a similar technique. Certain restrictions apply to the interfaces of remote enabled function modules.When you call ABAP programs that have a standard selection screen, you can pass data for the input fields in the call. There are two ways to do this:

By specifying a variant for the selection screen when you call the program.By specifying values for the input fields when you call the program.The WITH addition in the SUBMIT statement allows you to assign values to the fields on a standard selection screen. The abbreviations "EQ, NE, … , I, E" have the same meanings as with select options.

If you want to pass several selections to a selection option, you can use the RANGES statement instead of individual WITH additions. The RANGES statement creates a selection table , which you can fill as though it were a selection option. You then pass the whole table to the executable program.If you want to display the standard selection screen when you call the program, use the VIA SELECTION-SCREEN addition.When you use the SUBMIT statement, use the Pattern function in the ABAP Editor to insert an appropriate statement pattern for the program you want to call. It automatically suppplies the names of the parameters and selection options that are available on the standard selection screen.

The example shown above is an extract from transaction BC402_CALD_CONN. When the user requests the coordinates of a city, the executable program SAPBC402_TABD_HASHED is called.The parameters are filled with the city and country code from the transaction. The standard selection screen does not appear.For further information about working with variants and about other syntax variants of the WITH addition, refer to the documentation for the SUBMIT statement.To pass data between programs, you can use either the SAP memory or the ABAP memory.

SAP memory is a user-specific memory area that you can use to store field values. It is only of limited value for passing data between internal sessions. Values in SAP memory are retained for the duration of the user's terminal session. The memory can be used between sessions in the same terminal session. You can use the contents of SAP memory as default values for screen fields. All external sessions can use the SAP memory.

ABAP memory is also user-specific. There is a local ABAP memory for each external session. You can use it to exchange any ABAP variables (fields, structures, internal tables, complex objects) between the internal sessions in any one external session.When the user exits an external session (/i in the command field), the corresponding ABAP memory is automatically initialized or released.

Use the EXPORT … TO MEMORY statement to copy any number of ABAP variables with their current values (data cluster) to ABAP memory. The ID… addition (maximum 32 characters long) enables you to identify different clusters.If you use a new EXPORT TO MEMORY statement for an existing data cluster, the new one will overwrite the old.The IMPORT… FROM MEMORY ID… statement allows you to copy data from ABAP memory into the corresponding fields of your ABAP program. In the IMPORT statement, you can also restrict the selection to a part of the data cluster.The variables into which you want to read data from the cluster in ABAP memory must have the same types in both the exporting and the importing programs.To release a data cluster, use the FREE MEMORY ID… statement.Remember when you call programs using transaction codes that you can only use the ABAP memory to pass data to the transaction.

You can define memory areas (parameters) in the SAP memory in various ways:

By creating input/output fields with reference to the ABAP Dictionary. These take the parameter name of the data element to which they refer.Alternatively, you can enter a name in the attributes of the input/output fields. Then, you can also choose whether the entries from the field should be transferred to the parameter (SET), or whether the input field should be filled with the value from the parameter (GET).To find out about the names of the parameters assigned to input fields, display the field help for the field (F1), then choose Technical info.

You can also fill a memory area directly using the statement
SET PARAMETER ID '' FIELD .



RELATED POSTS


Legacy Data Transfer


Legacy Data Transfer

Function Modules and Groups of ABAP Lesson Twenty Four

Function modules of ABAP are more comfortable to use than subroutines, and have a wider range of uses. The following list, without claiming to be complete, details the essential role that function modules play in the ABAP Workbench:

Function modules ...

Are actively integrated in the ABAP Workbench. You create and manage them using the Function Builder.Can have optional importing and changing parameters, to which you can assign default values.Can trigger exceptions through which the return code field sy-subrc is filled.Can be remote-enabled.Can be executed asynchronously, allowing you to run parallel processes.Can be enabled for updates.Play an important role in the SAP enhancement concept.

In the Attributes of a function module, you specify its general administration data and the processing type :

Remote-enabled function modules can be called asynchronously in the same system, and can also be called from other systems (not just R/3 Systems). To call a function module in another system, there must be a valid system connection.Update function modules contain additional functions for bundling database changes. For further information, refer to the course BC414 (Programming Database Updates) and the online documentation.When you exchange data with function modules, you can distinguish clearly between three kinds of parameters:

Importing parameters, which are received by the function module
Exporting parameters, which are returned by the function module
Changing parameters, which are both received and returned.

By default, all parameters are passed by reference. To avoid unwanted side effects, you can only change exporting and changing parameters in the function module. If you want to pass parameters by value , you must select the relevant option when you define the interface.

You can also declare importing and changing parameters as optional. You do not have to pass values to these parameters when you call the function module. Where possible, you should use this option when you add new parameters to function modules that are already in use. You can assign a default value to an optional parameter. If you do not pass a value of your own when you call the function module, the system then uses the default value instead. Export parameters are always optional.

You may specify the type of an elementary parameter. You must specify the type of a structured or table parameter. You can use either ABAP Dictionary types, ABAP Dictionary objects, predefined ABAP types (I, F, P, N, C, STRING, X, XSTRING, D, T) or user-defined types. Any type conflicts show up in the extended program check.Tables parameters are obsolete for normal function modules, but have been retained to ensure compatibility for function modules with other execution modes.

When you save the interface, the system generates the statement framework together with the comment block that lists the interface parameters:

FUNCTION .
*"--------------
*" ...
*"--------------
...
ENDFUNCTION.


The comment block is updated automatically if you make changes to the function module later on. It means that you can always see the interface definition when you are coding the function module.

You program the statements exactly as you would in any other ABAP program in the ABAP Editor.In the function module, you can create your own local types and data objects, and call subroutines or other function modules.You can make a function module trigger exceptions .To do this, you must first declare the exceptions in the interface definition, that is, assign each one a different name.

In the source code of your function module, you program the statements that trigger an exception under the required condition. At run time, the function module is terminated when an exception is triggered.The changes to exporting and changing parameters are the same as in subroutines. There are two statements that you can use to trigger an exception. In the forms given below, stands for the name of an exception that you declared in the interface. The system reacts differently according to whether or not the exception was listed in the function module call:

RAISE .

If the exception is listed in the calling program, the system returns control to it directly. If the exception is not listed, a run time error occurs.

MESSAGE () RAISING .

If the exception is listed in the calling program, the statement has the same effect as RAISE . If it is not listed, the system sends message from message class with type , and no run time error occurs.Function modules differ from subroutines in that you must assume that they will be used by other programmers. For this reason, you should ensure that you complete the steps listed here.

Documentation (can be translated)

You should document both your parameters and exceptions with short texts (and long texts if necessary) and your entire function module. The system provides a text editor for you to do this, containing predefined sections for Functionality, Example Call, Hints, and Further Information.

Work list

When you change an active function module, it acquires the status active (revised). When you save it, another version is created with the status inactive . When you are working on a function module, you can switch between the inactive version and the last version that you activated. When you activate the inactive version, the previous active version is overwritten.

Function test

Once you have activated your function module, you can test it using the built-in test environment in the Function Builder. If an exception is triggered, the test environment displays it, along with any message that you may have specified for it. You can also switch into the Debugger and the Runtime Analysis tool. You can save test data and compare sets of results.

When you insert a function module call in your program, you should use the Pattern function. Then, you only need to enter the name of the function module (input help is available). The system then inserts the call and the exception handling (MESSAGE statement) into your program.

You assign parameters by name. The formal parameters are always on the left-hand side of the expressions:

Exporting parameters are passed by the program. If a parameter is optional, you do not need to pass it. Default values are displayed if they exist.

Importing parameters are received by the program. All importing parameters are optional.

Changing parameters are both passed and received. You do not have to list optional parameters.

Default values are displayed if they exist.The system assigns a value to each exception, beginning at one, and continuing to number them sequentially in the order they are declared in the function module definition. You can assign a value to all other exceptions that you have not specifically listed using the special exception OTHERS.

If you list the exceptions and one is triggered in the function module, the corresponding value is placed in the return code field sy-subrc. If you did not list the exception in the function call, a runtime error or a message occurs, depending on the statement you used in the function module to trigger the exception.When you create a function module, you must assign it to a function group. The function group is the main program in which a function module is embedded.A function group is a program with type F, and is not executable . The entire function group is loaded in a program the first time that you call a function module that belongs to it.

The system also triggers the LOAD-OF-PROGRAM event for the function group.The function group remains active in the background until the end of the calling program. It is therefore a suitable means of retaining data objects for the entire duration of a program. All of the function modules in a group can access the group's global data.

The same applies to screens. If you want to call one screen from several different programs, you must create it in a function group. You then create the ABAP data objects with the same names as the screen fields in the function group. The screen and data transport can now be controlled using the function modules in the group.


The implementation of the individual function modules is similar to the examples in the Internal Table Operations unit. To save space, we have only listed the ABAP coding that is relevant for the actual functions.The types of the parameters and global data objects have been specified by referring to appropriate types in the ABAP Dictionary.

Screen 100 belongs to the function group. It is a container screen for list processing that is processed invisibly. It allows the user to display the current contents of the waiting list in a modal dialog box.Forward navigation ensures that you always enter the correct object. Include programs are named automatically, and the relevant call statements are inserted automatically in the correct positions.

RELATED POSTS

LESSON 25 CALLING PROGRAM AND PASSING DATA IN ABAP

Closing ProcessAssets and Liabilities 
Profit and LossClosing Process

Sub Routines in ABAP Lesson Twenty Three

A subroutine in ABAP is an internal modularization unit within a program, to which you can pass data using an interface. You use subroutines to encapsulate parts of your program, either to make the program easier to understand, or because a particular section of coding is used at several points in the program. Your program thus becomes more function-oriented, with its task split into different constituent functions, and a different subroutine responsible for each one.As a rule, subroutines also make your programs easier to maintain. For example, you can execute them "invisibly" in the Debugger, and only see the result. Consequently, if you know that there are no mistakes in the subroutine itself, you can identify the source of the error faster.

Structure of a Subroutine

A subroutine begins with the FORM statement and ends with ENDFORM.

After the subroutine name, you program the interface. In the FORM statement, you specify the formal parameters , and assign them types if required. The parameters must occur in a fixed sequence - first the importing parameters, then the importing/exporting parameters. Within the subroutine, you address the data that you passed to it using the formal parameters.

You can declare local data in a subroutine.After any local data declarations, you program the statements that are executed as part of the subroutine.You define the way in which the data from the main program (actual parameters do1, do2, do3, and do4) are passed to the data objects in the subroutine (formal parameters p1, p2, p3, p4) in the interface . There are three possibilities:

Call by reference (p1, p3)

The dereferenced address of the actual parameter is passed to the subroutine.The USING and CHANGING additions both have the same effect (in technical terms). However, USING leads to a warning in the program check.

Call by value (p2)

A local "read only" copy of the actual parameter is passed to the subroutine. Do this using the form USING value().

Call by value and result (p4)

A local changeable copy of the actual parameter is passed to the subroutine. Do this using the form CHANGING value().

You should use this method when you want to be sure that the value of the actual parameter is not changed if the subroutine terminates early.When you use internal tables as parameters, you should use call by reference to ensure that the system does not have to copy what could be a large internal table.The data objects that you pass to a subroutine can have any data type . In terms of specifying data types, there are various rules:

You may specify the type for elementary types.If you do, the syntax check returns an error message if you try to pass an actual parameter with a different type to the formal parameter. Not specifying a type is the equivalent of writing TYPE ANY.In this case, the formal parameter "inherits" its type from the actual parameter at run time. If the statements in the subroutine are not compatible with this inherited data type, a run time error occurs.

Data types I, F, D, and T are already fully-specified. If, on the other hand, you use P, N, C, or X, the missing attributes are made up from the actual parameter. If you want to specify the type fully, you must define a type yourself (although a user-defined type may itself be generic). When you use STRING or XSTRING, the full specification is not made until run time.

You must specify the type of structures and references.You must specify the type of an internal table, but you can use a generic type, that is, program the subroutine so that the statements are valid for different types of internal table, and then specify the type:

. Using the corresponding interface specification:

TYPE [ANY|INDEX|STANDARD|SORTED|HASHED] TABLE,
(TYPE TABLE is the short form of TYPE STANDARD TABLE)

• Using a user-defined generic table type.
When you call a subroutine, the parameters are passed in the sequence in which they are listed.

The type of the parameters and the way in which they are passed is determined in the interface definition. When you call the subroutine, you must list the actual parameters after USING and CHANGING in the same way. There must be the same number of parameters in the call as in the interface definition.

The best thing to do is to define the subroutine and then use the Pattern function in the ABAP Editor to generate the call. This ensures that you cannot make mistakes with the interface. The only thing you have to do is replace the formal parameters with the appropriate actual parameters.

If you pass an internal table with a header line, the name is interpreted as the header line . To pass the body of an internal table with header line, use the form []. In the subroutine, the internal table will not have a header line.Formal parameters and local data objects that you define in a subroutine are only visible while the subroutine is active. This means that the relevant memory space is not allocated until the subroutine is called, and is released at the end of the routine. The data can only be addressed during this time.

The general rules are as follows:

You can address global data objects from within the subroutine. However, you should avoid this wherever possible, since in doing so you bypass the interface, and errors can creep into your coding.You can only address formal parameters and local data objects from within the subroutine itself.

If you have a formal parameter or local data object with the same name as a global data object, we say that the global object is locally obscured by the local object. This means that if you address an object with the shared name in the subroutine , the system will use the local object, if you use the same name outside the subroutine , the system will use the global object.

Summary

Address global data objects in the main program and, if you want to use them in the ubroutine, pass them using the interface.In the subroutine, address only formal parameters and local data objects.Avoid assigning identical names to global and local objects. For example, use a prefix such as p_ for a parameter and l_ for local data.This example calls the subroutine demosub. It contains a local data object with a starting value, and alters the four formal parameters.

The system allocates two memory areas p2 and p4 for the two call by value parameters d2 and d4, and fills them with the respective values. It also allocates memory for the local data object l_do, and fills it with the starting value.There is no VALUE addition for p1 or p3, This means that changes at runtime affect the actual parameters directly, and you can address do1 directly via p1.Here, the change to p1 directly affects the contents of do1.

The formal parameter p2 is declared as a local copy with read access. This means that any changes will not affect the actual parameter do2 at all.The same applies to p3 as to p1. If you do not use the VALUE addition, USING and CHANGING have the same effect.

The contents of do3 are affected directly by the changes to p3.As for p2, we have created a local copy for p4. Consequently, the changes to the formal parameter do not affect the actual parameter while the subroutine is running.The changes are not written back to the actual parameters until the ENDFORM statement.If demosub is interrupted for any reason, do4 would have the same value afterwards as it had before the call.

Now that demosub has finished running, the memory occupied by its local data objects is released. You now cannot address these data objects any more.Note that do still has its old value, even though p2 was changed in the subroutine.

It is technically possible to call subroutines from other main programs. However, this technique is obsolete, and you should use function modules instead. Function modules provide considerable advantages, and are important components in the ABAP Workbench. For further information, refer to the unit Function Groups and Function Modules. Another typical use of subroutines is recursive calls. Although all other modularization units can, in principle, be called recursively, the runtime required is often excessive for small easily-programmed recursions.

RELATED POSTS

LESSON 24 FUNCTION MODULES IN ABAP
Check Deposit Customization

Internal Tables in ABAP Lesson Twenty Two

INTERNAL TABLES IN ABAP:

There are two ways of accessing the records in an internal table,By copying individual records into a work area. The work area must be compatible with the line type of the internal table.You can access the work area in any way, as long as the component you are trying to access is not itself an internal table. If one of the components is an internal table, you must use a further work area, whose line type is compatible with that of the nested table.When you change the internal table, the contents of the work area are either written back to the table or added as a new record.

By assigning the individual data records to an appropriate field symbol. Once the system has read an entry, you can address its components directly via its address. There is no copying to and from the work area. This method is particularly appropriate for accessing large or complex tables.If you want to read more than one record, you must use a LOOP... ENDLOOP structure. You can then change or delete the line that has just been read, and the system applies the change to the table body. You can also change or delete lines using a logical condition.When you use the above statements with sorted tables, you must ensure that the sort sequence is maintained.

Within a loop, the INSERT statement adds the data record before the current record in the table. If you want to insert a set of lines from an internal table into another index table, you should use the INSERT LINES OF variant instead.When you read single data records, you can use two further additions:

In the COMPARING addition, the system compares the field contents of a data record with those in the work area for equality.In the TRANSPORTING addition, you can restrict the data transport to selected fields.Other statements for standard tables

SORT [ASCENDING|DESCENDING]
[BY [ASCENDING|DESCENDING] ..
[ASCENDING|DESCENDING]][AS TEXT] [STABLE].

These statements sort the table by the table key or the specified field sequence. If you do not use an addition, the system sorts ascending. If you use the AS TEXT addition, character fields are sorted in culture-specific sequence. The relative order of the data records with identical sort keys only remain constant if you use the STABLE addition.

APPEND INTO SORTED BY .

This statement appends the work area to the ranked list in descending order. The ranked list may not be longer than the specified INITIAL SIZE, and the work area must satisfy the sort order of the table.The statements listed here can be used freely with both standard and sorted tables.When you change a single line, you can specify the fields that you want to change using the TRANSPORTING addition. Within a loop, MODIFY changes the current data record.

If you want to delete a set of lines from an index table, use the variant DELETE FROM... TO.. or WHERE... instead of a loop. You can program almost any logical expression after WHERE.The only restriction is that the first field in each comparison must be a component of the line structure (see the corresponding Open SQL statements). You can pass component names dynamically.

If you want to delete the entire internal table , use the statement CLEAR .In the LOOP AT... ENDLOOP structure, the statements within the loop are applied to each data record in turn. The INTO addition copies entries one at a time into the work area.The system places the index of the current loop pass in the system field sy-tabix. When the loop has finished, sy-tabix has the same value that it had before the loop started.Inserting and deleting lines within a loop affects the following loop passes.Access to a hashed table is imple mented using a hash algorithm. Simplified, this means that the data records are distributed randomly but evenly over a particular memory area.. The addresses are stored in a special table called the hashing table .

There is a hash function, which determines the address at which the pointer to a data record with a certain key can be found. The function is not injective, that is, there can be several data records stored at a single address. This is implemented internally as a chained list. Therefore, although the system still has to search sequentially within these areas, it only has to read a few data records (usually no more than three). The graphic illustrates the simplest case, that is, in which there is only one data record stored at each address.

Using a hash technique means that the access time no longer depends on the total number of entries in the table. On the contrary, it is always very fast. Hash tables are therefore particularly useful for large tables with which you use predominantly read access.Data records are not inserted into the table in a sorted order. As with standard tables, you can sort hashed tables using the SORT statement:

SORT [ASCENDING|DESCENDING]
[BY [ASCENDING|DESCENDING] ..
[ASCENDING|DESCENDING]][AS TEXT].

Sorting the table can be useful if you later want to use a loop to access the table.You can use the statements listed here with tables of all three types. Apart from a few special cases, you can recognize the statements from the extra keyword TABLE. The technical implementation of the statements varies slightly according to the table type.

As a rule, index access to an internal table is quickest. However, it sometimes makes more sense to access data using key values. A unique key is only possible with sorted and hashed tables. If you use the syntax displayed here, your program coding is independent of the table type (generic type specification, easier maintenance).With a standard table, inserting an entry has the same effect as appending. With sorted tables with a non-unique key, the entry is inserted before the first (if any) entry with the same key.

To read individual data records using the first variant, all fields of that are key fields of must be filled. and can be identical. If you use the WITH TABLE KEY addition in the second variant, you must also specify the key fully. Otherwise, the system searches according to the sequence of fields that you have specified, using a binary search where possible. You can force the system to use a binary search with a standard table using the BINARY SEARCH addition.In this case, you must sort the table by the corresponding fields first. The system returns the first entry that meets the selection criteria.Similarly to when you read entries, when you change and delete entries using the key and a work area, you must specify all of the key fields.

You can prevent fields from being transported into the work area during loop processing by using the TRANSPORTING NO FIELDS addition in the WHERE condition. (You can use this to count the number of a particular kind of entry.)

Other statements for all table types

DELETE ADJACENT DUPLICATES FROM
[COMPARING .. | A L L F I E L }|ALL FIELDS}].
The system deletes all adjacent entries with the same key field contents apart from the first entry. You can prevent the system from only comparing the key field using the COMPARING addition. If you sort the table by the required fields beforehand, you can be sure that only unique entries will remain in the table after the DELETE ADJACENT DUPLICATES statement.

Searches all lines of the table for the string . If the search is successful, the system sets the fields sy-tabix and sy-fdpos.

FREE .
Unlike CLEAR, which only deletes the contents of the table, FREE releases the memory occupied by it as well.

If you want to access your data using the index and do not need your table to be kept in sorted order or to have a unique key, that is, when the sequence of the entries is the most important thing, not sorting by key or having unique entries, you should use standard tables. (If you decide you need to sort the table or access it using the key or a binary search, you can always program these functions by hand.)This example is written to manage a waiting list.

Typical functions are:

Adding a single entry,

Deleting individual entries according to certain criteria,

Displaying and then deleting the first entry from the list,

Displaying someone's position in the list.

For simplicity, the example does not encapsulate the functions in procedures.
The first thing we do in the example is to declare line and table type, from which we can then declare a work area and our internal table. We also require an elementary field for passing explicit index values.

Adding new entries

The data record for a waiting customer is only added to the table if it does not already exist in it. If the table had a unique key, you would not have had to have programmed this check yourself.

Deleting single entries according to various criteria

The criterion is the key field. However, other criteria would be possible - for example, deleting data records older than a certain insertion date reg_date.

Displaying and deleting the first entry from the list
Once a customer comes to the top of the waiting list, you can delete his or her entry. If the waiting list is empty, such an action has no effect. Consequently, you do not have to check whether there are entries in the list before attempting the deletion.

Displaying the position of a customer in the waiting list
As above, you do not need to place any data in the work area. We are only interested in the values of sy-subrc and sy-tabix. If the entry is not in the table, sy-tabix is set to zero.

At this stage, let us return to the special case of the restricted ranked list:
DATA {TYPE|LIKE} STANDARD TABLE OF ... INITIAL SIZE . ... APPEND INTO SORTED BY .
When you choose to use a sorted table, it will normally be because you want to define a unique key.

The mere fact that the table is kept in sorted order is not that significant, since you can sort any kind of internal table. However, with sorted tables (unlike hashed tables), new data records are inserted in the correct sort order. If you have a table with few entries but lots of accesses that change the contents, a sorted table may be more efficient than a hashed table in terms of runtime.

The aim of the example here is to modify the contents of a database table. The most efficient way of doing this is to create a local copy of the table in the program, make the changes to the copy, and then write all of its data back to the database table. When you are dealing with large amounts of data, this method both saves runtime and reduces the load on the database server. Since the internal table represents a database table in this case, you should ensure that its records have unique keys.

This is assured by the key definition. Automatic sorting can also bring further advantages.When you change a group of data records, only the fields price and currency are copied from the work area.This means that, with larger tables, the access time is reduced significantly in comparison with a binary search. In a loop, however, the hashed table has to search the entire table (full table scan). Since the table entries are stored unsorted, it would be better to use a sorted table if you needed to run a loop through a left-justified portion of the key.

It can also be worth using a hashed table but sorting it. A typical use for hashed tables is to buffer detailed information that you need repeatedly and can identify using a unique key. You should bear in mind that you can also set up table buffering for a table in the ABAP Dictionary to cover exactly the same case. However, whether the tables are buffered on the application table depends on the size of the database table.Buffering in the program using hashed tables also allows you to restrict the dataset according to your own needs, or to buffer additional data as required.In this example, we want to allow the user to enter the name of a city, and the system to display its geographical coordinates.


First, we fill our "buffer table" city_list with values from the database table sgeocity. Then, we read an entry from the hashed table, specifying the full key.The details are displayed as a simple list. At this point, it is worth repeating that you should only use this buffering technique if you want to keep large amounts of data locally in the program. You must ensure that you design your hashed table so that it is possible to specify the full key when you access it from your program.

You can define internal tables either with (WITH HEADER LINE addition) or without header lines. An internal table with header line consists of a work area (header line) and the actual table body. You address both objects using the same name. The way in which the system interprets the name depends on the context. For example, the MOVE statement applies to the header line, but the SEARCH statement applies to the body of the table.

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

Within ABAP Objects, you can only use internal tables without a header line. You can always address the body of an internal table explicitly by using the following syntax: []. This syntax is always valid, whether the internal table has a header line or not.The COLLECT statement adds the work area or header line to an internal entry with the same type or, if there is none, adds a new entry to the table. It searches for the entry according to the table type and defined key. If it finds an entry in the table, it adds all numeric fields that are not part of the key to the existing values. If there is not already an entry in the table, it appends the contents of the work area or header line to the end of the table.

When you read a table line using READ or a series of table lines using LOOP AT, you can assign the lines of the internal table to a field symbol using the addition ... ASSIGNING <>. The field symbol <> then points to the line that you assigned, allowing you to access it directly. Consequently, the system does not have to copy the entry from the internal table to the work area and back again.The field symbol <> must have the same type as the line type of the internal table. However, there are also certain restrictions when you use this technique:

You can only change the contents of key fields if the table is a standard table .

You cannot use the SUM statement in control level processing. (The SUM statement adds all of the numeric fields in the work area.)This technique is particularly useful for accessing a lot of table lines or nested tables within a loop. Copying values to and from the work area in this kind of operation is particularly runtime-intensive. In this example, the user should be able to enter a departure city, for which all possible flights are then listed.To do this, we decla re an innner table (cofl_list) and an outer table( travel_list) with corresponding work areas.



In order to allow loop access using field symbols, the buffer table and the inner internal table must have the same type. Furthermore, we want to sort the table by various criteria later on. Consequently, we are using standard tables, not sorted tables.

It would have been possible to solve this problem using nested SELECT statements. However, this is not a realistic proposition because of the excessive load that we would then place on the database server.

Index access (APPEND, INSERT ... INDEX, LOOP ... FROM TO and so on) is possible for standard and sorted tables. A possible consequence of this is that you may cause a runtime error by violating the sort sequence if you use INSERT with an index or APPEND on a sorted table.

SORT can only apply to standard and hashed tables. It has no positive effect in a sorted table, and can lead to a syntax or runtime error if the attempted sort violates the key sequence.You can use key access for any table type, but the runtime required varies according to the table type.

The run time depends on whether the values are part of the key (so the sequence in which you pass them is also significant). INSERT for a standard table or hashed table using the key has the same effect as the APPEND statement.The system supports control level processing for all table types. Hashed and standard tables must be sorted beforehand.

RELATED POSTS

LESSON 23 SUB ROUTIENS IN ABAP

My SAP Project safety and security

ABAP Statements for SAP Lesson Twenty One


Use CLEAR to reset any variable data object to the initial value appropriate to its type .In a structure, each component is reset individually.In an internal table without a header line, all of the lines are deleted.Use MOVE to copy the contents of one data object to another variable data object.With complex objects, you can either address the components individually or use a "deep copy". If the source and target objects are compatible , the system copies the objects component by component or line by line.If they are not compatible, the system converts the objects as long as there is an appropriate conversion rule.

If you are copying between two structures, and only want to copy values between identically-named fields, you can use the MOVE-CORRESPONDING statement.The conversion mechanisms explained on the following pages apply not only to the MOVE and MOVE CORRESPONDING statements, but also to calculations and value comparisons.Unlike the MOVE statement, when you use WRITE... TO... to assign values, the target field is always regarded as a character field, irrespective of its actual type. WRITE...TO behaves in the same way as when you write output to a list. This allows you to use formatting options when you copy data objects (for example, country-specific date formatting).

If two data types are not compatible but there is a converion rule, the system converts the source object into the type of the target object when you assign values, perform calculations, or compare values.The following pages contain the basic forms of the conversion rules, and examples for the most frequent cases.

If there is no conversion rule defined for a particular assignment, the way in which the system reacts depends on the context in which you programmed the assignment.If the types of the objects involved are defined statically, a syntax error occurs.

Example:
DATA: date TYPE d VALUE '19991231', time TYPE t.
FIELD-SYMBOLS: TYPE d, TYPE t.
ASSIGN: date TO , time TO .
= .

If the types of the objects involved are defined dynamically, a runtime error occurs, because the system cannot tell in the syntax check whether they are convertible or not.Example (remainder as above):

FIELD-SYMBOLS: TYPE ANY, TYPE ANY.
In general, there is a rule for converting every predefined ABAP data type into any other predefined type.Special cases:

There are no rules for converting from type D to type T or vice versa, or for converting ABAP Objects data types (object reference to obje ct reference, object reference to interface reference). Assignments or comparisons of this type cause syntax errors (where it is possible for the system to detect them).

When you assign a type C field to a type P field, you may only use digits, spaces, a decimal point, and a plus or minus sign. The target field must also be large enough.When you convert a packed number to a type C field, the leading zeros are converted into spaces. For full information about conversion rules for elementary types, refer to the online documentation in the ABAP Editor for the MOVE statement.

Internal tables can only be converted into other internal tables. The system converts the lines types according to the relevant rule for structures.

The example above shows that copying between non-compatible types may result in the target fields containing values that cannot be interpreted properly. To avoid this problem, you should copy values field by field in these cases. This ensures that the system applies the correct conversion rule for elementary fields.

If you want to manipulate strings, it is better to use the statements expressly intended for this purpose. You can use the following statements to process strings in ABAP:


SEARCH To search in a string
REPLACE To replace the first occurrence of a string
TRANSLATE To replace all specified characters
SHIFT To shift a character at a time
CONDENSE To remove spaces
CONCATENATE To chain two or more strings together
OVERLAY To overlay two strings
SPLIT To split a string

In all string operations, the operands are treated like type C fields, regardless of their actual field type. They are not converted.All of the statements apart from TRANSLATE and CONDENSE set the system field sy-subrc. SEARCH also sets the system field sy-fdpos with the offset of the beginning of the string found.All of the statements apart from SEARCH distinguish between upper- and lowercase.

To find out the occupied length of a string, use the standard function STRLEN().
The system searches the field for the string . The search string can have the following form:

'' String (trailing blanks are ignored)
'..' Any string between the periods (spaces are included in the search.)
'*' A string beginning with and including ''
'*' A string beginning with and including ''

The offset of the found string is placed in the system field sy-fdpos If the search string is not found, sy-fdpos contains the value 0 and sy-subrc is set to 4.
You can use SEARCH instead of SEARCH . The system then searches for the search string within the internal table . In this variant, the
system also sets the system field sy-tabix to the index of the line containing the search string.

In ABAP, you can program arithmetic expressions nested to any depth. You must remember that parentheses and operators are keywords, and must therefore be preceded and followed by at least one space.
The ABAP run time environment contains a range of functions for different data types. The opening parenthesis belongs to the functions name itself (and is therefore not separated from it by a space).The remaining elements of each expression must be separated by spaces.The expressions are processed in normal algebraic sequence - parenthetical expressions, followed by functions, powers, multiplication and division, and finally, addition and subtraction. A calculation may contain any data types that are convertible into each other and into the type of the result field. The system converts all of the fields into one of the three numeric data types (I, P, or F), depending on the data types of the operands. The ABAP runtime system contains an arithmetic for each of the three data types. The system then performs the calculation and converts it into the data type of the result field.



If you do not set the fixed point arithmetic option in the program attributes, the DECIMALS addition in the DATA statement only affects the output, not the arithmetic. In this case, all numbers are interpreted internally as integers, regardless of the position of the decimal point. You would then have to calculate the number of decimal places manually and ensure that the number was displayed correctly. Otherwise, the results would be meaningless.


You should therefore only use floating point numbe rs for approximations. When you compare numbers, always used intervals, and always round at the end of your calculations.
There are four general categories of runtime error that can occur in calculations:

A field that should have been converted could not be interpreted as a number.
A number range is too small for a conversion, value assignment, or to store intermediate results.
You tried to divide by zero.
You passed an invalid argument to a built-in function
(For example: ... log( -3 ) ... ).



CO only contains characters from ;
CN contains not only characters from (corresponds to NOT CO );
CA contains at least one character from ;
NA does not contain any characters from ;
CS contains the string ;
NS does not contain the string ;
CP contains the pattern ;
NP does not contain the pattern ;

The system field sy-fdpos contains the offset of the character that satisfies the condition, or the length of .In the first four expressions, the system takes into account upper- and lowercase letters and the full length of the string (SPACE column).To specify patterns, use '*' for any string, and '+' for any character. The escape symbol is '#'.

In a CASE - ENDCASE structure, you test a data object for equality against various values. When a test succeeds, the corresponding statement block is executed. If all of the comparisons fail, the OTHERS block is executed, if you have programmed one.

In an IF - ENDIF structure, you can use any logical expressions. If the condition is met, the corresponding statements are executed. If none of the conditions is true, the ELSE block is executed, if you have programmed one.


If each condition tests the same data object for equality with another object, you should use a CASEENDCASE structure. It is simpler, and requires less runtime .There are four loop structures. The number of the current loop pass is always available from the system field sy-index. If you use nested loops, the value of sy-index refers to the current one. You can take control over loop processing using the CHECK and EXIT statements. For further information, refer to Leaving Processing Blocks. The graphic shows how you can control the further processing of a loop. Mysap web application server
SAP web application and business server pages