23
Sat, Nov
1 New Articles

Practical SQL: Updating a File Using a Cursor

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

SQL isn't just for queries; this article shows you one way to use its update capabilities.

I like to use SQL primarily as a query tool. Its very name—Structured Query Language—sort of leans you in that direction. It's also an excellent tool for set-based updates, as its many proponents will tell you. But there are circumstances under which it would be good to be able to update a file one record at a time via SQL. This is how you do it.

Future-Proofing Your Code

The initial impetus for the concepts in this article came from an ongoing attempt to future-proof the development in a production shop. This shop, like so many, works on a combination of modern programming techniques, including free-format ILE RPG and what can charitably be called long-in-the-tooth packaged code. The goal is to be able to make changes in this code the most productive way possible.

While we've developed processes that allow us to implement changes rapidly, we still run up against one of the most difficult issues in all of RPG development: the dreaded database change. This is a package with thousands of programs, many of which share several major master files. Item master, anyone, or customer order? Transaction history, perhaps? Well, in order to handle database changes in packaged software, you really have only two options: modify the existing database or add extension files. Yes, there are a few other more-involved options, such as converting all existing code to SQL access. Those sorts of architectural overhauls might make sense in a software development shop, but in most production environments, those approaches aren't easy to get approved by the folks who pay the bills. So instead you'll have to choose between modifying the existing files or creating your own extension files.

Modifying Existing Files

Modifying the existing files is difficult, especially in a living, breathing production shop. You can't change the file during normal business operations because every program that has the file open has a lock on it. And it's bad enough in a simple 9-to-5 environment; the complexity simply increases as you throw in multiple shifts and international locations. Pretty soon you get to a spot where you have to set aside a specific window, say two hours in the wee hours on Sunday morning, when the system is unavailable to users. You may be able to schedule that once a week or, in even more complicated cases, once a month. Because of this, a database change requires someone to work in the off hours, installing not only the database changes but also recompiled versions of every affected program. And woe be to you if the database change fails in any way; backing it out is every bit as resource-sensitive, and it's usually an emergency requiring kicking people off during production. This isn't a scenario I recommend.

Creating Extension Files

Enter the extension file. In case you haven’t created one before, an extension file is simply a custom file that you build with the same unique keys as an existing master file. You put all your custom data points in that file. Then, programs that need those data points simply retrieve the appropriate record from the extension file.

When implemented using traditional record-level access (RLA), the extension file suffers from most of the same problems as a normal database file. If you define the file using a traditional F-spec (or a free-format dcl-f statement), the program will lock the file upon startup and hold it until you exit. You can circumvent the lock by using the USROPN keyword on the file definition and opening and closing the file as needed, but even in that scenario, if you change the file, the program will get a level-check error the next time it tries to open the file.

SQL Unbound

SQL provides a real benefit here because of its unbound nature. By that, I mean that SQL works with a more dynamic view of the data than native I/O. The names of the fields are specified in the SQL statement and passed to the SQL engine, which then accesses the data in the file dynamically. If the layout of the table changes, the SQL engine recognizes those changes and processes the new structure accordingly. As long as the changes don't conflict with the basic syntax of the SQL statement, there is no problem.

Now, most people when they think of using SQL to update data think of the traditional SQL UPDATE statement:

      exec sql update ORDEXT

     set OXSTAT = '40' where OXSTAT = '10';

This is a perfectly acceptable way of updating data. Set-based updates are in fact one of the features that SQL evangelists like to point to when they stress the benefits of SQL. And while I agree that updating large numbers of records with a single statement has a certain appeal, it's rare that I have the opportunity to do that. Instead, I typically have to slog through a whole raft of records, testing each case and processing only those that meet certain criteria. Since that selection process often involves multiple files and a lot of conditional logic, it's not very well suited to SQL's version of conditional logic, the adequate but somewhat verbose CASE statement.

That's where the cursor comes in. In RPG's embedded SQL, you can declare a cursor (if you've written an SQLRPGLE program you've almost certainly been down this path). You specify the SELECT criteria and the columns you want to retrieve, and then you loop through the cursor one row at a time using the FETCH NEXT statement.

That's for a read-only cursor. But what if you want to update the data? Well, that only requires one little extra clause on the DECLARE statement and then suddenly you can now update the data as well. Take a look at the following code.

      exec sql declare Orders cursor for

     select OXORDR from ORDEXT where OXSTAT = '10'

        order by OXCUST, OXORDR

        for update of OXSTAT;

     exec sql open Orders;

      dow (1=1);

     exec sql fetch next from Orders into :wOrder;

     if SQLCOD <> *zeros;

        leave;

     endif;

     if Process(wOrder);

        exec sql update ORDEXT

             set OXSTAT = '40' where current of Orders;

     endif;

      enddo;

     exec sql close Orders;

Here I've defined a cursor named Orders, and all that cursor does is retrieve the order number from the extension file. Most of the statement is vanilla SQL syntax, including a WHERE clause and an ORDER BY clause. Note that I use the same condition (OXSTAT = '10') as the original UPDATE clause. But it isn't until the very end that things get a little unusual. The FOR UPDATE clause indicates to the SQL engine not only that the program intends to update the file, but also which field (or fields) we expect it to update.

Next, I use one of my standard programming constructs: an infinite loop using the FETCH NEXT to get the next record; I exit the loop on EOF. But here's where we see a little extra logic. I execute a custom subprocedure called Process, which does some additional processing. If Process is successful, it will return *ON, which will in turn direct the program to execute the UPDATE statement.

And here's the tiny detail that makes all the difference. The UPDATE statement doesn't use a traditional WHERE clause that updates every record in the file in which some field or fields match the selection criteria. Instead, the Process routine adds additional checks, and only if those are passed does it return *ON. But the beauty of this technique is that it will work no matter how much you change the file (with obvious exceptions).

Note that this holds as long as you don't use the dreaded "SELECT *" syntax against the physical table. In another article, I'll spend a little more time on the pros and cons of using data structures and views for your SQL access, but that will have to wait. For now, take your time and see if an updatable cursor might just solve one of your business needs.

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

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: