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 the Hierarchy Generator

This example demonstrates how an internal table is accessed in a common table expression with self association and how the table is used as a data source of the hierarchy generator.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA(start_id) = CONV  demo_parent_chld-id( 'A' ).
    cl_demo_input=>request( CHANGING field = start_id ).

    DATA parent_child_tab TYPE HASHED TABLE OF parent_child
                          WITH UNIQUE KEY cnt.

    parent_child_tab = VALUE #(
            ( cnt = 1 id = 'A'  parent_id = ' ' )
            ( cnt = 2 id = 'B'  parent_id = 'A' )
            ( cnt = 3 id = 'C'  parent_id = 'A' )
            ( cnt = 4 id = 'D'  parent_id = 'C' )
            ( cnt = 5 id = 'D'  parent_id = 'B' )
            ( cnt = 6 id = 'D'  parent_id = 'A' ) ).

    WITH
      +parent_child_source AS
         ( SELECT FROM @parent_child_tab AS parent_child_tab
                  FIELDS id,
                         parent_id AS parent )
            WITH ASSOCIATIONS (
              JOIN TO MANY +parent_child_source AS _relat
                ON +parent_child_source~parent = _relat~id )
      SELECT FROM HIERARCHY( SOURCE +parent_child_source
                             CHILD TO PARENT ASSOCIATION _relat
                             START WHERE id = @start_id
                             SIBLINGS ORDER BY id
                             MULTIPLE PARENTS ALLOWED )
             FIELDS id,
                    parent,
                    hierarchy_rank,
                    hierarchy_tree_size,
                    hierarchy_parent_rank,
                    hierarchy_level,
                    hierarchy_is_cycle,
                    hierarchy_is_orphan,
                    node_id,
                    parent_id
             INTO TABLE @DATA(result).

    cl_demo_output=>display( result ).

Description

An internal table parent_child_tab is used as a data source of the common table expression +parent_child_source in a WITH statement. A CTE association _relat is defined and published for the common table expression. The CTE association is a self association. The common table expression can be used as a data source and the CTE association can be used as a hierarchy association of the hierarchy generator HIERARCHY used in the main query of the WITH statement.