18
Thu, Jul
2 New Articles

TechTip: Compound Dynamic SQL Statements

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

Dynamic? What's that all about?

 

A lot of new things came out in the IBM i Technology Refresh for 7.1 that was released this past fall. And some of those enhancements have been for DB2, the DDL-based database that's part of the i operating system. The only one of those enhancements that we're going to look at today is the one for Compound Dynamic SQL statements, which were added as part of PTF Group SF99701, Level 26.

A Review: Compound SQL Statements

Compound SQL statements have been part of SQL for quite some time. In short, they allow you to bind a set of SQL statements into a single entity that can then be triggered as a unit.

 

The compound statement starts with a BEGIN statement and ends with an END statement. You can include any executable SQL statement you want into the mix.

 

There are two basic types of compound (and compound dynamic) statements: atomic and non-atomic. And yes, I had the same public safety reaction you are having but don't go mental on me; neither is seriously radioactive. Atomic means that the whole thing is treated like a unit. If something in it blows up, then the whole thing ends and any results are backed out. Non-atomic means that if one statement ends in error, then the compound block will keep going and the next statement will be executed with no back out occurring.

 

Why would you use compound statements? Efficiency mostly. By putting things in this envelope, you reduce overhead on the data manager. And, it also means fewer messages being sent to any remote clients. Plus it's just kind of nice to be able to encapsulate a series of related statements into a pseudo script.

 

But it's not perfect, and if you have something that's going to be executed lots and lots of times, you might be better off putting it in a procedure, which is more efficient still.

Compound Dynamic SQL Statements

The topic of this tip, however, is not compound statements but compound dynamic statements. And this is what has just been added to DB2 with this TR7 PTF. So what is the difference? Dude. They're dynamic. I mean dynamic. Can you dig it, man?

 

First off, dynamic CSes are compiled within SQL as a single statement. This is done outside of the compile for the program as a whole. The system actually creates an ILE C program for this script, named QTEMP/QCMPDnnnnn, where nnnnnn is a sequential number given to the program by Star Fleet Command. This program's existence is only temporary, and after the program is completed it will be automatically deleted.

 

Second, within the statement itself, you can use any of the statements that can be used in a normal compound statement (executable, variables, handlers, For, If, While, etc.). Both non-atomic and atomic are supported, and you can have nested compound dynamic statements. Nesting can be used to help define scope (and so simplify other nesting levels). In other words, you have the power within these statements to make things as complicated and devious as you would like. Parameters, however, cannot be used on a compound dynamic statement. If you need that kind of functionality, you should use global variables instead.

 

Third, how do you kick this thing off? Well, it can be kicked off via any dynamic SQL option, like through Ops Nav or even RUNSQLSMT. Want to run it from inside a program? Then you have to set it up using the PREPARE and EXECUTE statements (this is where the temporary program is created by DB2), but that's another topic. In addition, it can be added to a trigger, an SQL method, or an SQL function.

 

Fourth, even though this results in a compiled program, the word on the street is that it's still more efficient if it's going to be run lots and lots to do this within a stored procedure. It's ideally designed for something that will not be run all that often but could have a lot of data involved.

 

Fifth, no special authority is required to do this, but you have to make sure that the authorization ID of the compound dynamic statement as a whole is sufficient to run every statement in the grouping.

And That's It

And that's it. Except for all of the other stuff. If you want to see the layout of the compound dynamic statement or really understand all the twists and turns involved (like the fact that the options for the SQL variable declaration clause are SQL variable name, data type, array type name, constant, null, or not null), then you should check out the DB2 for i SQL Reference. It's a good read.

 

David Shirey

David Shirey is president of Shirey Consulting Services, providing technical and business consulting services for the IBM i world. Among the services provided are IBM i technical support, including application design and programming services, ERP installation and support, and EDI setup and maintenance. With experience in a wide range of industries (food and beverage to electronics to hard manufacturing to drugs--the legal kind--to medical devices to fulfillment houses) and a wide range of business sizes served (from very large, like Fresh Express, to much smaller, like Labconco), SCS has the knowledge and experience to assist with your technical or business issues. You may contact Dave by email at This email address is being protected from spambots. You need JavaScript enabled to view it. or by phone at (616) 304-2466.


MC Press books written by David Shirey available now on the MC Press Bookstore.

21st Century RPG: /Free, ILE, and MVC 21st Century RPG: /Free, ILE, and MVC
Boost your productivity, modernize your applications, and upgrade your skills with these powerful coding methods.
List Price $69.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: