Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Processing External Data →  ABAP Database Access →  ABAP SQL →  ABAP SQL - Reads →  SELECT clauses →  SELECT - FROM →  SELECT - FROM data_source →  SELECT - FROM @itab 

Internal Table as a Data Source of a SELECT Statement

This example demonstrates how an internal table is accessed using an ABAP SQL query.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    TYPES:
      BEGIN OF struct,
        key1 TYPE c LENGTH 1,
        key2 TYPE c LENGTH 1,
        num1 TYPE i,
        num2 TYPE i,
      END OF struct,
      itab TYPE SORTED TABLE OF struct
                WITH NON-UNIQUE KEY key1 key2.

    DATA(rnd) = cl_abap_random_int=>create(
      seed = CONV i( sy-uzeit ) min = 1 max = 5 ).

    DATA(out) = cl_demo_output=>new( ).

    DATA(itab) = VALUE itab(
      FOR i = 1 UNTIL i > 100
        LET off1 = rnd->get_next( ) - 1
            off2 = rnd->get_next( ) - 1 IN
            ( key1 = sy-abcde+off1(1)
              key2 = sy-abcde+off2(1)
              num1 = rnd->get_next( )
              num2 = rnd->get_next( ) ) ).
    out->write( itab ).

    SELECT FROM @itab AS itab
           FIELDS key1,
                  key2,
                  SUM( num1 ) AS sum1,
                  SUM( num2 ) AS sum2,
                  SUM( num1 + num2 ) AS sum
           GROUP BY key1, key2
           ORDER BY key1, key2
           INTO TABLE @DATA(result)
           ##itab_db_select.
    out->write( result ).

    out->display( ).

Description

An internal table is filled with random values and is used as a data source of a SELECT statement. Aggregate expressions, an SQL expression, GROUP BY, and ORDER BY are all used when doing this. The statement cannot, however, be executed on the AS ABAP since it does not meet the restrictions in force. For this example, the pragma ##itab_db_select is used to hide the corresponding syntax check warning.