TechTip: Handling SQL Return Codes, Part I

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

In a previous article, I demonstrated that treating SQLCOD as a two-value field, just like a native IO on/off indicator has some inherent dangers. In this article, I encourage you to use SQLSTT instead of SQLCOD and I provide a list of the SQLSTT values that commonly occur in business programming. Then I show you that it's easy to stringently check all SQL return codes.

SQLSTT vs. SQLCOD

SQLSTT (SQL State) and SQLCOD (SQL Code) return largely the same information about the last executed SQL statement, but they use different formats. I prefer to use the SQLSTT field rather than SQLCOD for a couple of reasons:

  • SQLCOD = 0 means success, but "success" may also be qualified by warnings in the SQLWRN field. If any of the warnings might significantly impact your program logic, you also have to check SQLWRN and its subfields. A SQLSTT of '00000' means unqualified success, and I find it more convenient.
  • SQLSTT codes are based on the ISO/ANSI SQL 1999 Core standard and are the same across all versions of DB2, so you also have more in common with your non-iSeries coworkers.

I code as meaningfully named constants the handful of SQLSTT values that are routinely checked. See Figure 1. Put these lines in a copy book if you want consistency in your shop. Use different meaningful names if you want, but for clarity, do use names.

*=== SQL State Constants ============================= 
d SQLSuccess      c                   '00000'         
d SQLNoData       c                   '02000'         
d SQLNoMoreData   c                   '02000'         
d SQLDupRecd      c                   '23505'         
d SQLRowLocked    c                   '57033'         

Figure 1: These are meaningfully named common SQLSTT values.

SQLSuccess says the SQL operation went off without a hitch, exactly as expected.

SQLNoData occurs when a SELECT statement does not find a qualifying row and thus returns no data ("No record found" in native IO).

SQLNoMoreData occurs when FETCHing from a cursor and you have come to the end of the results set ("End of file" in native IO).

SQLDupRecd occurs when you do an insert that fails a primary key constraint. (In native parlance, you have a unique key on the file and a record with this key already exists.)

SQLRowLocked occurs when you try to update a record, but someone else has it locked for update.

(Sharp-eyed readers will notice that SQLNoData and SQLNoMoreData have the same value, '02000'. I'm a bit of a perfectionist, and I think the code is more intuitive if both are available and used in the appropriate context.)

There are many SQL return codes, but in my experience, only this handful turns up routinely in the business programs that most of us regularly create. Treat these as a beginning set and add more as needed. Most, but not all, of the others indicate an error that should never occur and from which there is frequently no programmatic recovery.

Checking SQL Execution Success

Here's my general rule of thumb: Check for and have logic to handle the SQLSTT return codes you expect. If you get a return code you don't expect, do not ignore it; instead, take some diagnostic action with a common error handler.

I check SQLSTT after every executable SQL statement. Note that Set Option and Declare Cursor are not executable statements, and thus they do not set SQLSTT, so do not check after these statements.

My assumption is that environmental issues—such as setting library lists, file authority, and file availability—have been taken care of prior to my program. So, after an Open Cursor statement, the only return code I expect is success, and I route any other to a standard routine to handle unexpected SQL return codes. If the cursor is already open, trying to open it again will return an error. This means to me that I goofed and seriously need to review my program logic, so the standard error-handling routine is appropriate in this case.

Figure 2 has examples of non-executable and executable SQL statements that typically occur at the beginning of a program, and it shows return code checking after the executable open statement.

//=== Set SQL Options =================
exec sql set option datfmt=*iso,      
                    closqlcsr=*endmod;
                                       
//=== Cursor ==========================
exec sql declare DemoCursor cursor for 
         select                        
                   PROMO,              
                   FIRST,              
                   LAST                
         from      SQL_DEMOP           
         where     FIRST <= :MyDate    
               and LAST  >= :MyDate    
         order by  PROMO               
     ;                                 
                                       
//=== Initialization ==================
exec sql open  DemoCursor;             
if SQLSTT <> SQLSuccess;               
    SQLProblem('open DemoCursor');     
endif;  

Figure 2: Note SQLSTT not checked when statement is not executable.

When fetching the next row from the cursor, you generally expect to get either a row or an end-of-data indication. The FetchCursor subroutine in Figure 3 returns with one of two values: success and data is available, or no more data. Any other return code is unexpected and routed to the standard error-handling routine. A SELECT...INTO statement would be treated the same way if, as usually is the case, you are expecting only one row to be returned.

//--- FetchCur ------------------------------
// Get the next row from the cursor          
// Returns: SQLSuccess, with data            
//          SQLNoMoreData, no data returned  
begsr FetchCur;                              
exec sql fetch DemoCursor into               
               :MyPromo,                     
               :MyFirst,                     
               :MyLast                       
     ;                                       
if SQLSTT <> SQLSuccess                      
    and SQLSTT <> SQLNoMoreData;             
    SQLProblem('fetch DemoCursor');          
endif;                                       
endsr;

Figure 3: The Fetch subroutine returns only two SQLSTT values.

I then use FetchCur in a simple main program loop, as in Figure 4, confident that SQLSTT is really now a two-valued field.

//=== Main Logic ====================
exsr FetchCur;                       
dow SQLSTT = SQLSuccess;             
    // Program logic here;                     
    exsr FetchCur;                   
enddo;

Figure 4: Use FetchCur in your main program loop.

When I have read all rows from the cursor, I close it, treating the Close Cursor statement the same way as the Open Cursor—only success is acceptable. See Figure 5. This may appear unnecessary, because what can go wrong closing a cursor? So far, I have never had a production problem closing a cursor, but the checking is not a whole lot of code, and during testing it may highlight a logic error if you unintentionally close a cursor you never opened or try to close one twice.

//=== Termination =====================
exec sql close DemoCursor;             
if SQLSTT <> SQLSuccess;               
    SQLProblem('close DemoCursor');    
endif;                                 
*inlr = *on;

Figure 5: Close the Cursor and check for success.

The Standard Error-Handler

The SQLProblem function that takes care of unexpected return codes has appeared in all of the code samples above. What does it do? Due to space constraints, SQLProblem will be covered in a follow-up article. In that TechTip, I will also provide a skeleton program that you can clone to start coding many of your embedded SQL programs.

Sam Lennon is a Systems Analyst and iSeries geek at a major electronics retailer. He has worked on the AS400/iSeries/i5 platform for 16 years and no longer admits to how long he's been writing code.

BLOG COMMENTS POWERED BY DISQUS