Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Processing External Data →  ABAP Database Accesses →  Open SQL →  Open SQL - Read Accesses →  OPEN CURSOR 

Reading Data Through the Cursor

The example shows how to read data through the cursor.

Other versions: 7.31 | 7.40 | 7.54

Source Code

REPORT demo_select_cursor.

DATA: wa_spfli   TYPE spfli,
      wa_sflight TYPE sflight,
      wa_sflight_back TYPE sflight.

DATA: c1 TYPE cursor,
      c2 TYPE cursor.

OPEN CURSOR @c1 FOR
  SELECT *
    FROM spfli
    ORDER BY PRIMARY KEY.

OPEN CURSOR @c2 FOR
  SELECT *
         FROM sflight
         ORDER BY PRIMARY KEY.

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

DO.
  FETCH NEXT CURSOR @c1 INTO @wa_spfli.
  IF sy-subrc NE 0.
    EXIT.
  ENDIF.
  out->begin_section(
    |{ wa_spfli-carrid } { wa_spfli-connid }| ).
  DO.
    IF NOT wa_sflight_back IS INITIAL.
      wa_sflight = wa_sflight_back.
      CLEAR wa_sflight_back.
    ELSE.
      FETCH NEXT CURSOR @c2 INTO @wa_sflight.
      IF  sy-subrc <> 0.
        EXIT.
      ELSEIF wa_sflight-carrid <> wa_spfli-carrid
          OR wa_sflight-connid <> wa_spfli-connid.
        wa_sflight_back = wa_sflight.
        EXIT.
      ENDIF.
    ENDIF.
    out->write(
     |{ wa_sflight-carrid } {
        wa_sflight-connid } {
        wa_sflight-fldate }| ).
  ENDDO.
  out->end_section( ).
ENDDO.

CLOSE CURSOR: @c1, @c2.

out->display( ).

Description

The system opens two cursors for the tables SPFLI and SFLIGHT. Since both tables are linked through a foreign key relationship, you can define a nested loop over the tables by sorting the selection by the primary key; the system then reads the data of the inner loop dependently on the data of the outer loop. This way of programming is more efficient than the usage of nested SELECT loops since the cursor for the inner loop needs not be reset again and again. In a control level change in the inner loop, the system temporarily stores the data read until the next loop pass since it is not possible to reset the cursor.