29
Fri, Nov
0 New Articles

TechTip: Simple Error Handling in Embedded SQL

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

Part of good programming practice is error handling:

  • Was the record found?
  • Does the field contain proper data?
  • Is it possible to add a record?

You know the sort.

The same is true with embedded SQL. Let's review two simple error-handling techniques for your embedded SQL statements.

WHENEVER

The simplest way to monitor for SQL errors is to use the SQL WHENEVER statement:

WHENEVER type action

Type indicates the type of status encountered by the SQL statement. It is one of the following:

  • NOT FOUND--True when the SQL statement finds no data (for example, FETCHing past the end of a result table or no records found for delete)
  • SQLWARNING--True when the SQL statement executes successfully, but with warnings
  • SQLERROR--True when the SQL statement fails

Action tells SQL what to do in case of one of the errors:

  • CONTINUE--Continue with the next statement in your program
  • GOTO (or GO TO) label--Go to a point in the program indicated by "label." In RPG, that would be a label with a TAG; in COBOL, a paragraph or section name.

A WHENEVER statement affects all SQL statements that follow in your program's listing (regardless of program logic), up to a subsequent WHENEVER statement. For any of the three types you do not code a WHENEVER for, SQL assumes an implicit WHENEVER, using an action of CONTINUE.

SQLCODE and SQLSTATE

I don't like WHENEVER because it's too general and it uses outdated and vilified programming constructs--GOTO and TAG. Instead of WHENEVER, I usually use SQLCODE or SQLSTATE.

SQLCODE and SQLSTATE are two fields that you define in your program. SQL sets these fields after every SQL statement executes. They are set to codes indicating the status of the SQL statement.

There are two ways to define SQLCODE and SQLSTATE. The first is to define them individually in your program. SQLCODE is a two-byte integer field (that's 10I 0 for RPG programmers), and SQLSTATE is a five-character alphanumeric field. The second is to bring into your program the special, predefined SQL Communications Area (SQLCA) data structure. This structure contains SQLCODE, SQLSTATE, and a plethora of additional information. You include the SQLCA by issuing the SQL statement INCLUDE SQLCA.

Defining an SQLCA is mutually exclusive from individually defining SQLCODE and SQLSTATE. You can't do both.

If you're an RPG programmer, you don't have to do either; RPG will include SQLCA automatically for you.

SQLCODE

SQLCODE is the easier and more generalized of the two fields. The table below shows how to do simple error handling by checking the values of SQLCODE:

Codes Indicating SQL Statement Status
Value of SQLCODE
Meaning
0
SQL statement executed successfully.
100
SQL statement executed successfully, but no data was found.
Greater than 0
SQL statement executed successfully, but there was a warning.
Less than 0
SQL statement failed to executed.


The neat thing about SQLCODE is that it can be used to get a description of the error message. All of the SQLCODE codes are in a message file called QSQLMSG. The message ID is constructed from the absolute value of SQLCODE:

  • If the absolute value of SQLCODE is four digits or fewer, the message ID is SQLnnnn, with nnnn containing leading zeros if necessary.
  • For five-digit codes, ID is SQnnnnn.

For example, the message corresponding to the SQLCODE of –7008 is SQL7008. The following command will give you the text of SQLCODE -7008:

DSPMSGD SQL7008 QSQLMSG

(Another field in SQLCA, SQLERRM, contains the message's substitution data).

SQLSTATE

SQLSTATE returns a more specific status code. It consists of five characters. The first two characters comprise a code that defines the class of the status' condition.

  • Class '00' indicates a successful execution.
  • Class '01' indicates a successful execution with warnings.
  • Class '02' indicates no data found.
  • All other classes indicate failed executions.

The last three characters give the specific status value.

Each SQLSTATE corresponds with one or more SQLCODEs. For example, SQLSTATE '00000' corresponds with SQLCODE 0, and '02000' corresponds to 100.

SQLSTATE is a DB2 standard across multiple platforms and is probably the best way to monitor your embedded SQL for errors.

GET DIAGNOSTICS

There is a third way to monitor SQL error messages: the GET DIAGNOSTICS statement. However, this statement does much, much more beyond error monitoring, and it's the topic of a future TechTip.

Good Programming Practice

Using either SQLCODE and SQLSTATE, or WHENEVER, allows for simple SQL error monitoring and is good programming practice, right along with the other error monitoring you do.

Useful Links


SQL Messages
SQLSTATE Class Codes
SQLSTATE Values
SQL Message Finder

Doug Eckersley is the iSeries programmer with a premier homebuilder in Columbus. He has been programming on the iSeries for 10 years and has been in the business for 15. He is certified by IBM. He welcomes back his Blue Jackets and is looking forward to the upcoming season.

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: