Search code examples
sqldb2db2-400rpgle

ILE RPG Static SQL Fetch first row of a cursor


My Code:

     EXEC SQL
     DECLARE C1 CURSOR
     FOR SELECT * FROM a
     WHERE :field LIKE CONCAT(TRIM(a.number), '%')
     ORDER BY a.number DESC;

     EXEC SQL
     OPEN C1;

     EXEC SQL
     FETCH C1 INTO :a;

I need only the highest number of the cursor - so the ORDER BY DESC.

How can I fetch only the first row of the cursor C1?


Solution

  •  EXEC SQL
         FETCH C1 INTO :a;
    

    Only fetches one row...so just execute it a single time.

    However, you'd be better off using a SELECT INTO with FETCH FIRST ROW ONLY if you know you only need 1 row

    exec sql
      SELECT * 
        FROM a
        INTO :a
       WHERE :field LIKE CONCAT(TRIM(a.number), '%')
       ORDER BY a.number DESC
       FETCH FIRST ROW ONLY;