SQLRPGLE: embedded SQL done properly
Embedded SQL in RPG is the default way to access Db2 for i in new code. It is also where I most often see sloppy code: no status checks, SELECT *, and cursors left open. This article gives a pattern you can paste into a real program.
Syntax in **FREE
SQL statements start with exec sql and end with a semicolon, and can span lines. The source member type is SQLRPGLE.
**free
exec sql set option commit = *none, closqlcsr = *endmod, datfmt = *iso;
Same program in fixed format (what you will meet in most shops):
C/EXEC SQL
C+ SET OPTION COMMIT = *NONE, CLOSQLCSR = *ENDMOD,
C+ DATFMT = *ISO
C/END-EXEC
Fixed format has no exec sql ...; one-liner: the statement sits between C/EXEC SQL and C/END-EXEC on C+ lines (/ in column 7, EXEC SQL in columns 8-16). SET OPTION goes there like any other statement.
SET OPTION is not executable; the precompiler reads it. IBM requires it to precede every other SQL statement in the source, and you can code only one, so put all options in that one statement. It lets the source carry its own compile options.
Host variables and structures
Prefix RPG variables with a colon inside SQL.
dcl-s custId packed(9:0);
dcl-s custName char(30);
dcl-ds cust qualified;
id packed(9:0);
name char(30);
balance packed(11:2);
end-ds;
Same program in fixed format (what you will meet in most shops):
DCUSTID S 9P 0
DCUSTNAME S 30A
DCUST DS QUALIFIED
D ID 9P 0
D NAME 30A
D BALANCE 11P 2
A host structure maps columns by position, not name, so the select list order must match the structure. Always list columns explicitly.
Single-row SELECT INTO
custId = 1001;
exec sql select name, balance
into :cust.name, :cust.balance
from mylib.customer
where id = :custId;
Same program in fixed format (what you will meet in most shops):
C EVAL CUSTID = 1001
C/EXEC SQL
C+ SELECT NAME, BALANCE
C+ INTO :CUST.NAME, :CUST.BALANCE
C+ FROM MYLIB.CUSTOMER
C+ WHERE ID = :CUSTID
C/END-EXEC
If no row matches you get SQLSTATE 02000 (SQLCODE 100). If more than one matches, you get an error (SQLSTATE 21000, SQLCODE -811) unless you add fetch first row only. Decide which you mean. A null in a column needs a null-indicator variable (:cust.balance :balInd) or you get SQLCODE -305.
Checking status: SQLSTATE and SQLCODE
The precompiler gives you sqlstate and sqlcode automatically. Check after every statement. SQLSTATE is the portable value; SQLCODE is Db2-specific but handy.
dcl-proc checkSql;
dcl-pi *n ind;
allowNoData ind const;
end-pi;
select;
when sqlstate = '00000';
return *off;
when sqlstate = '02000' and allowNoData;
return *off;
other;
dsply ('SQL error ' + sqlstate + ' code ' + %char(sqlcode));
return *on;
endsl;
end-proc;
Same program in fixed format (what you will meet in most shops):
PCHECKSQL B
DCHECKSQL PI N
D ALLOWNODATA N CONST
DMSG S 100A VARYING
C SELECT
C WHEN SQLSTATE = '00000'
C RETURN *OFF
C WHEN SQLSTATE = '02000' AND ALLOWNODATA
C RETURN *OFF
C OTHER
C EVAL MSG = 'SQL error ' + SQLSTATE
C + ' code ' + %CHAR(SQLCODE)
C MSG DSPLY
C RETURN *ON
C ENDSL
PCHECKSQL E
DSPLY needs a variable in fixed format, hence MSG. DSPLY also cuts the message at 52 characters, so keep it short. If CHECKSQL is called earlier in the same source, add a D CHECKSQL PR N prototype first.
Warnings start with 01, not found is 02, and 00 is success. Anything else (class 22, 23, 42 and so on) is an error you must handle. For details use GET DIAGNOSTICS CONDITION 1 :msg = MESSAGE_TEXT (the CONDITION 1 is required for condition items like MESSAGE_TEXT, RETURNED_SQLSTATE and DB2_MESSAGE_ID). Capture sqlstate into a variable before you run it, or any other statement, because every later SQL statement can overwrite what you were about to test.
Cursors
- DECLARE: Define the query, nothing runs yet
- OPEN: The database runs the query
- FETCH in a loop: One row (or a block) per call, until SQLCODE 100
- CLOSE: Release the cursor
Use a cursor when you expect many rows: declare, open, fetch in a loop, close.
exec sql declare c1 cursor for
select id, name, balance
from mylib.customer
where balance > :minBal
order by id;
exec sql open c1;
exec sql fetch next from c1 into :cust;
dow sqlstate < '02000';
// process cust
exec sql fetch next from c1 into :cust;
enddo;
exec sql close c1;
Same program in fixed format (what you will meet in most shops):
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+ SELECT ID, NAME, BALANCE
C+ FROM MYLIB.CUSTOMER
C+ WHERE BALANCE > :MINBAL
C+ ORDER BY ID
C/END-EXEC
C/EXEC SQL
C+ OPEN C1
C/END-EXEC
C/EXEC SQL
C+ FETCH NEXT FROM C1 INTO :CUST
C/END-EXEC
C DOW SQLSTATE < '02000'
* process cust
C/EXEC SQL
C+ FETCH NEXT FROM C1 INTO :CUST
C/END-EXEC
C ENDDO
C/EXEC SQL
C+ CLOSE C1
C/END-EXEC
DECLARE is not executable, but it must appear in the source before the OPEN that uses it, and the host variables it references must be declared before it. closqlcsr(*endmod) closes cursors when the module ends. The ILE default is *ENDACTGRP, so a cursor you forget to close stays open until the activation group ends, and the next call's OPEN fails with SQLSTATE 24502 (already open). Close cursors yourself anyway.
Multi-row fetch
Fetching a block of rows in one call reduces overhead. Use an array data structure.
dcl-ds rows qualified dim(100);
id packed(9:0);
name char(30);
balance packed(11:2);
end-ds;
dcl-s fetched int(10);
exec sql fetch next from c1 for 100 rows into :rows;
fetched = sqlerrd(3);
Same program in fixed format (what you will meet in most shops):
DROWS DS QUALIFIED DIM(100)
D ID 9P 0
D NAME 30A
D BALANCE 11P 2
DFETCHED S 10I 0
C/EXEC SQL
C+ FETCH NEXT FROM C1 FOR 100 ROWS INTO :ROWS
C/END-EXEC
C EVAL FETCHED = SQLERRD(3)
SQLERRD(3) (short name SQLER3) holds the number of rows fetched. The last block is usually short: Db2 then returns SQLSTATE 02000 (SQLCODE 100) and the rows it did find, so process SQLERRD(3) rows first and stop afterwards. Reading it straight after the FETCH needs no extra statement; GET DIAGNOSTICS :fetched = ROW_COUNT gives the same count but is one more statement to get wrong.
Dynamic SQL
When the statement text is built at run time, use PREPARE and EXECUTE. Use parameter markers (?), never concatenated user input, to avoid SQL injection.
dcl-s stmt varchar(200);
stmt = 'update mylib.customer set balance = balance + ? where id = ?';
exec sql prepare s1 from :stmt;
exec sql execute s1 using :amount, :custId;
Same program in fixed format (what you will meet in most shops):
DSTMT S 200A VARYING
C EVAL STMT = 'update mylib.customer set '
C + 'balance = balance + ? where id = ?'
C/EXEC SQL
C+ PREPARE S1 FROM :STMT
C/END-EXEC
C/EXEC SQL
C+ EXECUTE S1 USING :AMOUNT, :CUSTID
C/END-EXEC
The statement literal is split with + because a single literal would run past column 80.
For a one-off statement without parameters, EXECUTE IMMEDIATE :stmt is enough. A dynamic SELECT is prepared, then used with DECLARE CURSOR FOR s1 and OPEN c USING :value.
Commitment control basics
With COMMIT(*NONE) every statement is permanent immediately. With COMMIT(*CHG) (or *CS, *ALL) changes are held until you issue COMMIT or ROLLBACK.
exec sql update mylib.account set balance = balance - :amt where id = :fromId;
if checkSql(*off);
exec sql rollback;
else;
exec sql update mylib.account set balance = balance + :amt where id = :toId;
if checkSql(*off);
exec sql rollback;
else;
exec sql commit;
endif;
endif;
Same program in fixed format (what you will meet in most shops):
C/EXEC SQL
C+ UPDATE MYLIB.ACCOUNT SET BALANCE = BALANCE - :AMT
C+ WHERE ID = :FROMID
C/END-EXEC
C IF CHECKSQL(*OFF)
C/EXEC SQL
C+ ROLLBACK
C/END-EXEC
C ELSE
C/EXEC SQL
C+ UPDATE MYLIB.ACCOUNT SET BALANCE = BALANCE + :AMT
C+ WHERE ID = :TOID
C/END-EXEC
C IF CHECKSQL(*OFF)
C/EXEC SQL
C+ ROLLBACK
C/END-EXEC
C ELSE
C/EXEC SQL
C+ COMMIT
C/END-EXEC
C ENDIF
C ENDIF
Tables must be journaled to be used under commitment control; otherwise the statement fails at runtime (SQLCODE -7008, SQLSTATE 55019). The CRTSQLRPGI default is COMMIT(*CHG), so a program you compile without thinking about it hits this on any unjournaled file. On PUB400 a new SQL schema is journaled automatically, but tables created with CRTPF (see DDS to SQL DDL migration) in a plain library are not.
Compile options
CRTSQLRPGI OBJ(MYLIB/CUSTSQL) SRCFILE(MYLIB/QRPGLESRC) SRCMBR(CUSTSQL)
COMMIT(*NONE) OPTION(*EVENTF) CLOSQLCSR(*ENDMOD)
DBGVIEW(*SOURCE) COMPILEOPT('TGTRLS(*CURRENT)')
The precompiler produces a temporary source and then calls the RPG compiler. COMMIT(*NONE) is right for batch utilities (wrap the call in CL and use SBMJOB) and read-only programs; choose *CHG for transactional programs. The SET OPTION line in the source carries the same options with the member.
Defaults worth knowing before you rely on them:
| Parameter |
CRTSQLRPGI default |
Effect |
|---|---|---|
COMMIT |
*CHG |
Needs journaled tables, see above |
CLOSQLCSR |
*ENDACTGRP |
Open cursors survive the program ending; set *ENDMOD for a clean state per call |
OPTION naming |
*SYS |
Unqualified names resolve through the library list; *SQL uses the default schema (DFTRDBCOL) instead |
The samples use mylib.customer. With OPTION(*SQL) an unqualified name goes to the default schema instead of the library list.
Performance basics
- Select only the columns you need and filter in
WHERE, not in RPG loops. - Mixing RLA (
chain,read) and SQL on the same file in one program is allowed, but each keeps its own cursor position, and RLA does not follow SQL's. Stick to one access method per task, and if you must mix, test what each side sees after the other has changed data. - Use multi-row fetch and multi-row
INSERT ... FOR n ROWSfor volume. Both take a host structure array: an array data structure (dim) or an occurrence data structure. - If a statement is slow, use Visual Explain in ACS Run SQL Scripts. It shows index advice and the access plan.
- Make sure host variable types match column types. A mismatch causes conversions that can defeat index use.
Complete sample
**free
ctl-opt dftactgrp(*no) actgrp(*new) option(*srcstmt:*nodebugio);
exec sql set option commit = *none, closqlcsr = *endmod, datfmt = *iso;
dcl-s minBal packed(11:2) inz(1000);
dcl-s fetched int(10);
dcl-s total int(10);
dcl-ds rows qualified dim(50);
id packed(9:0);
name char(30);
balance packed(11:2);
end-ds;
exec sql declare c1 cursor for
select id, name, balance
from mylib.customer
where balance > :minBal
order by id;
exec sql open c1;
if sqlstate >= '02000';
dsply ('Open failed ' + sqlstate);
return;
endif;
dou sqlstate >= '02000';
exec sql fetch next from c1 for 50 rows into :rows;
if sqlstate <= '02000';
fetched = sqlerrd(3);
total += fetched;
endif;
enddo;
exec sql close c1;
if sqlstate > '02000';
dsply ('Error ' + sqlstate + ' ' + %char(sqlcode));
endif;
dsply ('Rows read: ' + %char(total));
return;
Same program in fixed format (what you will meet in most shops):
H DFTACTGRP(*NO) ACTGRP(*NEW) OPTION(*SRCSTMT:*NODEBUGIO)
DMINBAL S 11P 2 INZ(1000)
DFETCHED S 10I 0
DTOTAL S 10I 0
DMSG S 100A VARYING
DROWS DS QUALIFIED DIM(50)
D ID 9P 0
D NAME 30A
D BALANCE 11P 2
C/EXEC SQL
C+ SET OPTION COMMIT = *NONE, CLOSQLCSR = *ENDMOD,
C+ DATFMT = *ISO
C/END-EXEC
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+ SELECT ID, NAME, BALANCE
C+ FROM MYLIB.CUSTOMER
C+ WHERE BALANCE > :MINBAL
C+ ORDER BY ID
C/END-EXEC
C/EXEC SQL
C+ OPEN C1
C/END-EXEC
C IF SQLSTATE >= '02000'
C EVAL MSG = 'Open failed ' + SQLSTATE
C MSG DSPLY
C RETURN
C ENDIF
C DOU SQLSTATE >= '02000'
C/EXEC SQL
C+ FETCH NEXT FROM C1 FOR 50 ROWS INTO :ROWS
C/END-EXEC
C IF SQLSTATE <= '02000'
C EVAL FETCHED = SQLERRD(3)
C EVAL TOTAL = TOTAL + FETCHED
C ENDIF
C ENDDO
C/EXEC SQL
C+ CLOSE C1
C/END-EXEC
C IF SQLSTATE > '02000'
C EVAL MSG = 'Error ' + SQLSTATE
C + ' ' + %CHAR(SQLCODE)
C MSG DSPLY
C ENDIF
C EVAL MSG = 'Rows read: ' + %CHAR(TOTAL)
C MSG DSPLY
C RETURN
Fixed format wants all D specs before the first C spec, so the declarations move up. SET OPTION is still the first SQL statement in the source, which is what the precompiler needs.
Try it on PUB400
- In ACS Run SQL Scripts or
STRSQL, create a schema and a table:create schema yourlib; create table yourlib.customer (id decimal(9,0) not null, name char(30) not null, balance decimal(11,2) not null);then insert a few rows. - Change
mylibin the sample to your schema, add it as aSQLRPGLEmember, and compile withCRTSQLRPGI. - Run it, then break it: misspell a column and read the compile listing; fetch from a closed cursor and see SQLSTATE
24501.
Best resources
-
IBM Docs: Embedding SQL in ILE RPG programs:
EXEC SQLlayout, columns and continuation rules -
IBM Docs: Host structure arrays in ILE RPG: multi-row
FETCHandINSERT - IBM Docs: SET OPTION: every option, and the placement rule
-
IBM Docs: GET DIAGNOSTICS:
ROW_COUNTand the condition items - IBM Docs: CRTSQLRPGI: all compile parameters and defaults
- IBM Support: CLOSQLCSR with CRTSQLxxx: what each value does to cursors, prepared statements and locks
-
RPGPGM.com: getting the number of rows affected by SQL:
ROW_COUNTandSQLERRD(3)with worked examples - Db2 for i Services (Scott Forstie, IBM): SQL services you can call straight from RPG
Next
Next: DDS to SQL DDL migration
Related
Originally published on rainierio.dev. The full Learn IBM i track, with an Indonesian version, is at rainierio.dev/learn.
Top comments (0)