SQL in free format RPG

Do you use SQL and free format RPG independently but haven't really put the two together yet? If so then this article is for you.

Executing SQL statements in free format RPG may be a lot easier than you think. Doing so can streamline and speed up your legacy code.

Example of a simple select (to conditionally retrieve a field):

c/free
 //comment - get employee by company and last name
  exec sql
   select empno into :wkempno
      from datalib/empf
   where empco# = '001' and
     (lastnam = 'Doe');
 /end-free

Example two: Reading through a file using fetch cursor in free format should look something like this:

c//declare cursor
c/exec sql declare Cursor1 cursor as
c+   (select empno as myemp#, count(*) as mycount
c+     from myfile
c+     group empno
c+     order by empno)

c/end-exec
c//open cursor 
c/exec sql open Cursor1
c/end-exec
c/free
    dow sqlcod = *zero;
 /end-free
 //fetch records
c/exec sql fetch Cursor1 into recno;
c/end-exec
 /free
     if sqlcod <> *zero;
       iter;
     endif;
 //file processing statements added here
   enddo;
/end-free
//close cursor

c/exec sql close Cursor1
c/end-exec

Conclusion: one should not avoid using SQL code in free format RPG IV as doing so can improve the efficiency of legacy programs.