Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Showing posts with label ABAP and JAVA. Show all posts
Showing posts with label ABAP and JAVA. Show all posts

Thursday, February 21, 2008

What is ABAP?

ABAP is a programming language for developing applications for the SAP R/3 system. The latest version, ABAP Objects, is object-oriented programming. SAP will run applications written using ABAP/4, the earlier ABAP version, as well as applications using ABAP Objects.

ABAP Technical Interview Questions

1. What is the typical structure of an ABAP program?
2. What are field symbols and field groups.? Have you used "component idx of structure" clause with field groups?
3. What should be the approach for writing a BDC program?
4. What is a batch input session?
5. What is the alternative to batch input session?
6. A situation: An ABAP program creates a batch input session. We need to submit the program and the batch session in background. How to do it?
7. What is the difference between a pool table and a transparent table and how they are stored at the database level?
8. What are the problems in processing batch input sessions? How is batch input process different from processing on line?
9. What do you define in the domain and data element?
10. What are the different types of data dictionary objects?
11. How many types of tables exist and what are they in data dictionary?
12. What is the step-by-step process to create a table in data dictionary?
13. Can a transparent table exist in data dictionary but not in the database physically?
14. What are the domains and data elements?
15. Can you create a table with fields not referring to data elements?
16. What is the advantage of structures? How do you use them in the ABAP programs?
17. What does an extract statement do in the ABAP program?
18. What is a collect statement? How is it different from append?
19. What is open sql vs native sql?
20. What does an EXEC SQL stmt do in ABAP? What is the disadvantage of using it?
21. What is the meaning of ABAP editor integrated with ABAP data dictionary?
22. What are the events in ABAP language?
23. What is an interactive report? What is the obvious diff of such report compared with classical type reports?
24. What is a drill down report?
25. How do you write a function module in SAP? Describe.
26. What are the exceptions in function module?
27. What is a function group?
28. How are the date abd time field values stored in SAP?
29. What are the fields in a BDC_Tab Table?
30. Name a few data dictionary objects?
31. What happens when a table is activated in DD?
32. What is a check table and what is a value table?
33. What are match codes? Describe?
34. What transactions do you use for data analysis?
35. What is table maintenance generator?
36. What are ranges? What are number ranges?
37. What are select options and what is the diff from parameters?
38. How do you validate the selection criteria of a report? And how do you display initial values in a selection screen?
39. What are selection texts?
40. What is CTS and what do you know about it?
41. When a program is created and need to be transported to prodn does selection texts always go with it? if not how do you make sure? Can you change the CTS entries? How do you do it?
42. What is the client concept in SAP? What is the meaning of client independent?
43. Are programs client dependent?
44. Name a few system global variables you can use in ABAP programs?
45. What are internal tables? How do you get the number of lines in an internal table? How to use a specific number occurs statement?
46. How do you take care of performance issues in your ABAP programs?
47. What are datasets?
48. How to find the return code of a stmt in ABAP programs?
49. What are interface/conversion programs in SAP?
50. Have you used SAP supplied programs to load master data?

2. Adapted from response by Maram Roja on Tuesday, June 15, 2004

1. What are the techniques involved in using SAP supplied programs? Do you prefer to write your own programs to load master data? Why?
2. What are logical databases? What are the advantages/disadvantages of logical databases?
3. What specific statements do you using when writing a drill down report?
4. What are different tools to report data in SAP? What all have you used?
5. What are the advantages and disadvantages of ABAP query tool?
6. What are the functional areas? User groups? How does ABAP query work in relation to these?
7. Is a logical database a requirement/must to write an ABAP query?
8. What is the structure of a BDC sessions.
9. What are Change header/detail tables? Have you used them?
10. What do you do when the system crashes in the middle of a BDC batch session?
11. What do you do with errors in BDC batch sessions?
12. How do you set up background jobs in SAP? What are the steps? What are the event driven batch jobs?
13. Is it possible to run host command from SAP environment? How do you run?
14. What kind of financial periods exist in SAP? What is the relevant table for that?
15. Does SAP handle multiple currencies? Multiple languages?
16. What is a currency factoring technique?
17. How do you document ABAP programs? Do you use program documentation menu option?
18. What is SAPscript and layout set?
19. What are the ABAP commands that link to a layout set?
20. What is output determination? ABAP Technical Interview Questions:

1. What is the typical structure of an ABAP program?
2. What are field symbols and field groups.? Have you used "component idx of structure" clause with field groups?
3. What should be the approach for writing a BDC program?
4. What is a batch input session?
5. What is the alternative to batch input session?
6. A situation: An ABAP program creates a batch input session. We need to submit the program and the batch session in background. How to do it?
7. What is the difference between a pool table and a transparent table and how they are stored at the database level?
8. What are the problems in processing batch input sessions? How is batch input process different from processing on line?
9. What do you define in the domain and data element?
10. What are the different types of data dictionary objects?
11. How many types of tables exist and what are they in data dictionary?
12. What is the step-by-step process to create a table in data dictionary?
13. Can a transparent table exist in data dictionary but not in the database physically?
14. What are the domains and data elements?
15. Can you create a table with fields not referring to data elements?
16. What is the advantage of structures? How do you use them in the ABAP programs?
17. What does an extract statement do in the ABAP program?
18. What is a collect statement? How is it different from append?
19. What is open sql vs native sql?
20. What does an EXEC SQL stmt do in ABAP? What is the disadvantage of using it?
21. What is the meaning of ABAP editor integrated with ABAP data dictionary?
22. What are the events in ABAP language?
23. What is an interactive report? What is the obvious diff of such report compared with classical type reports?
24. What is a drill down report?
25. How do you write a function module in SAP? Describe.
26. What are the exceptions in function module?
27. What is a function group?
28. How are the date abd time field values stored in SAP?
29. What are the fields in a BDC_Tab Table?
30. Name a few data dictionary objects?
31. What happens when a table is activated in DD?
32. What is a check table and what is a value table?
33. What are match codes? Describe?
34. What transactions do you use for data analysis?
35. What is table maintenance generator?
36. What are ranges? What are number ranges?
37. What are select options and what is the diff from parameters?
38. How do you validate the selection criteria of a report? And how do you display initial values in a selection screen?
39. What are selection texts?
40. What is CTS and what do you know about it?
41. When a program is created and need to be transported to prodn does selection texts always go with it? if not how do you make sure? Can you change the CTS entries? How do you do it?
42. What is the client concept in SAP? What is the meaning of client independent?
43. Are programs client dependent?
44. Name a few system global variables you can use in ABAP programs?
45. What are internal tables? How do you get the number of lines in an internal table? How to use a specific number occurs statement?
46. How do you take care of performance issues in your ABAP programs?
47. What are datasets?
48. How to find the return code of a stmt in ABAP programs?
49. What are interface/conversion programs in SAP?
50. Have you used SAP supplied programs to load master data?

Break Points in ABAP

You can now create (de)activable breakpoints in your programs. You can release these breakpoints in production and a customer will have the opportunity to activate and debug your code more easily.

The following is an activable break-point : BREAK-POINT ID dany.

The checkpoint group is defined by double clicking on the checkpoint group in the editor OR directly via transaction SAAB.

Below is the SAAB screen. In the breakpoints part of the screen, you can set it to "inactive" or "break". All breakpoint groups will be shipped inactive by default.

Assert :

An assertion is a condition which must be true during program execution. By using asserts in your program, you can find cause of error in shorter time. The reaction when violating an assertion depend on a customizing and could be :

  1. Start the debugger from this assert

  2. Do nothing, ignore the assert

  3. Log the assertion in a log

  4. Terminate the program with runtime error ASSERTION_FAILED

The assertions are defined in SAAB (exactly like the breakpoints, see screen above).Here is an example of a use for an assertion :

METHOD sort_by_name.
     
