Example of a fetch in a statically executed SQL program

A fetch is an SQL action that positions a cursor on the next row of its result table and assigns the values of that row to host variables.

The following sample selects from a table using a cursor, opens the cursor, and fetches rows from the table. For each row fetched, the program decides, based on simple criteria, whether the row must be deleted or updated.

The REXX language does not support static SQL, so a sample is not provided.

  • C and C++ (tbmod.sqc/tbmod.sqC)
    The following example selects from a table using a cursor, opens the cursor, fetches, updates, or delete rows from the table, then closes the cursor.
    EXEC SQL DECLARE c1 CURSOR FOR SELECT * FROM staff WHERE id >= 310; 
      EXEC SQL OPEN c1; 
      EXEC SQL FETCH c1 INTO :id, :name, :dept, :job:jobInd, :years:yearsInd, :salary,
         :comm:commInd; 
    The sample shows almost all possible cases of table data modification.
  • COBOL (openftch.sqb)
    The following example is from the sample openftch. This example selects from a table using a cursor, opens the cursor, and fetches rows from the table.
     EXEC SQL DECLARE c1 CURSOR FOR 
       SELECT name, dept FROM staff 
       WHERE job='Mgr'
       FOR UPDATE OF job END-EXEC. 
    
     EXEC SQL OPEN c1 END-EXEC 
    
    
    * call the FETCH and UPDATE/DELETE loop.
      perform Fetch-Loop thru End-Fetch-Loop
      until SQLCODE not equal 0. 
    
     EXEC SQL CLOSE c1 END-EXEC.