Error Checking and Embedded SQL
June 8, 2005 Hey, Ted
We are still new to the world of embedded SQL. We are still trying to determine how to check for success or failure of SQL commands. So far we have determined that we should use the SQL code and SQL state variables, both of which seem to serve the same purpose. Can you give us some direction?
–Pat
Good question, Pat. I have seen programs that had no error checking for the SQL commands. When something goes wrong, they just keep on truckin’! Then people wonder why the database is messed up.
Here’s the method I use. It has worked well for me.
I define a return-code parameter in the program that contains embedded SQL. In my case, the program is written in RPG, so I’ll use that language for my examples.
D MYPGM pr extpgm('MYPGM') D ouStatus 8a D MYPGM pi D ouStatus 8a
Here’s the “old” method to define the parameter.
C *entry plist C parm ouStatus 8
When the program begins to run, I set the parameter to the value 00-00000.
D AllOK c const('00-00000') C eval ouStatus = AllOK
When an SQL command fails, I set the first two characters of the parameter to a two-digit number that uniquely identifies the SQL command and copy the SQL state variable to the last five characters.
D SQLNormal c const('00000') D SQLEOF c const('02000') C/exec sql C+ prepare SqlStmt from :SqlCommand C/end-exec C if SQLStt <> SQLNormal C eval ouStatus = '12-' + SqlStt C return C endif C/exec sql C+ open input C/end-exec C if SQLStt <> SQLNormal C eval ouStatus = '14-' + SqlStt C return C endif
This method tells me where the program failed and gives me some idea of the nature of the error.
The calling CL program tests the parameter and cancels if something went wrong.
dcl &Status *char 8 call mypgm parm(&Status) if (&Status *ne '00-00000') do SndPgmMsg MsgID(CPF9898) MsgF(QCPFMSG) + MsgDta('Program MYPGM + ended abnormally with status' *BCAT + &Status) MsgType(*ESCAPE) enddo
A couple more notes and I’m done. First, whether you use SQL state or SQL code is a matter of preference. Everything I read tells me that the SQL state mechanism is the more standard of the two, so that’s what I use.
Second, you’ll have to determine which values indicate success or failure. For example, SQL state 02000 indicates end-of-file for a fetch, and that is fine when you’re reading a result set through a cursor. However, there may be circumstances when you issue only one fetch and want to make sure that the fetch retrieved data. In that case, 02000 is not acceptable.
The same thing can be said of warnings, which are SQL state values greater than 00000 and less than 02000. In some cases, you may want to ignore some or all warnings, while in other cases, you may want to treat warnings as errors.
–Ted