23
Mon, Dec
3 New Articles

Practical SQL: Quick Results with VALUES

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

VALUES is an extremely useful shortcut in everything from embedded SQL to your favorite SQL client.

 

SQL provides a wide variety of functions that can be extremely useful to programmers, tasks that might otherwise take many lines of RPG code. ILE RPG has gotten much better at providing some of these base functions and also at making it easy for programmers to write their own function libraries and make them available as service programs, but I always prefer to take advantage of built-in capabilities rather than reinvent the wheel. In this article, I'll show you an easy way to use some of the capabilities of DB2 to do magic in your programs. UCASE, LCASE, MIN, MAX, and other SQL functions provide access to basic programming techniques that simply aren't as easy to do in RPG. The question is how to make those functions available to standard RPG code; the VALUES statement is the key to unlocking that power.

 

SQL Is Great, but It's Not Always Easy to Use

In the past, trying to get something into an RPG program from SQL usually involved a cursor and a FETCH; it just wasn't very convenient. IBM even had to set up a special file, SYSDUMMY1 in library SYSIBM, that had only one record. You could use it in a select statement in order to get a single value:

 

SELECT UCASE(:MYVAR) FROM SYSIBM/SYSDUMMY1

 

This was the way to convert MYVAR to uppercase. However, you still needed a cursor with that select statement, an open, a fetch, and a close:

 

DECLARE C1 CURSOR FOR SELECT UCASE(:MYVAR) FROM SYSIBM/SYSDUMMY1
OPEN C1
FETCH FROM C1 INTO :MYVARU
CLOSE C1

 

This was even uglier back in the pre-freeform RPG days, when each of those needed to be inside of an EXEC SQL and END-EXEC pair. At least now you can simply prefix each line with EXEC SQL. But that's still a lot of work in order to be able to take advantage of a simple SQL scalar function. In fact, there's really no reason not to just roll your own conversion using the old-fashioned technique of defining your own upper- and lowercase alphabet variables and then using the %XLATE function:

 

dcl-c UP 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
dcl-c LO 'abcdefghijklmnopqrstuvwxyz';

MVARU = %xlate(LO:UP:MYVAR);

 

VALUES to the Rescue!

What would make it easier? The answer is a relatively unknown but phenomenally flexible capability, the VALUES statement. VALUES is really the SQL shorthand for "evaluate this and return it." The key to that statement is the phrase "return it" because VALUES is eminently flexible in what it returns. Let's start with our situation above, where we want to take advantage of the UCASE scalar function. Here's the way we do it in freeform ILE RPG using VALUES:

 

EXEC SQL VALUES UCASE(:MYVAR) INTO :MYVARU;

 

Boom! That's it! It only takes a single line of code to call an SQL function to convert MYVAR to uppercase. At this point, it's even easier than the XLATE; no need to define your own alphabet variables! One minor caveat: I haven't done any timing analysis, and I suspect the call to SQL might be a bit slower than the equivalent XLATE function, but at the same time I would guess that the UCASE is probably smarter, especially about things like language differences. So the tradeoff is probably OK unless you're processing millions of transactions in a batch process.

 

And of course that's just one SQL function. DB2 has dozens of scalar functions available that provide capabilities not readily available in ILE RPG. One of my favorites is MAX. MAX returns the maximum value of an arbitrary list of variables, and MIN returns the minimum. How many times have you needed to compute a value but make sure it doesn't go over a limit?

 

EXEC SQL VALUES MIN( (COST*QTY), 9999999.99) INTO :LINECOST;

 

LINECOST will now contain the value of COST time QTY not to exceed 9999999.99 total dollars. This is especially important nowadays when you're dealing with ILE RPG and the fact that overflowing a variable causes a halt in the program. You can see where this might come in handy. I've had to write routines where I pass a value into a function that checks its range before updating another variable; the generic version of that function takes a little doing. And there are many other scalar functions available to do everything from string handling to advanced mathematics (ACOS, anyone?) to advanced XML handling.

 

VALUES Isn't Limited to Scalars

You could probably argue that, for most scalar functions, you could write a comparable ILE RPG routine and make it available via a service program. That's true, although, as I've noted, making those routines generic takes a little careful planning. Still, it's not out of the range of most of us, especially when we have the C libraries available for so many functions (especially the higher math). But using VALUES for scalars is only scratching the surface of this feature. VALUES is just as at home computing aggregate values, and that can come in very handy. Want to know the highest order number?

 

EXEC SQL VALUES (SELECT MAX(OHORD) FROM ORDHDR) INTO :MAXORDER;

 

That's it. There's your highest order number. Want to know the number of orders for a customer?

 

EXEC SQL VALUES (SELECT COUNT(*) FROM ORDHDR WHERE OHCUST = :MYCUST) INTO :NUMORDERS;

 

Pretty much anything you can SELECT using an SQL statement you can get into a variable just by using the equivalent VALUES statement. It's that simple. The beauty, I think, is that the SQLRPGLE preprocessor makes it so easy to integrate variables from your program directly into the SQL statements; it's as if SQL syntax is just an extension of RPG now. I'm currently trying to get versed in the XML functions; DB2 includes a wonderfully powerful XSLTRANSLATE function that can convert XML to other formats, which can be a quick way to create PDF documents in RPG. I'll write about that in a future article. Version 7.2 added regular expression processing as well.

 

DB2 also has a number of functions that make it uniquely suited for the IBM ecosystemfor example, the various MQ functions. Using these, you can send and receive messages directly to an MQSeries queue, which can in turn easily send that data to other systems in your network. It's a quick and powerful way to provide MQSeries connectivity to your RPG programs (and a lot easier than calling the MQSeries APIs yourself!). With the VALUES clause, you can simply do this to talk to another machine:

 

EXEC SQL VALUES (MQREAD('MYSERVICE')) INTO :MESSAGE;

 

It doesn't get a lot simpler than that!

 

So acquaint yourself with the VALUES statement and learn to use it in your RPG programs. As time goes on, I'll give you more examples of how to use DB2's functions to enhance your RPG programs.

 

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: