27
Wed, Nov
0 New Articles

TechTip: SQLCOD End-of-File Gotcha

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

More developers are using embedded SQL in their applications, and some treat the SQLCOD return value as a two-valued field, just like the on/off end-of-file indicator in native file access. In this article, I want to show you that treating SQLCOD like an on/off indicator can be dangerous.

Have you ever written code like this?

exsr FetchCursor;
dow SQLCOD = 0;  // process until no more data
    your processing here;
    exsr FetchCursor;
enddo;

This construction is based on the assumption that after you fetch a row from a cursor, SQLCOD will contain either zero, meaning a row was fetched successfully, or 100, meaning that there are no more rows to return. Most of the time this construction works, but there are exceptions. When an exception occurs, your program may not crash, but it may fail to process all the rows you intended to process.

A Simple Embedded SQL Program

To demonstrate why you need additional checking, I have contrived a stripped-down application that might exist in a retail organization. The database has a table that contains the promotion number (PROMO), the first day the promo is active (FIRST), and the last day the promo is active (LAST). Table SQL_DEMOP has only a few rows, and a query over the table, ordered by First, shows data like this:

PROMO   FIRST       LAST       
  124   2007-01-01  2007-01-03 
  178   2007-03-01  2007-03-31 
  326   2007-08-01  2007-08-01 
  923   2007-11-01  2007-11-30 
  401   2007-11-19  2007-11-29 
  403   2007-11-23  2007-11-25 
  701   2007-12-25  2007-12-25 

Application program SQL_DEMOR (Figure 1), lists all the promos that are active on a given date, in promo order. It employs the DOW SQLCOD = 0 construction, and I created it with the CRTSQLRPGI command, taking the IBM-supplied defaults.

h indent('| ')                                           
FQPRINT    O    F  132        PRINTER Oflind(*INOV)      
d MyFirst         s               d                      
d MyLast          s               d                      
d MyPromo         s              5  0                    
d MyDate          s               d   Inz(d'2007-11-23') 
                                                         
c/exec sql declare DemoCursor cursor for                 
c+          select                                       
c+                    PROMO,                             
c+                    FIRST,                             
c+                    LAST                               
c+          from      SQL_DEMOP                          
c+          where     FIRST <= :MyDate                   
c+                and LAST  >= :MyDate                   
c+          order by  PROMO                              
c/end-exec                                               
                                                         
c/exec sql          open  DemoCursor                     
c/end-exec                                               
c                   exsr      FetchCursor                
                                                         
c                   dow       SQLCOD = 0                 
c                   except    PrintLine                  
c                   exsr      FetchCursor                
c                   enddo                                
                                                         
c/exec sql          close DemoCursor                     
c/end-exec                                               
c                   eval      *inlr = *on                
                                                         
c     FetchCursor   begsr                                
c/exec sql          fetch DemoCursor into                
c+                        :MyPromo,                      
c+                        :MyFirst,                      
c+                        :MyLast                        
c/end-exec                                               
c                   endsr                                
                                                         
OQPRINT    E            PrintLine   1                    
O                       MyPromo       J     +1           
O                       MyFirst             +1           
O                       MyLast              +1           

Figure 1: This is the original source for SQL_DEMOR.

To keep the code simple, I hard-coded a search date of November 23, 2007, in the program. When I run SQL_DEMOR, I get a list like this, correctly showing the three promos in effect on November 23, 2007:

401  2007-11-19 2007-11-29 
403  2007-11-23 2007-11-25 
923  2007-11-01 2007-11-30

Add More, Get Less

Suppose the creative folk in advertising create promo 555 and on November 19 decree it "to be in effect immediately and to remain in effect until further notice." The data entry folk key it with a first day of 2007-11-19, but since they weren't given an end date and are fed up with the imprecise instructions they constantly get from advertising, they use a date way, way, way in the future, 2099-12-31.

A query over the table, again ordered by First, now gives data like this:

