SAP EXEC CURSOR ABAP Statements

Get Example source ABAP code based on a different SAP table
  



EXEC SQL - OPEN, CLOSE, FETCH

In embedded Native SQL, similar statements to those in Open SQL can be specified to read data using a database cursor.
• OPEN FOR SELECT EXEC SQL


ABAP Syntax EXEC SQL.

OPEN dbcur FOR SELECT ...
ENDEXEC.

What does it do? Opens a database cursor dbcur. For dbcur, a flat character-like host variable can be specified.
• FETCH EXEC SQL


ABAP Syntax EXEC SQL.

FETCH NEXT dbcur INTO ...
ENDEXEC.

What does it do? Reads data using an open database cursor dbcur.
• CLOSE EXEC SQL


ABAP Syntax EXEC SQL.

CLOSE dbcur
ENDEXEC.

What does it do? Closes an opened database cursor dbcur. If no row can be read using FETCH, sy-subrc is set to 4 by ENDEXEC. After a FETCH statement, the system field sy-dbcnt is set to the number of rows read up to that point using the cursor in question. If an overflow occurs because the number or rows is greater than 2,147,483,647, sy-dbcnt is set to -1.



Latest notes:It depends on the database system whether the database
cursor in the database is closed implicitly after the extraction of the final row of the results set or not. For this reason, it is advisable to use the statement CLOSE dbcur explicitly.



Example ABAP Coding
Reads multiple rows from the database table SPFLI
using cursor handling and host variables in static Native SQL. If rows are found, sy-subrc is set to 0 and sy-dbcnt is increased by one for each row read. PARAMETERS p_carrid TYPE spfli-carrid.

DATA: connid TYPE spfli-connid,
cityfrom TYPE spfli-cityfrom,
cityto TYPE spfli-cityto.

EXEC SQL.
OPEN dbcur FOR
SELECT connid, cityfrom, cityto
FROM spfli
WHERE mandt = :sy-mandt AND
carrid = :p_carrid
ENDEXEC.

DO.
EXEC SQL.
FETCH NEXT dbcur INTO :connid, :cityfrom, :cityto
ENDEXEC.
IF sy-subrc <(><<)>> 0.
EXIT.
ELSE.
...
ENDIF.
ENDDO.

EXEC SQL.
CLOSE dbcur
ENDEXEC.

Return to menu