DATA: l_f1 TYPE i VALUE 2,
      l_f2 TYPE c LENGTH 10 VALUE 'test',
      l_t1 TYPE TABLE OF sflight.
     
   the_sorting_algorithm.
     
   ASSERT ID        dany
          SUBKEY    'danysub1'
          FIELDS    l_f1 l_f2 l_t1
          CONDITION itab->is_sorted_by_name( ) <> ' '.                
ENDMETHOD.

This will ensure that the table is sorted. Below is the result of the log for this assert

You can now create (de)activable breakpoints in your programs. You can release these breakpoints in production and a customer will have the opportunity to activate and debug your code more easily.

The following is an activable break-point : BREAK-POINT ID dany.

The checkpoint group is defined by double clicking on the checkpoint group in the editor OR directly via transaction SAAB.

Below is the SAAB screen. In the breakpoints part of the screen, you can set it to "inactive" or "break". All breakpoint groups will be shipped inactive by default.

Assert :

An assertion is a condition which must be true during program execution. By using asserts in your program, you can find cause of error in shorter time. The reaction when violating an assertion depend on a customizing and could be :

  1. Start the debugger from this assert

  2. Do nothing, ignore the assert

  3. Log the assertion in a log

  4. Terminate the program with runtime error ASSERTION_FAILED

The assertions are defined in SAAB (exactly like the breakpoints, see screen above).Here is an example of a use for an assertion :

METHOD sort_by_name.
     
DATA: l_f1 TYPE i VALUE 2,
      l_f2 TYPE c LENGTH 10 VALUE 'test',
      l_t1 TYPE TABLE OF sflight.
     
   the_sorting_algorithm.
     
   ASSERT ID        dany
          SUBKEY    'danysub1'
          FIELDS    l_f1 l_f2 l_t1
          CONDITION itab->is_sorted_by_name( ) <> ' '.                
ENDMETHOD.

This will ensure that the table is sorted. Below is the result of the log for this assert

ABAP Keywords and their usage

What is a collect statement and how it is different from append ?
ANS:-
If an entry with the same key already exists, the COLLECT statement does not append a new line, but adds the contents of the numeric fields in the work area to the contents of the numeric fields in the existing entry.
Dependency Syntax: General Rules in SAP


Operators

Operators
Use in Dependencies

AND
Two statements that are both either true or not true are linked with AND.

Length = 300 and Width = 200

OR
Two statements of which at least one is either true or not true are linked with OR.

Color = ‘red’ or Basic_material = ‘wood’

NOT
You can negate one or more expressions by using NOT.

NOT (Color = ‘blue’)

NOT (Color = ‘red’ and Basic_material = ‘wood’)

IF
Conditions in actions and procedures start with IF.

Color = 'red' if Model = ‘A’



Special Features

Lists
In lists, the individual elements are always separated by commas.

COLOR = 'RED' IF MODEL = 'A',
COLOR = 'BLUE' IF MODEL = 'B',
COLOR = 'GREEN' IF MODEL = 'C',

Case sensitivity
In characteristic names, object variables, and operators, there is no distinction between upper case and lower case letters.


Concatenation

LC
All letters are converted to lower case.

Leather_saddle = LC('Alpha')

= 'a'

UC
All letters are converted to upper case.

Leather_saddle = U C('Alpha')

= 'A'

This function is important if the assigned characteristic does not allow lower case, but the assigned expression may contain lower-case letters.

||
The string is cut off at the maximum number of 30 characters.

Leather_saddle = Alpha || Beta

= 'AB'


List of Built-In Conditions

Expression
Implied Condition

SPECIFIED
Characteristic has a value:

SPECIFIED COLOR

See Built-In Condition SPECIFIED

IN
One of these values must be set:

COLOR IN (‘red’, ‘green’, ‘blue’)

See Built-In Condition IN

TYPE_OF
Only for certain objects:

TYPE_OF ($ROOT, (Material) (300) (NR = 'U91’))

See Built-In Condition TYPE_OF

PART_OF
The object is a component of a BOM

(only in constraints).

See Constraints: Entering Conditions

SUBPART_OF
The object is a component of an assembly that is part of the BOM of a configurable material

(only in constraints).







WRITE TO sap abap keyword syntax and description

Assigns strings.
Syntax
WRITE TO [].
Converts the contents of the data object to type C and assigns the resulting string to the
variable . You can use the same formatting options available in the WRITE statement.





WRITE sap abap keyword syntax and description

Creates list output.
Syntax
WRITE [AT [/][][()]] [AS CHECKBOX|SYMBOL|ICON|LINE]
[QUICKINFO ].
[]
The contents of the field are formatted according to their data type and displayed on the list.
The additions before the field allow you to specify a line break, the starting position, and the
length of the field. The additions after the field allow you to display checkboxes, symbols, icons,
and lines. The addition can contain various other formatting options. The QUICKINFO
addition allows you to assign a quickinfo to the field.





WINDOW sap abap keyword syntax and description

Displays a list as a modal dialog box.
Syntax
WINDOW STARTING AT [ENDING AT ].
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 and line . The bottom
right-hand corner is positioned at column and line (if specified).





WHILE sap abap keyword syntax and description

Introduces a loop.
Syntax
WHILE [VARY FROM NEXT ].
Introduces a statement block that is concluded with ENDWHILE. The statement block between
WHILE and ENDWHILE is repeated for as long as the expression is true, or until a
termination statement such as CHECK or EXIT occurs. The VARY addition allows you to process
fields that are a uniform distance apart within memory.





WHEN sap abap keyword syntax and description

Introduces a statement block in a CASE control structure
Syntax
WHEN [OR OR...] | OTHERS.
The statement block after a WHEN statement is executed if the contents of the field in the
CASE statement are the same as those of one of the fields
. Processing then resumes after the ENDCASE statement. The WHEN OTHERS statement
block is executed if the contents of do not correspond to any of the fields .





UPDATE sap abap keyword syntax and description

Modifies lines in database tables.
Syntax
UPDATE SET =
| = +
| = - [WHERE ].
Sets the value in to , increases it by , or decreases it by for all selected lines. The
WHERE addition determines the lines that are updated. If you omit the WHERE addition, all lines
are updated.
Syntax
UPDATE FROM .
UPDATE FROM TABLE .
Overwrites the line with the same primary key as with the contents of , or all lines with
the same primary key as a line in the internal table with the corresponding line of itab. The
work area or the lines of the table must have at least the same length and the same
alignment as the line structure of the database table.





UNPACK sap abap keyword syntax and description

Converts variables from type P to type C.
Syntax
UNPACK TO .
Unpacks the packed field and places it in the string with leading zeros. The opposite of
PACK.





ULINE sap abap keyword syntax and description

Places a horizontal line on the output list.
Syntax
ULINE [AT [/][][()]].
Without additions, generates a new line on the current list and fills it with a horizontal line. The
additions allow you to insert a line break and specify the starting position and length of the line.





TYPES for Aggregate Types sap abap keyword syntax and description

Defines aggregated types.
Syntax
TYPES: BEGIN OF ,
...
...,
...
END OF .
Combines the data types to form the structure . You can address the individual
components of a structure in a program using a hyphen between the structure name and the
component name as follows: -.
Syntax
TYPES TYPE|LIKE OF [WITH ].
Defines the local data type in the program as an internal table with the access type
, the line type , and the key





TYPES for Simple Field Types sap abap keyword syntax and description

Defines a simple field type.
Syntax
TYPES [()] [TYPE |LIKE ] [DECIMALS ].
Defines the internal data type in the program with length , reference to the ABAP
Dictionary type or a data object , and, where appropriate, with decimal
places.
Syntax
TYPES TYPE REF TO |.
Defines the internal data type in the program with reference to the class or the
interface .





TYPE-POOLS sap abap keyword syntax and description

Declares the types and constants of a type group to a program.
Syntax
TYPE-POOLS .
After this statement, you can use all of the data types and constants defined in the type group
in your program.





TYPE-POOL sap abap keyword syntax and description

Introduces a type group.
Syntax
TYPE-POOL .
The first statement in a type group. You do not have to enter this statement in the ABAP Editor -
instead, it is automatically inserted in the type group by the ABAP Dictionary. A type group is an
ABAP program containing type definitions and constant declarations that can then be used in
several different programs.





TRANSLATE sap abap keyword syntax and description

Converts characters in strings.
Syntax
TRANSLATE TO UPPER|LOWER CASE
|USING .
The characters of the string are converted into upper- or lowercase, or according to a
substitution rule specified in .





TRANSFER

Writes data to a file.
Syntax
TRANSFER TO [LENGTH ].
Writes the field to the file on the application server. The LENGTH addition specifies
the length of the data you want to transfer





TOP-OF-PAGE sap abap keyword syntax and description

Event keyword for defining an event block for a list event.
Syntax
TOP-OF-PAGE [DURING LINE-SELECTION].
Whenever a new page begins while a standard list is being created, the runtime environment
triggers the TOP-OF-PAGE event and the corresponding event block is executed. The addition
DURING LINE-SELECTION has the same function, but for detail lists.





TABLES

Declares an interface work area.
Syntax
TABLES .
Declares a structure with the same data type and name as a database table, a view, or a
structure from the ABAP Dictionary. Structures declared using TABLES in main programs and
subroutines use a common data area.





SUPPRESS DIALOG sap abap keyword syntax and description

Prevents the current screen from being displayed.
Syntax
SUPPRESS DIALOG.
Can only occur in a PBO dialog module. The screen is not displayed, but its flow logic is still
processed.





SUPPLY sap abap keyword syntax and description

Fills context instances with values.
Syntax
SUPPLY = ... = TO CONTEXT .
Fills the key fields of the context instance with the values .
SUPPRESS

Starting the debugger in a modal screen Using ABAP

Usually in ABAP, when you want to start the debugger from a certain point, you just have to write "/H" in the

command window. But if you are in a modal screen or in a message display, you cannot write the traditional

"/H", here is how to do it :

  1. Open notepad and paste these lines in a document : [FUNCTION] Command=/H Title=Debugger Type=SystemCommand

  2. Save this document anywhere on your local pc. ex: c:\breakpoint.txt

  3. Drag&drop this file from the explorer to your ABAP modal screen.... et voila !!


Usually in ABAP, when you want to start the debugger from a certain point, you just have to write "/H" in the

command window. But if you are in a modal screen or in a message display, you cannot write the traditional

"/H", here is how to do it :

  1. Open notepad and paste these lines in a document : [FUNCTION] Command=/H Title=Debugger Type=SystemCommand

  2. Save this document anywhere on your local pc. ex: c:\breakpoint.txt

  3. Drag&drop this file from the explorer to your ABAP modal screen.... et voila !!

Retrieving field names dynamically using sap abap

Sometimes you may have only a table name and want to retrieve the name of each field of the corresponding table. For example, when you want to use ASSIGN COMPONENT fieldname OF TABLE table.

An ABAPer's first reaction is to read the standard ABAP basis tables DD02L, DD03L, etc

This way of reading fields is very slow. Use methods from the class CL_ABAP_TYPEDESCR instead.

Example:

data: descr_struc_ref TYPE REF TO cl_abap_structdescr.

descr_struc_ref ?= cl_abap_typedescr=>describe_by_name('SFLIGHT' ).

Here is the result of descr_struct_ref after the execution of this piece of code

ABSOLUTE_NAME C 200 \TYPE=SFLIGHT

TYPE_KIND C 1 u

LENGTH I 4 80

DECIMALS I 4 0

KIND C 1 S

STRUCT_KIND C 1 F

COMPONENTS h 8 Table[14x40]

HAS_INCLUDE C 1

The table COMPONENTS is filled with :

LENGTH DECIMALS TYPE_KIND NAME

3 | 0 |C |MANDT

3 | 0 |C |CARRID

4 | 0 |N |CONNID

8 | 0 |D |FLDATE

etc.

You have the fields name and a lot more information about the table. This class can also handle structure, table type, etc.

Note that this method is very fast because it uses the database layer directly thanks to SYSTEM CALLs.

To have a look at the class, use transaction SE24.

Sometimes you may have only a table name and want to retrieve the name of each field of the corresponding table. For example, when you want to use ASSIGN COMPONENT fieldname OF TABLE table.

An ABAPer's first reaction is to read the standard ABAP basis tables DD02L, DD03L, etc

This way of reading fields is very slow. Use methods from the class CL_ABAP_TYPEDESCR instead.

Example:

data: descr_struc_ref TYPE REF TO cl_abap_structdescr.

descr_struc_ref ?= cl_abap_typedescr=>describe_by_name('SFLIGHT' ).

Here is the result of descr_struct_ref after the execution of this piece of code

ABSOLUTE_NAME C 200 \TYPE=SFLIGHT

TYPE_KIND C 1 u

LENGTH I 4 80

DECIMALS I 4 0

KIND C 1 S

STRUCT_KIND C 1 F

COMPONENTS h 8 Table[14x40]

HAS_INCLUDE C 1

The table COMPONENTS is filled with :

LENGTH DECIMALS TYPE_KIND NAME

3 | 0 |C |MANDT

3 | 0 |C |CARRID

4 | 0 |N |CONNID

8 | 0 |D |FLDATE

etc.

You have the fields name and a lot more information about the table. This class can also handle structure, table type, etc.

Note that this method is very fast because it uses the database layer directly thanks to SYSTEM CALLs.

To have a look at the class, use transaction SE24.

Restricting the selection screen using sap abap

When you create a select-option for an input to your program, for each field, the default selection screen looks like this:

And the default possible selections are:

but sometime you don't want to give the user the possibility to select a range, select values "greater than", etc.
     
Here is a small example on how to do it:
     
REPORT ZDANY_RESTRICT_SELECTION.
     
* Include type pool SSCR
    TYPE-POOLS sscr.
    TABLES : sflight.
     
* defining the selection-screen
    select-options :
        s_carrid for sflight-carrid,
        s_connid for sflight-connid.
     
* Define the object to be passed to the RESTRICTION parameter
    DATA restrict TYPE sscr_restrict.
     
* Auxiliary objects for filling RESTRICT
    DATA :     optlist TYPE sscr_opt_list,
                    ass type sscr_ass.
     
    INITIALIZATION.
* Restricting the carrid selection to only EQ and 'BT'.
    optlist-name = 'OBJECTKEY1'.
    optlist-options-eq = 'X'.
    optlist-options-bt = 'X'.
    APPEND optlist TO restrict-opt_list_tab.
     
    ass-kind = 'S'.
    ass-name = 'S_carrid'.
    ass-sg_main = 'I'.
    ass-sg_addy = space.
    ass-op_main = 'OBJECTKEY1'.
    APPEND ass TO restrict-ass_tab.
     
* Restricting the connid selection to CP, GE, LT, NE.
    optlist-name = 'OBJECTKEY2'.
    optlist-options-cp = 'X'.
    optlist-options-ge = 'X'.
    optlist-options-lt = 'X'.
    optlist-options-ne = 'X'.
    APPEND optlist TO restrict-opt_list_tab.
     
    ass-kind = 'S'.
    ass-name = 'S_connid'.
    ass-sg_main = 'I'.
    ass-sg_addy = space.
    ass-op_main = 'OBJECTKEY2'.
    APPEND ass TO restrict-ass_tab.
     
    CALL FUNCTION 'SELECT_OPTIONS_RESTRICT'
        EXPORTING
            restriction = restrict
        EXCEPTIONS
            TOO_LATE = 1
            REPEATED = 2
            SELOPT_WITHOUT_OPTIONS = 3
            SELOPT_WITHOUT_SIGNS = 4
            INVALID_SIGN = 5
            EMPTY_OPTION_LIST = 6
            INVALID_KIND = 7
            REPEATED_KIND_A = 8
            OTHERS = 9.
     
    IF sy-subrc <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
        WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
     
when you execute this piece of code, you will notice that for carrid, the selection screen is now restricted :


When you create a select-option for an input to your program, for each field, the default selection screen looks like this:

And the default possible selections are:

but sometime you don't want to give the user the possibility to select a range, select values "greater than", etc.
     
Here is a small example on how to do it:
     
REPORT ZDANY_RESTRICT_SELECTION.
     
* Include type pool SSCR
    TYPE-POOLS sscr.
    TABLES : sflight.
     
* defining the selection-screen
    select-options :
        s_carrid for sflight-carrid,
        s_connid for sflight-connid.
     
* Define the object to be passed to the RESTRICTION parameter
    DATA restrict TYPE sscr_restrict.
     
* Auxiliary objects for filling RESTRICT
    DATA :     optlist TYPE sscr_opt_list,
                    ass type sscr_ass.
     
    INITIALIZATION.
* Restricting the carrid selection to only EQ and 'BT'.
    optlist-name = 'OBJECTKEY1'.
    optlist-options-eq = 'X'.
    optlist-options-bt = 'X'.
    APPEND optlist TO restrict-opt_list_tab.
     
    ass-kind = 'S'.
    ass-name = 'S_carrid'.
    ass-sg_main = 'I'.
    ass-sg_addy = space.
    ass-op_main = 'OBJECTKEY1'.
    APPEND ass TO restrict-ass_tab.
     
* Restricting the connid selection to CP, GE, LT, NE.
    optlist-name = 'OBJECTKEY2'.
    optlist-options-cp = 'X'.
    optlist-options-ge = 'X'.
    optlist-options-lt = 'X'.
    optlist-options-ne = 'X'.
    APPEND optlist TO restrict-opt_list_tab.
     
    ass-kind = 'S'.
    ass-name = 'S_connid'.
    ass-sg_main = 'I'.
    ass-sg_addy = space.
    ass-op_main = 'OBJECTKEY2'.
    APPEND ass TO restrict-ass_tab.
     
    CALL FUNCTION 'SELECT_OPTIONS_RESTRICT'
        EXPORTING
            restriction = restrict
        EXCEPTIONS
            TOO_LATE = 1
            REPEATED = 2
            SELOPT_WITHOUT_OPTIONS = 3
            SELOPT_WITHOUT_SIGNS = 4
            INVALID_SIGN = 5
            EMPTY_OPTION_LIST = 6
            INVALID_KIND = 7
            REPEATED_KIND_A = 8
            OTHERS = 9.
     
    IF sy-subrc <> 0.
        MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
        WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
     
when you execute this piece of code, you will notice that for carrid, the selection screen is now restricted :

Calling an external program using sap abap

You want to call a program on your PC from an ABAP program ? try this function :
     *This example calls the dos prompt DATA:
     i_returncode TYPE i.
         
CALL FUNCTION 'GUI_EXEC'
     EXPORTING
     command = 'CMD' <<==-- CMD calls the DOS prompt but you can put any program here
     * PARAMETER = 'test'
     IMPORTING
      returncode = i_returncode.
     there is a lot of other functions to communicate with the PC like:
     GUI_CREATE_DIRECTORY GUI_DELETE_FILE GUI_DOWNLOAD
     GUI_EXEC
     GUI_FILE_SAVE_DIALOG
     GUI_GET_DESKTOP_INFO
     GUI_GET_FILE_INFO
     etc...

You want to call a program on your PC from an ABAP program ? try this function :
     *This example calls the dos prompt DATA:
     i_returncode TYPE i.
      CALL FUNCTION 'GUI_EXEC'
        EXPORTING
       command = 'CMD' <<==-- CMD calls the DOS prompt but you can put any program here
       * PARAMETER = 'test'
        IMPORTING
           returncode = i_returncode.
     there is a lot of other functions to communicate with the PC like:
      GUI_CREATE_DIRECTORY GUI_DELETE_FILE GUI_DOWNLOAD
     GUI_EXEC
     GUI_FILE_SAVE_DIALOG
     GUI_GET_DESKTOP_INFO
     GUI_GET_FILE_INFO
     etc...

Using a variable from a calling program without passing it in parameter using abap

Did you ever try to use a variable from another program without passing this variable as a parameter. This is very useful when you CANNOT add the field as a standard parameter. For example, when you want to use a variable in a BADI which is not already passed as a parameter. Another good example is when you create a correction in a function and you want to keep the installation of the OSS note automatic (if you add parameters in a note, the user will have to install the note manually).

Here is a short example on how to do this :

REPORT zdany_test_var_from_fm.

TABLES: spfli.

DATA dbcnt TYPE sy-dbcnt.

DATA: itab TYPE spfli_tab.

SELECT * FROM spfli INTO TABLE itab UP TO 2 ROWS.

dbcnt = sy-dbcnt.

CALL FUNCTION 'ZFUNCTION'.

FUNCTION zfunction.

* We want to use the DBCNT from the program ZDANY_TEST_VAR_FROM_FM

DATA: field(50).

FIELD-SYMBOLS: .

field = '(ZDANY_TEST_VAR_FROM_FM)dbcnt'.

ASSIGN (field) TO .

WRITE .

* We want to use the internal table from the program ZDANY_TEST_VAR_FROM_FM

DATA: itab TYPE spfli.

FIELD-SYMBOLS: TYPE spfli_tab.

field = '(ZDANY_TEST_VAR_FROM_FM)ITAB[]'.

ASSIGN (field) TO .

LOOP AT INTO itab.

WRITE: / itab-carrid, itab-connid.

ENDLOOP.

ENDFUNCTION


Did you ever try to use a variable from another program without passing this variable as a parameter. This is very useful when you CANNOT add the field as a standard parameter. For example, when you want to use a variable in a BADI which is not already passed as a parameter. Another good example is when you create a correction in a function and you want to keep the installation of the OSS note automatic (if you add parameters in a note, the user will have to install the note manually).

Here is a short example on how to do this :

REPORT zdany_test_var_from_fm.

TABLES: spfli.

DATA dbcnt TYPE sy-dbcnt.

DATA: itab TYPE spfli_tab.

SELECT * FROM spfli INTO TABLE itab UP TO 2 ROWS.

dbcnt = sy-dbcnt.

CALL FUNCTION 'ZFUNCTION'.

FUNCTION zfunction.

* We want to use the DBCNT from the program ZDANY_TEST_VAR_FROM_FM

DATA: field(50).

FIELD-SYMBOLS: .

field = '(ZDANY_TEST_VAR_FROM_FM)dbcnt'.

ASSIGN (field) TO .

WRITE .

* We want to use the internal table from the program ZDANY_TEST_VAR_FROM_FM

DATA: itab TYPE spfli.

FIELD-SYMBOLS: TYPE spfli_tab.

field = '(ZDANY_TEST_VAR_FROM_FM)ITAB[]'.

ASSIGN (field) TO .

LOOP AT INTO itab.

WRITE: / itab-carrid, itab-connid.

ENDLOOP.

ENDFUNCTION

Showing a progress bar in ABAP

This process is very easy but a lot of programmers don't know how to do it. You just have to call the ABAP FM SAPGUI_PROGRESS_INDICATOR, at the appropriate points.

Below is a simple example, give it a try !!

REPORT zdany_progress_bar.
DATA: percentage_text TYPE c LENGTH 5.
DO 100 TIMES.
     
    WAIT UP TO '0.5' SECONDS.
    percentage_text(3) = sy-index.
    percentage_text+3 = '%'.
     
     
    CALL FUNCTION 'SAPGUI_PROGRESS_INDICATOR'
    EXPORTING
     
        percentage = sy-index
        text = percentage_text.
     
     
ENDDO.

This process is very easy but a lot of programmers don't know how to do it. You just have to call the ABAP FM SAPGUI_PROGRESS_INDICATOR, at the appropriate points.

Below is a simple example, give it a try !!

REPORT zdany_progress_bar.
DATA: percentage_text TYPE c LENGTH 5.
DO 100 TIMES.
     
    WAIT UP TO '0.5' SECONDS.
    percentage_text(3) = sy-index.
    percentage_text+3 = '%'.
     
     
    CALL FUNCTION 'SAPGUI_PROGRESS_INDICATOR'
    EXPORTING
     
        percentage = sy-index
        text = percentage_text.
     
     
ENDDO.

Generating your own standard F4 help using sap abap

To avoid the standard F4 help to be show, insert the event PROCESS ON-VALUE-REQUEST request in the program and add a field statement for the field that should trigger the F4 help. In the module called from PROCESS ON-VALUE-REQUEST request, call function module F4IF_FIELD_VALUE_REQUEST.

Example:

process before output.

.....

process after input.

.....

PROCESS ON VALUE-REQUEST. FIELD sflight-carrid MODULE f4_help_for_carrid.

MODULE f4_help_for_carrid INPUT.

* NOTE:

* Tabname/fieldname is the name of the table and field

* for which F4 should be shown.

*

* Dynprog/Dynpnr/Dynprofield are the names of the Progran/Dynpro/Field

* in which the f4 value should be returned.

*

* Value: The value of the Dynpro field when calling the F4 help.

* You can limit the values shown, by inseting a value in this parameter

* e.g 'A*' to show only values beginning with A

CALL FUNCTION 'F4IF_FIELD_VALUE_REQUEST'
    EXPORTING
        tabname     = 'SFLIGHT'
        fieldname   = 'CARRID'
*        SEARCHHELP  = ' '
*        SHLPPARAM   = ' '
        dynpprog    = 'ZDANY_F4_OWN_CALL'
        dynpnr      = '0100'
        dynprofield = 'SFLIGHT-CARRID'
*        STEPL       = 0
        value       = 'A*'
*        MULTIPLE_CHOICE     = ' '
*        DISPLAY             = ' '
*        SUPPRESS_RECORDLIST = ' '
*        CALLBACK_PROGRAM    = ' '
*        CALLBACK_FORM       = ' '
*    TABLES
*        RETURN_TAB =
*    EXCEPTIONS
*        FIELD_NOT_FOUND   = 1
*        NO_HELP_FOR_FIELD = 2
*        INCONSISTENT_HELP = 3
*        NO_VALUES_FOUND   = 4
*        OTHERS            = 5
.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
     
ENDMODULE. " F4_help_for_carrid INPUT

To control F4 help in a selection screen use the AT SELECTION-SCREEN ON VALUE-REQUEST FOR

event.

Note that for ranges both the low and high value of the field must have there own ON VALUE-REQUEST

Example:

AT SELECTION-SCREEN ON VALUE-REQUEST FOR s_prctr-low.

PERFORM f4_help_carrid.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR s_prctr-high.

PERFORM f4_help_carrid.

To avoid the standard F4 help to be show, insert the event PROCESS ON-VALUE-REQUEST request in the program and add a field statement for the field that should trigger the F4 help. In the module called from PROCESS ON-VALUE-REQUEST request, call function module F4IF_FIELD_VALUE_REQUEST.

Example:

process before output.

.....

process after input.

.....

PROCESS ON VALUE-REQUEST. FIELD sflight-carrid MODULE f4_help_for_carrid.

MODULE f4_help_for_carrid INPUT.

* NOTE:

* Tabname/fieldname is the name of the table and field

* for which F4 should be shown.

*

* Dynprog/Dynpnr/Dynprofield are the names of the Progran/Dynpro/Field

* in which the f4 value should be returned.

*

* Value: The value of the Dynpro field when calling the F4 help.

* You can limit the values shown, by inseting a value in this parameter

* e.g 'A*' to show only values beginning with A

CALL FUNCTION 'F4IF_FIELD_VALUE_REQUEST'
    EXPORTING
        tabname     = 'SFLIGHT'
        fieldname   = 'CARRID'
*        SEARCHHELP  = ' '
*        SHLPPARAM   = ' '
        dynpprog    = 'ZDANY_F4_OWN_CALL'
        dynpnr      = '0100'
        dynprofield = 'SFLIGHT-CARRID'
*        STEPL       = 0
        value       = 'A*'
*        MULTIPLE_CHOICE     = ' '
*        DISPLAY             = ' '
*        SUPPRESS_RECORDLIST = ' '
*        CALLBACK_PROGRAM    = ' '
*        CALLBACK_FORM       = ' '
*    TABLES
*        RETURN_TAB =
*    EXCEPTIONS
*        FIELD_NOT_FOUND   = 1
*        NO_HELP_FOR_FIELD = 2
*        INCONSISTENT_HELP = 3
*        NO_VALUES_FOUND   = 4
*        OTHERS            = 5
.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
     
ENDMODULE. " F4_help_for_carrid INPUT

To control F4 help in a selection screen use the AT SELECTION-SCREEN ON VALUE-REQUEST FOR

event.

Note that for ranges both the low and high value of the field must have there own ON VALUE-REQUEST

Example:

AT SELECTION-SCREEN ON VALUE-REQUEST FOR s_prctr-low.

PERFORM f4_help_carrid.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR s_prctr-high.

PERFORM f4_help_carrid.

Manipulating Timestamps using abap

Actually, we should use time stamp in our abap programs instead of the traditional date and time fields.

When we have to do some calculation on a time stamp is not as easy as on a date field.

For example, to add an hour to a timestamp, many people will:

  1. convert the time stamp into a standard date and field

  2. add an hour

  3. convert back the date and time to a timestamp

However, it is the slowest method you can use.

Instead, use class CL_ABAP_TSTMP.

It enables you to make whatever calculation you want on a time stamp.

In the following example, 1 hour is added

REPORT zdany_tstamp.
DATA : l_tstamp         TYPE timestamp,
       l_tstamp_out TYPE timestamp.
     
 GET TIME STAMP FIELD l_tstamp.
TRY.
  CALL METHOD cl_abap_tstmp=>add
     EXPORTING
        tstmp = l_tstamp
        secs = 3600 <<<===--- 1 hour = 3600 seconds
     RECEIVING
                r_tstmp = l_tstamp_out.
  CATCH cx_parameter_invalid_range .
                WRITE 'invalid range'.
                EXIT.
  CATCH cx_parameter_invalid_type .
                WRITE 'invalid type'.
                EXIT.
ENDTRY.
     
WRITE l_tstamp time zone 'UTC '.
SKIP.
WRITE l_tstamp_out time zone 'UTC '.

Actually, we should use time stamp in our abap programs instead of the traditional date and time fields.

When we have to do some calculation on a time stamp is not as easy as on a date field.

For example, to add an hour to a timestamp, many people will:

  1. convert the time stamp into a standard date and field

  2. add an hour

  3. convert back the date and time to a timestamp

However, it is the slowest method you can use.

Instead, use class CL_ABAP_TSTMP.

It enables you to make whatever calculation you want on a time stamp.

In the following example, 1 hour is added

REPORT zdany_tstamp.
DATA : l_tstamp         TYPE timestamp,
       l_tstamp_out TYPE timestamp.
     
 GET TIME STAMP FIELD l_tstamp.
TRY.
  CALL METHOD cl_abap_tstmp=>add
     EXPORTING
        tstmp = l_tstamp
        secs = 3600 <<<===--- 1 hour = 3600 seconds
     RECEIVING
                r_tstmp = l_tstamp_out.
  CATCH cx_parameter_invalid_range .
                WRITE 'invalid range'.
                EXIT.
  CATCH cx_parameter_invalid_type .
                WRITE 'invalid type'.
                EXIT.
ENDTRY.
     
WRITE l_tstamp time zone 'UTC '.
SKIP.
WRITE l_tstamp_out time zone 'UTC '.

Creating an ALV Grid in 3 lines using sap abap

Did you know that you can create an ALV Grid very fast; you don't need to define a layout, a fieldcatalog, a container and all the other small things we usually define in an ALV Grid. If we don't need to finetune the ALV Grid and just want to display a list on the screen or to the printer, here is a very simple way to proceed:

DATA: l_alv      TYPE REF TO   cl_gui_alv_grid,
      lt_sflight TYPE TABLE OF sflight.
     
SELECT * FROM sflight INTO TABLE lt_sflight.
     
* Creation of the ALV object, when we use cl_gui_container=>screen0 as parent, the ALVGrid control will
* automatically use the full screen to display the grid, NO CONTAINER DEFINITION IS REQUIRED !
CREATE OBJECT l_alv EXPORTING i_parent = cl_gui_container=>screen0.
     
* calling the display of the grid, the system will automatically create the fieldcatalog based
* on the table name you pass in parameter
CALL METHOD l_alv->set_table_for_first_display
     EXPORTING i_structure_name = 'SFLIGHT'
     CHANGING  it_outtab        = lt_sflight.
     
* You have to create an EMPTY screen, put NOTHING in the layout and this is going to work
CALL SCREEN 100

Instead of creating an empty screen 100, you can also define an empty selection screen in you program and use it, no more screen painter required !

SELECTION-SCREEN BEGIN OF SCREEN 1001.

SELECTION-SCREEN END OF SCREEN 1001.

CALL SELECTION-SCREEN 1001.

Did you know that you can create an ALV Grid very fast; you don't need to define a layout, a fieldcatalog, a container and all the other small things we usually define in an ALV Grid. If we don't need to finetune the ALV Grid and just want to display a list on the screen or to the printer, here is a very simple way to proceed:

DATA: l_alv      TYPE REF TO   cl_gui_alv_grid,
      lt_sflight TYPE TABLE OF sflight.
     
SELECT * FROM sflight INTO TABLE lt_sflight.
     
* Creation of the ALV object, when we use cl_gui_container=>screen0 as parent, the ALVGrid control will
* automatically use the full screen to display the grid, NO CONTAINER DEFINITION IS REQUIRED !
CREATE OBJECT l_alv EXPORTING i_parent = cl_gui_container=>screen0.
     
* calling the display of the grid, the system will automatically create the fieldcatalog based
* on the table name you pass in parameter
CALL METHOD l_alv->set_table_for_first_display
     EXPORTING i_structure_name = 'SFLIGHT'
     CHANGING  it_outtab        = lt_sflight.
     
* You have to create an EMPTY screen, put NOTHING in the layout and this is going to work
CALL SCREEN 100

Instead of creating an empty screen 100, you can also define an empty selection screen in you program and use it, no more screen painter required !

SELECTION-SCREEN BEGIN OF SCREEN 1001.

SELECTION-SCREEN END OF SCREEN 1001.

CALL SELECTION-SCREEN 1001.

Modifying the F4 standard calendar using sap abap

When you press F4 on any date field the standard calendar opens in order for you to choose a date. When you do not want the user to choose a weekend day or a holiday, you can do it.

Two different type of calendars are defined in SAP, the holiday calendar and the factory calendar.

These calendars are defined in the customizing under :

SPRO -> General settings -> maintain calendar

in this screen, all the default holidays are predefined by country, you can add or delete holiday as you want. I tried to create the Dany's day in ISP but I'm stuck on a small access problem... stupid security !

Because a holiday can be different by country, the factory calendar is stored for each plants, in table T001W, field FABKL.

here is a small example on how to call the calendar :

CALL FUNCTION 'F4_DATE'
   EXPORTING
     date_for_first_month = '20031208'
holiday_calendar_id = 'CA'           "<<==-- Here is how you point on a holiday calendar
*     factory_calendar_id = T001W-FABKL    "<<==-- ... or a factory one
     display = ' '
   IMPORTING
     select_date = select_date
   EXCEPTIONS
     OTHERS = 4.

Here is an example of the result, a red square marks each holiday.

When you press F4 on any date field the standard calendar opens in order for you to choose a date. When you do not want the user to choose a weekend day or a holiday, you can do it.

Two different type of calendars are defined in SAP, the holiday calendar and the factory calendar.

These calendars are defined in the customizing under :

SPRO -> General settings -> maintain calendar

in this screen, all the default holidays are predefined by country, you can add or delete holiday as you want. I tried to create the Dany's day in ISP but I'm stuck on a small access problem... stupid security !

Because a holiday can be different by country, the factory calendar is stored for each plants, in table T001W, field FABKL.

here is a small example on how to call the calendar :

CALL FUNCTION 'F4_DATE'
   EXPORTING
     date_for_first_month = '20031208'
holiday_calendar_id = 'CA'           "<<==-- Here is how you point on a holiday calendar
*     factory_calendar_id = T001W-FABKL    "<<==-- ... or a factory one
     display = ' '
   IMPORTING
     select_date = select_date
   EXCEPTIONS
     OTHERS = 4.

Here is an example of the result, a red square marks each holiday.

Saving an internal table in Microsoft Excel format using sap abap

While you are debugging your program, you can save the content of an internal table.

  1. Display the content of the internal table in the debugger.

  2. Then press ctrl-F11 or right-mouse and click "Save As Excel Worksheet".

  3. Enter the From-index and To-index for the lines you want to save.

  4. Choose folder/filename and save

While you are debugging your program, you can save the content of an internal table.

  1. Display the content of the internal table in the debugger.

  2. Then press ctrl-F11 or right-mouse and click "Save As Excel Worksheet".

  3. Enter the From-index and To-index for the lines you want to save.

  4. Choose folder/filename and save

Generating a number range automatically in sap

If you need a unique key in a table or a sequential number for any other purpose, you can use a range object .

Ranges are maintained in transaction SNRO

After maintaining the first screen you have to maintain the intervals by clicking the button "number ranges"

These informations are stored in tables :

- TNRO Definition of number range objects

- NRIV Number range intervals. Note: Field NRLEVEL Contains the last assigned number.

In you program you read the next number by using the function NUMBER_GET_NEXT

DATA l_number TYPE i.
CALL FUNCTION 'NUMBER_GET_NEXT'
    EXPORTING
        nr_range_nr = '01'
        object = 'ZTEST'
        quantity = '1'
    IMPORTING
        number = l_number
*       quantity = ' '
*       RETURNCODE =
    EXCEPTIONS
        interval_not_found = 1
        number_range_not_intern = 2
        object_not_found = 3
        quantity_is_0 = 4
        quantity_is_not_1 = 5
        interval_overflow = 6
        OTHERS = 7.

display l_number.

each time you call NUMBER_GET_RANGE the number is automatically increased.

You can also create the number range in your program instead of using SNRO with the functions:

NUMBER_RANGE_INTERVAL_LIST : verify if a number range already exist

NUMBER_RANGE_ENQUEUE : lock the specifier number range

NUMBER_RANGE_INTERVAL_UPDATE : create the number range

NUMBER_RANGE_UPDATE_CLOSE : commit changes NUMBER_RANGE_DEQUEUE : unlock

If you need a unique key in a table or a sequential number for any other purpose, you can use a range object .

Ranges are maintained in transaction SNRO

After maintaining the first screen you have to maintain the intervals by clicking the button "number ranges"

These informations are stored in tables :

- TNRO Definition of number range objects

- NRIV Number range intervals. Note: Field NRLEVEL Contains the last assigned number.

In you program you read the next number by using the function NUMBER_GET_NEXT

DATA l_number TYPE i.
CALL FUNCTION 'NUMBER_GET_NEXT'
    EXPORTING
        nr_range_nr = '01'
        object = 'ZTEST'
        quantity = '1'
    IMPORTING
        number = l_number
*       quantity = ' '
*       RETURNCODE =
    EXCEPTIONS
        interval_not_found = 1
        number_range_not_intern = 2
        object_not_found = 3
        quantity_is_0 = 4
        quantity_is_not_1 = 5
        interval_overflow = 6
        OTHERS = 7.

display l_number.

each time you call NUMBER_GET_RANGE the number is automatically increased.

You can also create the number range in your program instead of using SNRO with the functions:

NUMBER_RANGE_INTERVAL_LIST : verify if a number range already exist

NUMBER_RANGE_ENQUEUE : lock the specifier number range

NUMBER_RANGE_INTERVAL_UPDATE : create the number range

NUMBER_RANGE_UPDATE_CLOSE : commit changes NUMBER_RANGE_DEQUEUE : unlock

Defining a local type dynamically using abap

You can now define a local type dynamically.

This is only supported in 6.40. Here's how it goes:

REPORT ZDANY_DYN_LOCAL_TYPES.

****************** hardcoded "old style" local type *******************
* This is a normal hardcoded local type
 types : begin of typ_hardcoded,
         l_count type i,
         lt_sflight type sflight.
 types : end of typ_hardcoded.
* create a table based on hardcoded type
 data : lt_hardcoded type table of typ_hardcoded.
     
****************** dynamic "new wave" local type *******************
 types: typ_count type i.
     
 field-symbols :  type any table.
 data: dref type ref to data,
       itab_type type ref to cl_abap_tabledescr,
       struct_type type ref to cl_abap_structdescr,
       elem_type type ref to cl_abap_elemdescr,
       comp_tab type cl_abap_structdescr=>component_table,
       comp_fld type cl_abap_structdescr=>component.

* We read information about each fields of SFLIGHT (see ABAP FAQ #2)

struct_type ?= cl_abap_typedescr=>describe_by_name( 'SFLIGHT' ).

* We also need the information about the type "typ_count", note that

* we should use class cl_abap_elemdescr instead of cl_abap_typedescr

elem_type ?= cl_abap_elemdescr=>describe_by_name( 'TYP_COUNT' ).

* we read all fleids of SFLIGHT and create a component table

comp_tab = struct_type->get_components( ).

* We add manually the counter

comp_fld-name = 'L_COUNT'.

comp_fld-type = elem_type.

insert comp_fld into comp_tab index 1.

* we create the structure

struct_type = cl_abap_structdescr=>create( comp_tab ).

* ... and the internal table

itab_type = cl_abap_tabledescr=>create( struct_type ).

* The new thing here is the "type handle" which create a pointer to a

* handle

create data dref type handle itab_type.

* we finally assign a field symbol to the pointer because we cannot

* directly access a pointer.

assign dref->* to .

* At the end of this small program, internal table lt_hardcoded and

* lt_dynamic are the same

break-point.

You can now define a local type dynamically.

This is only supported in 6.40. Here's how it goes:

REPORT ZDANY_DYN_LOCAL_TYPES.

****************** hardcoded "old style" local type *******************
* This is a normal hardcoded local type
 types : begin of typ_hardcoded,
         l_count type i,
         lt_sflight type sflight.
 types : end of typ_hardcoded.
* create a table based on hardcoded type
 data : lt_hardcoded type table of typ_hardcoded.
     
****************** dynamic "new wave" local type *******************
 types: typ_count type i.
     
 field-symbols :  type any table.
 data: dref type ref to data,
       itab_type type ref to cl_abap_tabledescr,
       struct_type type ref to cl_abap_structdescr,
       elem_type type ref to cl_abap_elemdescr,
       comp_tab type cl_abap_structdescr=>component_table,
       comp_fld type cl_abap_structdescr=>component.

* We read information about each fields of SFLIGHT (see ABAP FAQ #2)

struct_type ?= cl_abap_typedescr=>describe_by_name( 'SFLIGHT' ).

* We also need the information about the type "typ_count", note that

* we should use class cl_abap_elemdescr instead of cl_abap_typedescr

elem_type ?= cl_abap_elemdescr=>describe_by_name( 'TYP_COUNT' ).

* we read all fleids of SFLIGHT and create a component table

comp_tab = struct_type->get_components( ).

* We add manually the counter

comp_fld-name = 'L_COUNT'.

comp_fld-type = elem_type.

insert comp_fld into comp_tab index 1.

* we create the structure

struct_type = cl_abap_structdescr=>create( comp_tab ).

* ... and the internal table

itab_type = cl_abap_tabledescr=>create( struct_type ).

* The new thing here is the "type handle" which create a pointer to a

* handle

create data dref type handle itab_type.

* we finally assign a field symbol to the pointer because we cannot

* directly access a pointer.

assign dref->* to .

* At the end of this small program, internal table lt_hardcoded and

* lt_dynamic are the same

break-point.

How to use macros in sap

First : DO NOT use macros in a new program, there is a lot of better way to do it.

Some people come to my desk and tell me they found a "magic" function which the code behind is invisible and it's impossible to trace this function. In some old programs, you can see a strange call to what it look like a function but it's not, it's a macro.

The macros are stored in table TRMAC.

One of the most used macros is "break". To put a break-point in your code that will break only for your user name, you probably use "break my_user_name". This is not part of the ABAP language despite what a lot of people think; it's a macro. If you have a look in table TRMAC, you will see :

BREAK 000 * USER specific BREAK-POINT

BREAK 001 if sy-uname = '&1'

BREAK 002 break-point

BREAK 003 endif

Here is how to create a simple macro, for the sake of understanding what old programs do. Again, do not

create new macros unless you absolutely must.

REPORT zdany_macro.

*Macro definition
DEFINE ZMULTIPLY.
  MULTIPLY &1 BY &2.
END-OF-DEFINITION.
     
DATA: number1 TYPE i VALUE 2,
      number2 TYPE i VALUE 5.
     
* calling the macro, no easy way of knowing this is a macro
ZMULTIPLY number1 number2.
     
WRITE number1.

First : DO NOT use macros in a new program, there is a lot of better way to do it.

Some people come to my desk and tell me they found a "magic" function which the code behind is invisible and it's impossible to trace this function. In some old programs, you can see a strange call to what it look like a function but it's not, it's a macro.

The macros are stored in table TRMAC.

One of the most used macros is "break". To put a break-point in your code that will break only for your user name, you probably use "break my_user_name". This is not part of the ABAP language despite what a lot of people think; it's a macro. If you have a look in table TRMAC, you will see :

BREAK 000 * USER specific BREAK-POINT

BREAK 001 if sy-uname = '&1'

BREAK 002 break-point

BREAK 003 endif

Here is how to create a simple macro, for the sake of understanding what old programs do. Again, do not

create new macros unless you absolutely must.

REPORT zdany_macro.

*Macro definition
DEFINE ZMULTIPLY.
  MULTIPLY &1 BY &2.
END-OF-DEFINITION.
     
DATA: number1 TYPE i VALUE 2,
      number2 TYPE i VALUE 5.
     
* calling the macro, no easy way of knowing this is a macro
ZMULTIPLY number1 number2.
     
WRITE number1.

Using dynamic SELECT statements in sap abap

The very useful SELECT statement could be fully dynamic from release 6.10 and up.

For more information about the dynamic select, you can read the document "Enhanced ABAP programming with Dynamic Open SQL" from Adrian Görler and Ulrich Koch. Here is the link

https://webphl07.phl.sap.corp/~sapidb/011000358700002805272003E , this is a PDF file.

Here is an example of a fully dynamic select.

REPORT zdany_dynamic_select.

* We use some parameters to dynamically control the select, this is not very 
* clever but this is just a test program !!
PARAMETER : p_tabnam TYPE tabname DEFAULT 'SFLIGHT',
            p_selfl1 TYPE edpline DEFAULT 'CARRID',
            p_selfl2 TYPE edpline DEFAULT 'CONNID',
            p_selfl3 TYPE edpline DEFAULT 'FLDATE',
            p_selfl4 TYPE edpline DEFAULT 'PRICE',
            p_selfl5 TYPE edpline DEFAULT 'CURRENCY',
            p_where1 TYPE edpline DEFAULT 'PRICE > 300',
            p_where2 TYPE edpline DEFAULT 'AND CURRENCY = ''EUR'''.
     
FIELD-SYMBOLS :  TYPE ANY TABLE,
                 TYPE ANY,
                 TYPE ANY.
     
DATA: lt_where    TYPE TABLE OF edpline,
      lt_sel_list TYPE TABLE OF edpline,
      lt_group    TYPE TABLE OF edpline,
      l_having    TYPE string,
      l_wa_name   TYPE string,
      l_sel_list  TYPE edpline,
      dref        TYPE REF TO data,
      itab_type   TYPE REF TO cl_abap_tabledescr,
      struct_type TYPE REF TO cl_abap_structdescr,
      elem_type   TYPE REF TO cl_abap_elemdescr,
      comp_tab    TYPE cl_abap_structdescr=>component_table,
      comp_fld    TYPE cl_abap_structdescr=>component.
     
TYPES: f_count TYPE i.
     
* Creation of the output table including a non standard field, f_count
* see ABAP FAQ #14 for more information on this topic
struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
elem_type   ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
comp_tab = struct_type->get_components( ).
     
* We remove the unnecessary fields
LOOP AT comp_tab INTO comp_fld.
   IF comp_fld-name <> p_selfl1 AND
      comp_fld-name <> p_selfl2 AND
      comp_fld-name <> p_selfl3 AND
      comp_fld-name <> p_selfl4 AND
      comp_fld-name <> p_selfl5.
         DELETE TABLE comp_tab WITH TABLE KEY name = comp_fld-name.
   ENDIF.
ENDLOOP.
     
comp_fld-name = 'F_COUNT'.
comp_fld-type = elem_type.
APPEND comp_fld TO comp_tab.
     
struct_type = cl_abap_structdescr=>create( comp_tab ).
itab_type   = cl_abap_tabledescr=>create( struct_type ).
     
l_wa_name = 'l_WA'.
CREATE DATA dref TYPE HANDLE itab_type.
ASSIGN dref->* TO .
CREATE DATA dref TYPE HANDLE struct_type.
ASSIGN dref->* TO .
     
* Creation of the selection fields and the "group by" clause
APPEND p_selfl1 TO lt_sel_list.
APPEND p_selfl1 TO lt_group.
APPEND p_selfl2 TO lt_sel_list.
APPEND p_selfl2 TO lt_group.
APPEND p_selfl3 TO lt_sel_list.
APPEND p_selfl3 TO lt_group.
APPEND p_selfl4 TO lt_sel_list.
APPEND p_selfl4 TO lt_group.
APPEND p_selfl5 TO lt_sel_list.
APPEND p_selfl5 TO lt_group.
APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
     
* creation of the "where" clause
APPEND p_where1 TO lt_where.
APPEND p_where2 TO lt_where.
     
* Creation of the "having" clause
l_having = 'count(*) >= 1'.
     
* THE dynamic select
SELECT          (lt_sel_list)
       FROM     (p_tabnam)
       INTO CORRESPONDING FIELDS OF TABLE 
       WHERE    (lt_where)
       GROUP BY (lt_group)
       HAVING   (l_having)
       ORDER BY (lt_group).
     
* display of the results
LOOP AT  ASSIGNING .
   LOOP AT comp_tab INTO comp_fld.
      ASSIGN COMPONENT comp_fld-name OF STRUCTURE  TO .
      WRITE: .
   ENDLOOP.
   SKIP.
ENDLOOP.

The very useful SELECT statement could be fully dynamic from release 6.10 and up.

For more information about the dynamic select, you can read the document "Enhanced ABAP programming with Dynamic Open SQL" from Adrian Görler and Ulrich Koch. Here is the link

https://webphl07.phl.sap.corp/~sapidb/011000358700002805272003E , this is a PDF file.

Here is an example of a fully dynamic select.

REPORT zdany_dynamic_select.

* We use some parameters to dynamically control the select, this is not very 
* clever but this is just a test program !!
PARAMETER : p_tabnam TYPE tabname DEFAULT 'SFLIGHT',
            p_selfl1 TYPE edpline DEFAULT 'CARRID',
            p_selfl2 TYPE edpline DEFAULT 'CONNID',
            p_selfl3 TYPE edpline DEFAULT 'FLDATE',
            p_selfl4 TYPE edpline DEFAULT 'PRICE',
            p_selfl5 TYPE edpline DEFAULT 'CURRENCY',
            p_where1 TYPE edpline DEFAULT 'PRICE > 300',
            p_where2 TYPE edpline DEFAULT 'AND CURRENCY = ''EUR'''.
     
FIELD-SYMBOLS :  TYPE ANY TABLE,
                 TYPE ANY,
                 TYPE ANY.
     
DATA: lt_where    TYPE TABLE OF edpline,
      lt_sel_list TYPE TABLE OF edpline,
      lt_group    TYPE TABLE OF edpline,
      l_having    TYPE string,
      l_wa_name   TYPE string,
      l_sel_list  TYPE edpline,
      dref        TYPE REF TO data,
      itab_type   TYPE REF TO cl_abap_tabledescr,
      struct_type TYPE REF TO cl_abap_structdescr,
      elem_type   TYPE REF TO cl_abap_elemdescr,
      comp_tab    TYPE cl_abap_structdescr=>component_table,
      comp_fld    TYPE cl_abap_structdescr=>component.
     
TYPES: f_count TYPE i.
     
* Creation of the output table including a non standard field, f_count
* see ABAP FAQ #14 for more information on this topic
struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
elem_type   ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
comp_tab = struct_type->get_components( ).
     
* We remove the unnecessary fields
LOOP AT comp_tab INTO comp_fld.
   IF comp_fld-name <> p_selfl1 AND
      comp_fld-name <> p_selfl2 AND
      comp_fld-name <> p_selfl3 AND
      comp_fld-name <> p_selfl4 AND
      comp_fld-name <> p_selfl5.
         DELETE TABLE comp_tab WITH TABLE KEY name = comp_fld-name.
   ENDIF.
ENDLOOP.
     
comp_fld-name = 'F_COUNT'.
comp_fld-type = elem_type.
APPEND comp_fld TO comp_tab.
     
struct_type = cl_abap_structdescr=>create( comp_tab ).
itab_type   = cl_abap_tabledescr=>create( struct_type ).
     
l_wa_name = 'l_WA'.
CREATE DATA dref TYPE HANDLE itab_type.
ASSIGN dref->* TO .
CREATE DATA dref TYPE HANDLE struct_type.
ASSIGN dref->* TO .
     
* Creation of the selection fields and the "group by" clause
APPEND p_selfl1 TO lt_sel_list.
APPEND p_selfl1 TO lt_group.
APPEND p_selfl2 TO lt_sel_list.
APPEND p_selfl2 TO lt_group.
APPEND p_selfl3 TO lt_sel_list.
APPEND p_selfl3 TO lt_group.
APPEND p_selfl4 TO lt_sel_list.
APPEND p_selfl4 TO lt_group.
APPEND p_selfl5 TO lt_sel_list.
APPEND p_selfl5 TO lt_group.
APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
     
* creation of the "where" clause
APPEND p_where1 TO lt_where.
APPEND p_where2 TO lt_where.
     
* Creation of the "having" clause
l_having = 'count(*) >= 1'.
     
* THE dynamic select
SELECT          (lt_sel_list)
       FROM     (p_tabnam)
       INTO CORRESPONDING FIELDS OF TABLE 
       WHERE    (lt_where)
       GROUP BY (lt_group)
       HAVING   (l_having)
       ORDER BY (lt_group).
     
* display of the results
LOOP AT  ASSIGNING .
   LOOP AT comp_tab INTO comp_fld.
      ASSIGN COMPONENT comp_fld-name OF STRUCTURE  TO .
      WRITE: .
   ENDLOOP.
   SKIP.
ENDLOOP.

Recent Topics