PROMO   FIRST       LAST      
  124   2007-01-01  2007-01-03
  178   2007-03-01  2007-03-31
  326   2007-08-01  2007-08-01
  923   2007-11-01  2007-11-30
  401   2007-11-19  2007-11-29
  555   2007-11-19  2099-12-31
  403   2007-11-23  2007-11-25
  701   2007-12-25  2007-12-25

Clearly, promo 555 is in effect on November 23, 2007, but if I run SQL_DEMOR again, promo 555 does not show up. In fact, now it lists only two promos! I get this:

401  2007-11-19 2007-11-29 
403  2007-11-23 2007-11-25

Not only is promo 555 missing, but promo 923 has also disappeared!

This is a contrived application, but it could bear some resemblance to the real world. What would have happened if the advertising department had put out a holiday season flyer that featured promo 555, but your program hadn't told the point of sales system about it? You would have some irate customers and some equally irate sales staff who had to explain to the irate customers why the promo discount was not ringing up at the cash register.

SQL_DEMOR did not crash, but it gave wrong results. Before reading further, can you figure out why?

SQLCOD = Minus 181?

When I look in the job log, I find an SQL0181 diagnostic message, telling me that a value in a date, time, or timestamp string is not valid. SQL_DEMOR was created with the default IBM CRTSQLRPGI command, which defaults to DATFMT(*JOB). In my shop, and probably in most shops in the United States, the job date default is *MDY. This tells the compiler that only dates between 1940-01-01 and 2039-12-31 are valid in this program. SQL_DEMOR works as long as there are no dates outside this range, so it receives an SQLCOD value of -181 when it encounters the 2099 date. As written, the program then thinks it has processed the last row in the cursor and ends normally.

The Fix

There are two remarkably easy fixes specific to this program.

You can recompile the program specifying DATFMT(*ISO) on the CRTSQLRPGI command. Or, if you're afraid you'll forget this option when you next compile the program or put it into production (and you know you will), instead add this to the code:

set option datfmt=*iso

Figure 2 shows the revised source.

h indent('| ')                                           
FQPRINT    O    F  132        PRINTER Oflind(*INOV)      
d MyFirst         s               d                      
d MyLast          s               d                      
d MyPromo         s              5  0                    
d MyDate          s               d   Inz(d'2007-11-23') 
                                                         
c/exec sql                                               
c+  set option datfmt=*iso                               
c/end-exec                                               
                                                         
c/exec sql declare DemoCursor cursor for                 
c+          select                                       

Figure 2: This is the beginning of the revised source for SQL_DEMOR.

Is It the Right Fix?

I do not consider either of the above fixes robust coding techniques for handling SQL return codes. Granted, either one solves the immediate date-handling issue, but the program is still treating SQLCOD as a two-value field. The original version of SQL_DEMOR demonstrated that SQLCOD can have at least a third value we didn't know about, and who knows what other values will turn up that will give a false end-of-data indication?

There are way more than three positive SQLCOD values documented by IBM in the iSeries Information Center, though many will never occur when reading through a cursor. The ones you are most likely to encounter relate to date and time stamps, truncation of string data if your host variable is too short, and conversion between database and host variable data types.

In a follow-up article, I will show a better technique using SQLSTT instead of SQLCOD. I will provide with it a template program with more robust error-checking, which you can use as a skeleton for many of your embedded SQL programs.

Downloadable Source

If you want to experiment, you can download the code from this article from the MC Press Web site. Included is the source of both versions of SQL_DEMOR, an SQL script to create and load table (file) SQL_DEMOP, and an SQL script to insert a record that causes the first version of SQL_DEMOR to fail.

Sam Lennon is a Systems Analyst and iSeries geek at a major electronics retailer. He has worked on the AS/400/iSeries/System i platform for 16 years and no longer admits to how long he's been writing code. You may reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..

Sam Lennon

Sam Lennon is an analyst, developer, consultant and IBM i geek. He started his programming career in 360 assembly language on IBM mainframes, but moved to the AS400 platform in 1991 and has been an AS400/iSeries/i5/IBM i advocate ever since.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: