Control Break Statements in SAP ABAP
By
SAP
-
January 29, 2014
7472
5
Control break events are used to control the sequence data flow inside the loops in ABAP.
1) AT FIRST
2) AT NEW
3) AT END OF
4) AT LAST
5) SUM
6) ON CHANGE OF
Note: AT-FIRST, AT-NEW,AT-END-OF,AT-LAST this events works only in between LOOP——ENDLOOP, We are also calling it as LOOP EVENTS
AT FIRST
It is the loop event, it triggers at first run of the loop.
Using this event we can display the page header.
AT FIRST ——————- END AT.
AT NEW
It is the loop event. Whenever the new field value is occurred then AT NEW event will trigger.
The trigger point will be at the first occurrence of the new value for the field.
SYNTAX
AT NEW ——————— END AT.
AT END OF
It is the loop event. It triggers at end of every field value.
Using this event we can calculate the subtotals.
SYNTAX
AT END OFS ——————— END AT.
AT LAST
It is the loop event. It triggers in the last loop operation
Using this event we can find calculate the grand totals.
SYNTAX
AT LAST ——————— END AT.
SUM
Sum is the keyword to find the totals.
ON CHANG OF
On change of it triggers only when there is any change in the particular field, we can use ON CHANGE OF loop and outside the Loop also.
We can use Logical expressions like AND OR can be used with ON CHANGE OF
SYNTAX
ON CHANGE OF ——————— END OF.
*&———————————————————————*
*& REPORT ZCEVENTS
*&
*&———————————————————————*
*&
*&
*&———————————————————————*
REPORT ZCEVENTS NO STANDARD PAGE HEADING.*// TABLES DECLARATION.
TABLES MARC.
*//TYPES DECLARATION FOR TY_MARC.
TYPES : BEGIN OF TY_MARC,
MATNR TYPE MATNR,
WERKS TYPE WERKS_D,
PSTAT TYPE PSTAT_D,
LVORM TYPE LVOWK,
PLIFZ TYPE PLIFZ,
END OF TY_MARC.*//TYPES DECLARATION FOR TY_MARC1.
TYPES : BEGIN OF TY_MARC1,
WERKS TYPE WERKS_D,
PSTAT TYPE PSTAT_D,
LVORM TYPE LVOWK,
PLIFZ TYPE PLIFZ,
MATNR TYPE MATNR,
END OF TY_MARC1.*//INTERNAL TABLE DECLARATION.
DATA : LT_MARC TYPE TABLE OF TY_MARC,
LT_MARC1 TYPE TABLE OF TY_MARC1.
*//WORKAREA DECLARATION.
DATA : WA_MARC TYPE TY_MARC,
WA_MARC1 TYPE TY_MARC1.
*//SELECTION SCREEN DESIGN.
SELECT-OPTIONS : S_MATNR FOR MARC-MATNR.*//RETRIVE THE DATA FROM MARA.
SELECT MATNR WERKS PSTAT LVORM PLIFZFROM MARC
INTO TABLE LT_MARC
WHERE MATNR IN S_MATNR.
IF SY-SUBRC EQ 0.
*//POPULATING DATA INTO FINAL INTERNAL TABLE.
LOOP AT LT_MARC INTO WA_MARC.***** WA_MARC1-MATNR = WA_MARC-MATNR.
***** WA_MARC1-WERKS = WA_MARC-WERKS.
***** WA_MARC1-PSTAT = WA_MARC-PSTAT.
***** WA_MARC1-LVORM = WA_MARC-LVORM.
***** WA_MARC1-PLIFZ = WA_MARC-PLIFZ.
MOVE-CORRESPONDING WA_MARC TO WA_MARC1.
APPEND WA_MARC1 TO LT_MARC1.CLEAR WA_MARC1.
ENDLOOP.
ENDIF.*// SORT BY SPECIFIC FIELD
SORT LT_MARC1 BY PSTAT.
*******//DISPLAY OUTPUT.
******LOOP AT LT_MARC1 INTO WA_MARC1.
****** WRITE : / WA_MARC1-MATNR,WA_MARC1-WERKS,WA_MARC1-PSTAT,WA_MARC1-LVORM,WA_MARC1-PLIFZ.
******ENDLOOP.
*//APPLY THE CONTROL BREAK EVENTS.
LOOP AT LT_MARC1 INTO WA_MARC1.*//AT FIRST.
AT FIRST.
WRITE : / ‘PLANT DATA’.
ULINE.
SKIP 2.
ENDAT.******//AT NEW.
***** AT NEW PSTAT.
***** WRITE : / ‘MAINTENANCE STATUS: ‘ ,WA_MARC1-PSTAT.
***** ENDAT.
***** WRITE : /,/ WA_MARC1-MATNR,WA_MARC1-WERKS,WA_MARC1-PSTAT,WA_MARC1-LVORM,WA_MARC1-PLIFZ .
*//ON CHANGE OF.
ON CHANGE OF WA_MARC1-PSTAT.
WRITE : /,/ ‘MAINTENANCE STATUS :’,WA_MARC1-PSTAT.
ENDON.WRITE : / WA_MARC1-MATNR,WA_MARC1-WERKS,WA_MARC1-PSTAT,WA_MARC1-LVORM,WA_MARC1-PLIFZ.
*//AT END OF.
AT END OF PSTAT.
SUM .
WRITE : /30 ‘SUBTOTAL’, WA_MARC1-PLIFZ.
ENDAT.*//AT LAST.
AT LAST.
SUM.
WRITE : /30 ‘GRAND TOTAL’,WA_MARC1-PLIFZ.
ENDAT.
ENDLOOP.Click on Execute.
Enjoy
Creating Pushbuttons on Selection Screen.
Display a Column As a Pushbutton in the ALV Report Output.
How to Create Transaction Code for Table Maintenance Generator in SAP.
TAGS
ABAP Tutorials
abap tutorials for beginners
SAP
SAP ABAP
SAP ABAP Tutorials
Previous articleBenefits of BW on HANA
Next articleTable Maintenance without using SE11 and SE30 Transaction Codes
SAP
RELATED ARTICLESMORE FROM AUTHOR
SAP ABAP
SAP ABAP Online Quiz 4
SAP ABAP
Difference Between Main Window and Variable Window in SAP
SAP ABAP
Display PO And Goods Receipt Details Against Purchase Requisition – SAP Reports
SAP ABAP
Business Application Programming Interface Introduction – BAPI
SAP ABAP
Interactive reports in SAP ABAP
SAP ABAP
SAP ABAP report with checkbox to Download selected records at Runtime
5 COMMENTS
Deepthi January 30, 2014 at 12:28 pm
Hi ,i am not finding any post for webdynpro, can you provide it.
Reply
SAP January 30, 2014 at 12:50 pm
Hi deepthi currently i am writing ABAP post, it will take some time to write post on Webdynpro
Reply
garapati surendra February 3, 2014 at 6:37 am
hi can i post some documents on your site and how can i post…
Thank u..
Reply
SAP February 3, 2014 at 6:44 am
Send ur documents editor to editor@sapsimplified.com, i will publish your documents with your name.
Reply
Naveen March 5, 2014 at 11:59 am
. Please Provide Interviews Questions for 2 Years/3 Years Experiences
Reply
Leave a Reply
以下内容整理自 SAP 官方 ABAP 速查表(主题:Program Flow Logic),作为本文的扩展补充资料。
IF StatementsCOND OperatorCASE: Case DistinctionsSWITCH OperatorDO: Unconditional LoopsWHILE: Conditional LoopsThis cheat sheet gathers information on program flow logic. Find more details here in the ABAP Keyword Documentation.
In ABAP, the flow of a program is controlled by control structures, procedure calls and the raising or handling of exceptions.
Using control structures as an example, you can determine the conditions for further processing of code, for example, if at all or how often a statement block should be executed. Control structures - as, for example, realized by an IF ... ELSEIF ... ELSE ... ENDIF. statement - can include multiple statement blocks that are executed depending on conditions.
In a very simple form, such an IF statement might look as follows:
DATA(num) = 1 + 1.
"A simple condition: Checking if the value of num is 2
IF num = 2.
... "Statement block
"Here goes some code that should be executed if the condition is true.
ELSE.
... "Statement block
"Here goes some code that should be executed if the condition is false.
"For example, if num is 1, 8, 235, 0 etc., then do something else.
ENDIF.... num = 2 ... - a logical expression.NOT, AND and OR."Single relational expression
IF num = 1.
...
ENDIF.
"Multiple expressions
IF num = 1 AND flag = 'X'.
...
ENDIF.
IF num = 1 OR flag = 'X'.
...
ENDIF.
"Multiple expressions can be parenthesized explicitly
IF ( num = 1 AND flag = 'X' ) OR ( num = 2 AND flag = 'X' ).
...
ENDIF.the comparisons are carried out according to comparison rules.
The following code snippet shows a selection of possible expressions and operands of such expressions using a big IF statement. Certainly, such a huge statement is far from ideal. Here, the intention is to just cover many syntax options in one go for demonstration purposes. For more information on built-in functions, you can refer to the Built-In Functions cheat sheet.
"Some declarations to be used in the IF statement below
DATA(num) = 2. "integer
DATA(empty_string) = ``. "empty string
DATA(flag) = 'x'.
DATA(dref) = NEW string( `ref` ). "data reference variable
"Object reference variable
DATA oref TYPE REF TO object.
"Creating an object and assigning it to the reference variable
oref = NEW zcl_demo_abap_prog_flow_logic( ).
"Declaration of and assignment to a field symbol
FIELD-SYMBOLS <fs> TYPE string.
ASSIGN `hallo` TO <fs>.
"Creating an internal table of type string inline
DATA(str_table) = VALUE string_table( ( `a` ) ( `b` ) ( `c` ) ).
"The following IF statement includes multiple expressions combined by AND to demonstrate different options
"Comparisons
IF 2 = num "equal, alternative EQ
AND 1 <> num "not equal, alternative NE
AND 1 < num "less than, alternative LT
AND 3 > num "greater than, alternative GT
AND 2 >= num "greater equal, alternative GE
AND 2 <= num "less equal, alternative LE
"Checks whether the content of an operand is within a closed interval
AND num BETWEEN 1 AND 3
AND NOT num BETWEEN 5 AND 7 "NOT negates a logical expression
AND ( num >= 1 AND num <= 3 ) "Equivalent to 'num BETWEEN 1 AND 3';
"here, demonstrating the use of parentheses
"Comparison operators CO, CN ,CA, NA, CS, NS, CP, NP for character-like data types;
"see the cheat sheet on string processing
"Predicate Expressions
AND empty_string IS INITIAL "Checks whether the operand is initial. The expression
"is true, if the operand contains its type-dependent initial value
AND num IS NOT INITIAL "NOT negates
AND dref IS BOUND "Checks whether a data reference variable contains a valid reference and
"can be dereferenced;
"Negation (IS NOT BOUND) is possible which is also valid for the following examples
AND oref IS BOUND "Checks whether an object reference variable contains a valid reference
"IS INSTANCE OF checks whether for a
"a) non-initial object reference variable the dynamic type
"b) for an initial object reference variable the static type
"is more specific or equal to a comparison type.
AND oref IS INSTANCE OF zcl_demo_abap_prog_flow_logic
AND oref IS INSTANCE OF if_oo_adt_classrun
AND <fs> IS ASSIGNED "Checks whether a memory area is assigned to a field symbol
"See the predicate expression IS SUPPLIED in the executable example.
"It is available in method implementations and checks whether a formal parameter
"of a procedure is filled or requested.
"Predicate function: Some examples
AND contains( val = <fs> pcre = `\D` ) "Checks whether a certain value is contained;
"the example uses the pcre parameter for regular expressions;
"it checks whether there is any non-digit character contained
AND matches( val = <fs> pcre = `ha.+` ) "Compares a search range of the argument for the val parameter;
"the example uses the pcre parameter for regular expressions;
"it checks whether the value matches the pattern 'ha'
"and a sequence of any characters
"Predicate functions for table-like arguments
"Checks whether a line of an internal table specified in the table expression
"exists and returns the corresponding truth value.
AND line_exists( str_table[ 2 ] )
"Predicative method call
"The result of the relational expression is true if the result of the functional method call
"is not initial and false if it is initial. The data type of the result of the functional method call,
"i. e. the return value of the called function method, is arbitrary.
"A check is made for the type-dependent initial value.
AND check_is_supplied( )
"It is basically the short form of such a predicate expression:
AND check_is_supplied( ) IS NOT INITIAL
"Boolean Functions
"Determine the truth value of a logical expression specified as an argument;
"the return value has a data type dependent on the function and expresses
"the truth value of the logical expression with a value of this type.
"Function boolc: Returns a single-character character string of the type string.
"If the logical expression is true, X is returned. False: A blank is returned.
"Not to be compared with the constants abap_true and abap_false in relational expressions,
"since the latter convert from c to string and ignore any blanks. Note: If the logical
"expression is false, the result of boolc does not meet the condition IS INITIAL since
"a blank and no empty string is returned. If this is desired, the function xsdbool
"can be used instead of boolc.
AND boolc( check_is_supplied( ) ) = 'X'
"Result has the same ABAP type as abap_bool.
AND xsdbool( check_is_supplied( ) ) = abap_true
"Examples for possible operands
"Data objects as shown in the examples above
AND 2 = 2
AND num = 2
"Built-in functions
AND to_upper( flag ) = 'X'
AND NOT to_lower( flag ) = 'X'
"Numeric functions
AND ipow( base = num exp = 2 ) = 4
"Functional methods
"Assume such a method exists having one return value
AND addition( num1 = 1 num2 = 1 ) = 2
"Calculation expressions
AND 4 - 3 + 1 = num
"String expressions
AND `ha` && `llo` = <fs>
"Constructor expression
AND VALUE i( ) = 0
AND VALUE string_table( ( `a` ) ( `b` ) ( `c` ) ) = str_table
"Table expression
AND str_table[ 2 ] = `b`.
... "All of the logical expressions are true.
ELSE.
... "At least one of the logical expressions is false.
ENDIF.[!NOTE] - Logical expressions and functions can also be used in other ABAP statements. - Similar to predicative method calls, individual data objects can represent a relational expression, returning a truth value. The expression evaluates to true if the operand's content is not initial. The type-specific initial value is checked. As an example,IF flag. ...corresponds toIF flag IS NOT INITIAL. .... ``abap DATA(flag) = 'X'. IF flag. ... ELSE. ... ENDIF.``
[!TIP] Find more information in the Logical Expressions and Functions ABAP cheat sheet.
IF StatementsIF statements define statement blocks that can be included in branches.ELSE statement is executed.ELSE and ELSEIF statements are optional. However, it is recommended that you specify an ELSE so that at least one statement block is executed.ENDIF..DATA(abap) = `ABAP`.
FIND `AB` IN abap.
IF sy-subrc = 0.
"found
...
ELSE.
"not found
...
ENDIF.
"IF statement with multiple included ELSEIF statements
DATA(current_utc_time) = cl_abap_context_info=>get_system_time( ).
DATA greetings TYPE string.
IF current_utc_time BETWEEN '050000' AND '115959'.
greetings = |Good morning, it's { current_utc_time TIME = ISO }.|.
ELSEIF current_utc_time BETWEEN '120000' AND '175959'.
greetings = |Good afternoon, it's { current_utc_time TIME = ISO }.|.
ELSEIF current_utc_time BETWEEN '180000' AND '215959'.
greetings = |Good evening, it's { current_utc_time TIME = ISO }.|.
ELSE.
greetings = |Good night, it's { current_utc_time TIME = ISO }.|.
ENDIF.
Control structures can be nested.
DATA(num) = 1.
DATA(flag) = 'X'.
IF num = 1.
IF flag = 'X'.
...
ELSE.
...
ENDIF.
ELSE.
... "statement block, e. g.
"ASSERT 1 = 0.
"Not to be executed in this example.
ENDIF.[!NOTE] - Control structures can be nested. It is recommended that you do not include more than 5 nested control structures since the code will get really hard to understand. Better go for outsourcing functionality into methods to reduce nested control structures. - Keep the number of consecutive control structures low. - If you are convinced that a specified logical expression must always be true, you might include a statement likeASSERT 1 = 0.to go sure - as implied in the example'sELSEstatement above. However, anELSEstatement that is never executed might be a hint that logical expressions might partly be redundant.
COND OperatorCOND can also be used to implement branches in operand positions that are based on logical expressions.COND right before the first parenthesis. It can also be the # character as a symbol for the operand type if the type can be derived from the context. THEN must be convertible to the result's data type.DATA greetings_cond TYPE string.
DATA(current_utc_time_cond) = cl_abap_context_info=>get_system_time( ).
greetings_cond = COND #( WHEN current_utc_time_cond BETWEEN '050000' AND '115959' THEN |Good morning, it's { current_utc_time_cond TIME = ISO }.|
WHEN current_utc_time_cond BETWEEN '120000' AND '175959' THEN |Good afternoon, it's { current_utc_time_cond TIME = ISO }.|
WHEN current_utc_time_cond BETWEEN '180000' AND '215959' THEN |Good evening, it's { current_utc_time_cond TIME = ISO }.|
ELSE |Good night, it's { current_utc_time_cond TIME = ISO }.| ).
[!NOTE] There are special rules regarding type inference when using expressions withCONDandSWITCHwith#for actual parameters in case of generic formal parameters. Find more information here.
CASE: Case DistinctionsCASE statements are used for case distinctions.CASE.WHEN matches the content specified after CASE, the statement block is executed. Constant values should be specified as operands.WHEN statement can include more than one operand using the syntax WHEN op1 OR op2 OR op3 ....WHEN OTHERS. which is optional.ENDCASE.."Getting a random number
DATA(random_num) = cl_abap_random_int=>create( seed = cl_abap_random=>seed( )
min = 1
max = 5 )->get_next( ).
DATA num TYPE string.
CASE random_num.
WHEN 1.
num = `The number is 1.`.
WHEN 2.
num = `The number is 2.`.
WHEN 3 OR 4.
num = `The number is either 3 or 4.`.
WHEN OTHERS.
num = `The number is not between 1 and 4.`.
ENDCASE.Special control structure introduced by CASE TYPE OF: Checks the type of object reference variables. An object reference variable with the static type of a class or an interface must be specified after CASE TYPE OF.
"The example shows the retrieval of type information at runtime (RTTI).
"For more information on RTTI, refer to the Dynamic Programming cheat
"sheet. The result of the method call is a type description object
"that points to one of the classes specified.
DATA stringtab TYPE TABLE OF string WITH EMPTY KEY.
DATA(type_description) = cl_abap_typedescr=>describe_by_data( stringtab ).
CASE TYPE OF type_description.
WHEN TYPE cl_abap_elemdescr.
...
WHEN TYPE cl_abap_refdescr.
...
WHEN TYPE cl_abap_structdescr.
...
WHEN TYPE cl_abap_tabledescr.
"This is the class the type description object points to for
"the example data object.
...
WHEN OTHERS.
...
ENDCASE.SWITCH OperatorThe conditional operator SWITCH can also be used to make case distinctions in operand positions. As mentioned above for COND, a result is constructed. The same criteria apply for SWITCH as for COND regarding the type. See also the ABAP Keyword Documentation and the Constructor Expressions cheat sheet for more information and examples.
DATA(random_num_switch) = cl_abap_random_int=>create( seed = cl_abap_random=>seed( )
min = 1
max = 5 )->get_next( ).
DATA(num_switch) = SWITCH #( random_num_switch
WHEN 1 THEN `The number is 1.`
WHEN 2 THEN `The number is 2.`
WHEN 3 OR 4 THEN `The number is either 3 or 4.`
ELSE `The number is not between 1 and 4.` ).DO: Unconditional LoopsDO and ENDDO is carried out multiple times.EXIT, see further down). Otherwise, it is executed endlessly. DATA str_a TYPE string.
DO.
str_a &&= sy-index.
IF sy-index = 5.
EXIT.
ENDIF.
ENDDO.
"str_a: 12345TIMES addition and specify the maximum number of loop passes. DATA str_b TYPE string.
DO 9 TIMES.
str_b &&= sy-index.
ENDDO.
"str_b: 123456789sy-index within the statement block contains the number of previous loop passes including the current pass.The following ABAP keywords are available for interrupting and exiting loops:
| Keyword | Syntax | Details |
|---|---|---|
CONTINUE | CONTINUE. | The current loop pass is terminated immediately and the program flow is continued with the next loop pass. |
CHECK | CHECK log_exp. | Conditional termination. If the logical expression log_exp is false, the current loop pass is terminated immediately and the program flow is continued with the next loop pass. |
EXIT | EXIT. | The loop is terminated completely. The program flow resumes after the closing statement of the loop. |
*&---------------------------------------------------------------------*
*& CONTINUE
*&---------------------------------------------------------------------*
DATA str_c TYPE string.
DO 15 TIMES.
"Continue with the next loop pass if the number is even
"Terminating the loop pass and continuing with the next loop pass if the condition specified
"with the IF statement is true (if the number is even)
IF sy-index MOD 2 = 0.
CONTINUE.
ELSE.
str_c = |{ str_c }{ COND #( WHEN str_c IS NOT INITIAL THEN `, ` ) }{ sy-index }|.
ENDIF.
ENDDO.
"str_c: 1, 3, 5, 7, 9, 11, 13, 15
*&---------------------------------------------------------------------*
*& CHECK
*&---------------------------------------------------------------------*
DATA str_d TYPE string.
DO 15 TIMES.
"Terminating the loop pass and continuing with the next loop pass if the condition is
"true (if the number is odd)
CHECK sy-index MOD 2 = 0.
str_d = |{ str_d }{ COND #( WHEN str_d IS NOT INITIAL THEN `, ` ) }{ sy-index }|.
ENDDO.
"str_d: 2, 4, 6, 8, 10, 12, 14
"CHECK NOT
DATA str_e TYPE string.
DO 15 TIMES.
"Here, it is checked whether the sy-index value is not an even number
CHECK NOT sy-index MOD 2 = 0.
str_e = |{ str_e }{ COND #( WHEN str_e IS NOT INITIAL THEN `, ` ) }{ sy-index }|.
ENDDO.
"str_e: 1, 3, 5, 7, 9, 11, 13, 15
*&---------------------------------------------------------------------*
*& EXIT
*&---------------------------------------------------------------------*
DATA str_f TYPE string.
DO 15 TIMES.
"Terminating the entire loop
IF sy-index = 7.
EXIT.
ELSE.
str_f = |{ str_f }{ COND #( WHEN str_f IS NOT INITIAL THEN `, ` ) }{ sy-index }|.
ENDIF.
ENDDO.
"str_f: 1, 2, 3, 4, 5, 6[!NOTE] -RETURNstatements immediately terminate the current processing block. However, according to the guidelines (F1 docu for standard ABAP),RETURNshould only be used to exit procedures like methods. -EXITandCHECKmight also be used for exiting procedures. However, their use inside loops is recommended.
WHILE: Conditional LoopsWHILE and ended by ENDWHILE are repeated as long as a logical expression is true.DO loops, the system field sy-index contains the number of previous loop passes including the current pass.FOR ... WHILE with a constructor expression in the Constructor Expressions cheat sheet.DATA int_itab TYPE TABLE OF i WITH EMPTY KEY.
WHILE lines( int_itab ) = 5.
int_itab = VALUE #( BASE int_itab ( sy-index ) ).
ENDWHILE.
"Content of int_itab:
"1
"2
"3
"4
"5
"The following string replacement example uses a WHILE
"statement for demo purposes - instead of using a REPLACE ALL
"OCCURRENCES statement or the replace function to replace all
"occurrences. The WHILE loop exits when there are no more '#'
"characters to be replaced in the string. The value of the data
"object, which is checked in the logical expression, is then set
"to make the logical expression false.
DATA(str_to_replace) = `Lorem#ipsum#dolor#sit#amet`.
DATA(subrc) = 0.
DATA(counter) = 0.
WHILE subrc = 0.
REPLACE `#` IN str_to_replace WITH ` `.
IF sy-subrc <> 0.
subrc = 1.
ELSE.
counter += 1.
ENDIF.
ENDWHILE.
"str_to_replace: Lorem ipsum dolor sit amet
"counter: 4Further keywords for defining loops are as follows. They are not dealt with here since they are covered in other ABAP cheat sheets.
LOOP ... ENDLOOP statements are meant for loops across internal tables. See also the cheat sheet on internal tables.sy-index is not set. Instead, the system field sy-tabix is set and which contains the table index of the current table line in the loop pass.FOR loops: You can also realize loops using iteration expressions with VALUE and REDUCE. For more information, refer to the Constructor Expressions cheat sheet.SELECT ... ENDSELECT statements loop across the result set of a data source access. See also the cheat sheet on ABAP SQL.Procedures can be explicitly called within an ABAP program, thereby influencing the program flow logic.
In modern ABAP programs, classes and methods are the way to go for modularization purposes (instead of function modules and subroutines in most cases; the latter is only available in Standard ABAP). Note that methods and calling methods are described in the context of the ABAP Object Orientation cheat sheet. Find more information and examples there.
[!NOTE] Find information on events in the ABAP Object Orientation cheat sheet.
[!NOTE] In ABAP for Cloud Development, function modules can technically be used, but they are not recommended for new implementations. Many features available in standard ABAP, such as various includes, are not compatible with ABAP for Cloud Development (for example, dynpro-related functionality).
Function modules ...
FUNCTION ... .
...
ENDFUNCTION.CALL FUNCTION statements.Function pools ...
FUNCTION-POOL statement. Syntax to call function modules:
CALL FUNCTION func params.func: Character-like data object (for example, a literal) that contains the name of a function module in uppercase lettersparams: Parameter list or table CL_ABAP_DYN_PRG as shown in the Released ABAP Classes cheat sheet. sy-subrc is set to 0. If a non-class-based exception is raised and a value is assigned to handle it, this value updates sy-subrc.Example function module calls with parameter passing and exception handling:
"Handling non-class-based exception
DATA it TYPE some_table_type.
CALL FUNCTION 'SOME_FUNCTION_MODULE_A'
EXPORTING
param_a = 'somevalue'
IMPORTING
param_b = it
EXCEPTIONS
not_found = 4.
IF sy-subrc <> 0.
...
ENDIF.
"Handling class-based exception
TRY.
CALL FUNCTION 'SOME_FUNCTION_MODULE_B'
EXPORTING
param_c = 'somevalue'
IMPORTING
param_d = it.
CATCH cx_some_exception INTO DATA(exc).
...
ENDTRY.
*&---------------------------------------------------------------------*
*& Dynamic function method calls
*&---------------------------------------------------------------------*
"Function module name contained in a variable
DATA(func_name) = 'SOME_FUNCTION_MODULE_C'.
CALL FUNCTION func_name ...
"For parameters in a parameter table, use the addition ... PARAMETER-TABLE ptab ...
"ptab: Sorted table of type abap_func_parmbind_tab (line type abap_func_parmbind)
"For exceptions, use the addition ... EXCEPTION-TABLE ...
DATA(ptab) = VALUE abap_func_parmbind_tab( ... ).
CALL FUNCTION func_name PARAMETER-TABLE ptab.Expand the following section to get a simple executable example:
🟢 Click to expand for more information and example code
The following example demonstrates a simple function module:
PARAMETER-TABLE addition.To get started quickly with copiable code snippets, you can proceed as follows.
Z_DEMO_ABAP_TEST_FUNC_P) and Description Field (e.g. Demo function group) fields, and choose Next.Z_DEMO_ABAP_TEST_FUNC_M), Description Field (e.g. Demo function module), and Function Group (e.g. the previously created Z_DEMO_ABAP_TEST_FUNC_P) fields and choose Next.ZCL_DEMO_ABAP_FUNC_TEST, and copy and paste the code below. Code for the function module Z_DEMO_ABAP_TEST_FUNC_M:
FUNCTION z_demo_abap_test_func_m
IMPORTING
num1 TYPE i
operator TYPE string
num2 TYPE i
EXPORTING
result TYPE string
RAISING
cx_sy_arithmetic_error.
"ABAP 'allows' zero division if both operands are 0.
IF num1 = 0 AND num2 = 0.
RAISE EXCEPTION TYPE cx_sy_zerodivide.
ENDIF.
DATA op TYPE c LENGTH 1.
op = condense( val = operator to = `` ).
result = SWITCH #( op
WHEN '+' THEN |{ num1 } + { num2 } = { num1 + num2 STYLE = SIMPLE }|
WHEN '-' THEN |{ num1 } - { num2 } = { num1 - num2 STYLE = SIMPLE }|
WHEN '*' THEN |{ num1 } * { num2 } = { num1 * num2 STYLE = SIMPLE }|
WHEN '/' THEN |{ num1 } / { num2 } = { CONV decfloat34( num1 / num2 ) STYLE = SIMPLE }|
ELSE `Use one of the operators + - * /` ).
ENDFUNCTION.Code for the class ZCL_DEMO_ABAP_FUNC_TEST that can be run in ADT choosing F9:
CLASS zcl_demo_abap_func_test DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS zcl_demo_abap_func_test IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
"Calling a function module
"For handling a possible wrong operator in the example, you may want to implement
"a separate exception. The simple example just catches calculation errors
"and uses a data object of type string for storing the calculation result.
DATA calculation_result TYPE string.
TRY.
CALL FUNCTION 'Z_DEMO_ABAP_TEST_FUNC_M'
EXPORTING
num1 = 1
operator = `+`
num2 = 2
IMPORTING
result = calculation_result.
CATCH cx_sy_arithmetic_error INTO DATA(exc).
calculation_result = exc->get_text( ).
ENDTRY.
out->write( calculation_result && |\n\n| ).
"More calculation examples; calculations are stored in a table
DATA calculation_result_table TYPE string_table.
TYPES: BEGIN OF s,
num1 TYPE i,
operator TYPE string,
num2 TYPE i,
END OF s,
it_type TYPE TABLE OF s WITH EMPTY KEY.
DATA(itab) = VALUE it_type( ( num1 = 10 operator = `-` num2 = 12 )
( num1 = 15 operator = `*` num2 = 4 )
( num1 = 7 operator = `/` num2 = 2 )
( num1 = 1 operator = `/` num2 = 0 )
( num1 = 0 operator = `/` num2 = 0 )
( num1 = 9999999 operator = `*` num2 = 9999999 ) ).
LOOP AT itab INTO DATA(wa).
TRY.
CALL FUNCTION 'Z_DEMO_ABAP_TEST_FUNC_M'
EXPORTING
num1 = wa-num1
operator = wa-operator
num2 = wa-num2
IMPORTING
result = calculation_result.
CATCH cx_sy_arithmetic_error INTO exc.
calculation_result = |{ wa-num1 } { wa-operator } { wa-num2 } -> Error: { exc->get_text( ) }|.
ENDTRY.
APPEND calculation_result TO calculation_result_table.
ENDLOOP.
out->write( calculation_result_table ).
out->write( |\n\n\n| ).
*&---------------------------------------------------------------------*
*& Dynamic function module call
*&---------------------------------------------------------------------*
DATA(func_name) = 'Z_DEMO_ABAP_TEST_FUNC_M'.
DATA(ptab) = VALUE abap_func_parmbind_tab( ( name = 'NUM1'
kind = abap_func_exporting
value = NEW i( 3 ) )
( name = 'OPERATOR'
kind = abap_func_exporting
value = NEW string( `+` ) )
( name = 'NUM2'
kind = abap_func_exporting
value = NEW i( 5 ) )
( name = 'RESULT'
kind = abap_func_importing
value = NEW string( ) ) ).
CALL FUNCTION func_name PARAMETER-TABLE ptab.
out->write( data = ptab name = `ptab` ).
ENDMETHOD.
ENDCLASS.Special function modules exist in Standard ABAP (and not in ABAP for Cloud Development), and for which special properties are specified in the Function Builder:
CALL FUNCTION ... IN UPDATE TASKCALL FUNCTION ... DESTINATION CALL FUNCTION ... STARTING NEW TASK CALL FUNCTION ... IN BACKGROUND UNIT. Find more information here.FORM and ENDFORM.PERFORM statementsPERFORM ... ON COMMIT and ... ROLLBACK).Regarding the exiting of procedures, note the hint mentioned above. The use of RETURN is recommended.
RETURN terminates the current processing block. Usually, the statement is intended for leaving processing blocks early. In case of functional methods, i.e. methods that have one returning parameter, the RETURN statement can also be specified with an expression. In doing so, the following statement
res = some_expr.
RETURN.can also be specified as follows:
RETURN some_expr.In the following example, the expression result is passed to the returning parameter without naming it explicitly. As an expression, you can specify a constructor expression (and using type inference with # means using the type of the returning parameter).
CLASS zcl_demo_abap DEFINITION
PUBLIC
FINAL
CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES: if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
CLASS-METHODS multiply
IMPORTING num1 TYPE i
num2 TYPE i
RETURNING VALUE(result) TYPE i.
ENDCLASS.
CLASS zcl_demo_abap IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
DATA(res1) = multiply( num1 = 2 num2 = 3 ).
DATA(res2) = multiply( num1 = 10 num2 = 10 ).
DATA(res3) = multiply( num1 = 99999999 num2 = 99999999 ).
out->write( res1 ). "6
out->write( res2 ). "100
out->write( res3 ). "0
ENDMETHOD.
METHOD multiply.
TRY.
"result = num1 * num2.
RETURN num1 * num2.
CATCH cx_sy_arithmetic_error.
"The following statement is actually not needed in the example, but used nevertheless
"to showcase the specification of a constructor expression after RETURN.
RETURN VALUE #( ).
ENDTRY.
ENDMETHOD.
ENDCLASS.Using WAIT UP TO statements, you can interrupt the program execution by a specified number of seconds.
"First retrieval of the current time stamp
DATA(ts1) = utclong_current( ).
...
WAIT UP TO 1 SECONDS.
...
WAIT UP TO 3 SECONDS.
...
"Second retrieval of the current time stamp after the WAIT statements
DATA(ts2) = utclong_current( ).
"Calculating the difference of the two time stamps
cl_abap_utclong=>diff( EXPORTING high = ts2
low = ts1
IMPORTING seconds = DATA(seconds) ).
"The value of the 'seconds' data object holding the delta of the time stamps
"should be greater than 4.
ASSERT seconds > 4.Exceptions and runtime errors affect the program flow. Find an overview in the Exceptions and Runtime Errors cheat sheet.
[!NOTE] - The executable example ... - covers the following topics, among others: - Control structures withIF,CASE, andTRY- Excursions:CONDandSWITCHoperators - Expressions and functions for conditions - Predicate expression withIS SUPPLIED- Loops withDO,WHILE, andLOOP- Terminating loop passes - Handling exceptions - The steps to import and run the code are outlined here. - Disclaimer
13_Program_Flow_Logic.md。版权归原作者所有。