Example of dynamic SQL in an ILE RPG application that uses SQL

The following is an example of using dynamic SQL in ILE RPG.

D**************************************************
D* Declare program variables.                     *
D* STMT initialized to the                        *
D* listed SQL statement.                          *
D**************************************************                                                                
D EMPNUM          S              6A 
D NAME            S             15A
D STMT            S            500A   INZ('SELECT LASTNAME         -
D                                     FROM CORPDATA.EMPLOYEE WHERE -
D                                     EMPNO = ?')

…

C*************************************************************
C* Prepare STMT as initialized in declare section            *
C*************************************************************
C/EXEC SQL
C+ PREPARE S1 FROM :STMT
C/END-EXEC
C*
C*************************************
C* Declare Cursor for STMT           *
C*************************************
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR S1
C/END-EXEC
C*
C*****************************************************
C* Assign employee number to use in select statement *
C*****************************************************
C                   eval      EMPNUM = '000110'

C**********************
C* Open Cursor        *
C**********************
C/EXEC SQL
C+ OPEN C1 USING :EMPNUM
C/END-EXEC
C*
C***********************************************
C* Fetch record and put value of               *
C* LASTNAME into NAME                          *
C***********************************************
C/EXEC SQL
C+  FETCH C1 INTO :NAME
C/END-EXEC
…


C********************************
C* Program processes NAME here  *
C********************************
…
C******************
C* Close cursor   *
C******************
C/EXEC SQL
C+  CLOSE C1
C/END-EXEC