23
Sat, Nov
1 New Articles

TechTip: Perform SQL Updates Using Multiple Files

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
If you use SQL on the iSeries--either interactively using the Start SQL Interactive Session (STRSQL) command or embedded within other programming languages (/EXEC SQL /END-EXEC)--you already know how powerful this language is. One of the most powerful features of SQL is the ability to update a set of records within a table with a single statement. The shortcoming of the UPDATE statement is that it must be based on a single file, meaning that you can't use a JOIN clause to read data from multiple files to define the conditions or values for the fields to be updated. There is a workaround, however, and this TechTip explains it.

Single File Update

Before I describe how to perform updates using multiple files, take a look at the standard format of the SQL UPDATE statement, as shown in Figure 1.

UPDATE filename 
        SET field1 = value1, field2 = value2 ...
        WHERE condition_field1 = criteria1 
              AND condition_field2 = criteria2

Figure 1: The SQL UPDATE statement is used to modify file data.

Within this statement, filename indicates the file name. This value can be specified as the fully qualified library/filename or library.filename, depending on whether you are using the *SYS or the *SQL naming format. The field1 and field2 values represent the names of fields within your file to be updated. Value1 and value2 indicate the values to be assigned to the respective fields. The condition_fieldx and criteriax values define the criteria used to select the records to be updated.

You'd use the SQL statement shown in Figure 2 to set the value of the field PURGE to 'YES' for all records in which the value of the field ORDATE is less than or equal to 20030101 within the file MYLIB.ORDERS.

UPDATE MYLIB.ORDERS
        SET PURGE = 'YES'
        WHERE ORDATE <= 20030101

Figure 2: This simple update statement updates a single field.

This example will update any records matching your defined criteria with the specified constant value. Many times, however, the criteria cannot be found in the table to be updated. But you can achieve that by using SUB-SELECT.

Criteria Using SUB-SELECT

In cases where the criteria or a portion of the criteria for records to be updated exists within another table, the solution is to replace the criteria value with an SQL SELECT statement. A good example would be when you want to update a value in an order line detail file based on a value from the order header, as shown in Figure 3.

UPDATE MYLIB.ORDLINS
        SET ODPURG = 'YES'
        WHERE ODORDR = (SELECT OHORDR FROM MYLIB.ORDHEAD 
                        WHERE OHORDR=ODORDR AND OHODAT<20030101)

Figure 3: This example uses an embedded SQL statement as part of the criteria.

In this example, the SUB-SELECT will return only records in which the order number field from the two files match and the order date from the header is less than 20030101. The WHERE clause from the UPDATE statement will find a match only for those records returned by the SUB-SELECT shown. The WHERE clause in the SUB-SELECT is able to use values from the file you are updating--in this case, the field ODORDR comes from the file MYLIB.ORDLINS, which is what you're updating. The result is that your update is based on criteria contained in a file other than the file to be updated.

Update Values from a SUB-SELECT

When performing an SQL UPDATE, there are often times when not only a criterion is based on values from another file, but also the value of the field to be updated. A good example would be updating a total quantity on a header record by summarizing the values from the line details. You can do this by using SUB-SELECT in a method similar to that used earlier. Figure 4 shows an example of this type of SQL UPDATE.

UPDATE MYLIB.ORDHEAD
        SET OHOTOT = (SELECT SUM(ODOQTY) FROM MYLIB.ORDLINS   
                      WHERE ODORDR=OHORDR)
        WHERE OHODAT<20030101

Figure 4: This example uses a SUB-SELECT to calculate a field value.

This example uses the SUB-SELECT as the target for the SET clause. When the statement is run, the value of the field ODOQTY in the file ORDLINS will be summarized for all records where the value of ODORDR is equal to the field OHORDR from ORDHEAD (the file to be updated). Again, you use a value from the "primary" file, ORDHEAD, within the WHERE clause of the SUB-SELECT.

It's important to remember that the SUB-SELECT used must return only one value for each record in the file to be updated, meaning that there must be a one-to-one relationship between each record in the file to be updated and the value returned by the SUB-SELECT. If not, you'll get an SQL0811 error stating that the result of the select is more than one row. The same would be true when using the SUB-SELECT as part of the WHERE clause. This is not a problem in this example because the SUM() function summarizes all records within the ODORDR file that match the criteria.

Using Both Methods

My final example combines both methods to use the SUB-SELECT as part of the SET clause and the WHERE clause. This method can be useful when, for example, you want to recalculate an order total in an order header file by summarizing the line details from the order detail file for customers in a specific region based on a value from a customer master file. Figure 5, a modified version of an earlier example, performs this task.

UPDATE MYLIB.ORDHEAD
        SET OHOTOT = (SELECT SUM(ODOQTY) FROM MYLIB.ORDLINS 
                      WHERE ODORDR=OHORDR)
        WHERE OHCUSN=(SELECT CMCUSN FROM MYLIB.CUSTMAST 
                      WHERE CMREGN='NE' AND CMCUSN=OHCUSN)

Figure 5: This example uses SUB-SELECT for both the criteria and the value.

The WHERE clause used in this SQL statement may be a bit confusing at first. The SUB-SELECT statement will return the customer number from the file CUSTMAST for the record where CMCUSN is equal to OHCUSN, only if the value of CMREGN is 'NE'. If this condition is not true, the SUB-SELECT returns a null value, and as a result, the condition WHERE clause will be false. The SUB-SELECT used with the SET clause summarizes the value of the field ODOQTY for all records where the value of the field ODORDR matches the value of OHORDR from ORDHEAD. When this statement is executed, the order total summary will be recalculated for all customers in the region 'NE'.

These examples illustrate how you can use SQL to update data in one file based on values from another. As I've shown, you need to put some careful consideration into each of the SUB-SELECTs used, but this method can be a great time saver when you're performing SQL updates.

Mike Faust is MIS Manager for The Lehigh Group in Macungie, Pennsylvania. Mike is also the author of the books The iSeries and AS/400 Programmer's Guide to Cool Things and Active Server Pages Primer from MC Press. You can contact Mike at This email address is being protected from spambots. You need JavaScript enabled to view it..

Mike Faust

Mike Faust is a senior consultant/analyst for Retail Technologies Corporation in Orlando, Florida. Mike is also the author of the books Active Server Pages Primer, The iSeries and AS/400 Programmer's Guide to Cool Things, JavaScript for the Business Developer, and SQL Built-in Functions and Stored Procedures. You can contact Mike at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Mike Faust available now on the MC Press Bookstore.

Active Server Pages Primer Active Server Pages Primer
Learn how to make the most of ASP while creating a fully functional ASP "shopping cart" application.
List Price $79.00

Now On Sale

JavaScript for the Business Developer JavaScript for the Business Developer
Learn how JavaScript can help you create dynamic business applications with Web browser interfaces.
List Price $44.95

Now On Sale

SQL Built-in Functions and Stored Procedures SQL Built-in Functions and Stored Procedures
Unleash the full power of SQL with these highly useful tools.
List Price $49.95

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: