Search code examples
abapsubroutine

Pass inline declared table/variable to subroutine in ABAP


I know when I need to pass an internal table to a subroutine, I need to declare a type so I can use it in the FORM statement. What happens if the internal table is an inline declaration table from a SELECT statement like this:

SELECT * FROM KNA1 INTO TABLE @DATA(LT_KNA1)

Is there any way to pass this table to a subroutine? Thank you.


Solution

  • The subroutines are obsolete since ABAP 7.02 (2009), so I use a method in my example.

    Inline declarations are an easy way of declaring types implicitly, but the limit of this solution is that you can type the parameter of a method only generically (types STANDARD TABLE, INDEX TABLE, ANY TABLE, ANY) which prevents you from stating the component names statically in your code.

    But inline declarations of type DATA(...) are always based on a complete "bound" data type, so you can declare the type explicitly with TYPES and use it to type both your parameter and your data object.

    If you use the ABAP Development Tools (Eclipse), you may use the Quick Fix "Declare local variable ... explicitly" to simplify the task: enter image description here

    which gives this code:

    REPORT.
    CLASS lcl_app DEFINITION.
      PUBLIC SECTION.
        CLASS-METHODS main.
    ENDCLASS.
    CLASS lcl_app IMPLEMENTATION.
      METHOD main.
        TYPES: BEGIN OF helper_type,                       " <=== automatically generated
                 carrid TYPE scarr-carrid,
                 carrname TYPE scarr-carrname,
               END OF helper_type.
        DATA: lt_scarr TYPE STANDARD TABLE OF helper_type. " <=== automatically generated
        SELECT carrid, carrname FROM scarr 
            INTO TABLE @lt_scarr.                          " <=== automatically changed
      ENDMETHOD.
    ENDCLASS.
    

    Now, declare manually the table type, use it to type a parameter of a method (a new one here):

    REPORT.
    CLASS lcl_app DEFINITION.
      PUBLIC SECTION.
        TYPES: BEGIN OF helper_type,
                 carrid TYPE scarr-carrid,
                 carrname TYPE scarr-carrname,
               END OF helper_type.
        TYPES: tt_scarr TYPE STANDARD TABLE OF helper_type.  " <=== declare the type
        CLASS-METHODS main.
        CLASS-METHODS process_table                          " <=== new method with this type
            IMPORTING table TYPE tt_scarr.
    ENDCLASS.
    CLASS lcl_app IMPLEMENTATION.
      METHOD main.
        DATA: lt_scarr TYPE STANDARD TABLE OF helper_type.
        SELECT carrid, carrname FROM scarr 
            INTO TABLE @lt_scarr.
      ENDMETHOD.
      METHOD process_table.                                  " <=== new method
        LOOP AT table REFERENCE INTO DATA(line).
          DATA(carrid) = line->carrid.
        ENDLOOP.
      ENDMETHOD.
    ENDCLASS.