25
Thu, Apr
0 New Articles

Practical SQL: UDFs and Service Programs, Part II

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

With a little creativity, SQL allows you to add a form of overloading to RPG that can really extend your toolkit.

 

In the previous article in this series in this series, I created a simple user-defined function (UDF) that acted as an SQL interface to an RPG service program procedure. It was simple and easy to do, but the emphasis was on simple. The UDF simply passed parameters from the SQL environment straight through to the RPG procedure and returned the result. This is enough in many cases, but at other times, you might want a little more flexibility.

 

For example, you might want some of the parameters to be optional or you might want to hardcode one or more of the parameters. And while this sounds like it might be a job for the *NOPASS parameter on your RPG procedure, as it turns out, that doesn't work in the world of service programs and subprocedures. Instead, you need to take advantage of SQL function signatures, and this article explains how they work.

Recapping and Moving Forward

Let me do a quick recap. In the previous article, I showed you a simple file and then added a record to it. The order number is binary, and the customer is packed (you can look at the other article to get the rest of the file layout). I added a record with order = 314478, customer = 70021, ship-to = 3, and address = 1234 MAIN ST. When I performed a DSPPFM on the file, I saw this:

 

*...+....1....+....2....+...

­­  ö>­ ø      ­­­­­­1234 MAIN ST   

00C607010000FFFF4DCCD4EE4444

04CE002F00031234041950230000

 

If you try, you can make out the customer number in positions 5-8 because the data is packed, but the order number is binary, so the hex values have no discernable relationship to the decimal order number 314478. Because of this, it's really hard to work with alpha fields with embedded binary data. Luckily, we don't have to very often, but there are times when that sort of processing is necessary. In the previous article, I brought up a specific example: looking at journal entries to try to find specific records. I noted that in the OUTFILE of the DSPJRN command, the whole record is stored without any sort of field definitions in the JOESD field; you have to access the individual fields using the substring function (SUBSTR). If you want to parse that data using SQL, it's very hard to work with that embedded numeric data. You can sort of do it with positive packed numbers (using the HEX function and dropping the trailing "F"), but it's impossible to extract the decimal representation of a binary field using traditional SQL techniques. Instead, I wrote a simple routine called UDFHEX2NUM that would take the binary data and convert it back into a usable decimal value. Here's an example of the code:

 

select * from JRNOUT where JOENTT = 'PT'            

  and HEX2NUM(substr(JOESD,1,4),2) between 314000 and 315000

 

It worked quite well. However, one of the problems with writing utility functions is that sometimes in order to make the routine flexible, you need extra parameters and then you have to use those parameters even when they aren't exactly intuitive. If you've used some of the IBM i's APIs you know exactly what I mean; although they're very powerful, the error structures for the APIs aren't intuitive at all. This tradeoff between flexibility and ease of use is even true in the case of my little procedure. It treats the first parameter as either binary or packed data, depending on the value of the second parameter. The second parameter was either 1 or 2, depending on the data being converted, and that means every time you call it, you have to remember whether to use 1 or 2. It's easy to make a mistake, and APIs that encourage mistakes are not good programming. So how do we fix it?

There Are Two Paths You Can Go Down

Sorry, just a little pop culture reference; if you don't remember "Stairway to Heaven," then never mind. But there really are two basic ways to attack the problem. The quickest might be to simply add another service program procedure; have one procedure for converting binary data and another for converting packed data. That's a reasonable option, and relatively straightforward. But this article is centered on the other approach: we're going to create different SQL UDFs, but they will all call the same RPG service program procedure. Once we've created the first two UDFs, we'll see how this approach can allow for even more flexibility. But for now, let me just separate the binary conversion from the packed conversion. It's quite simple. Assume that we have the HEX2NUM UDF shown above and outlined in the other article. I then simply create two more UDFs.

 

First, I'll create the UDF that converts a packed value to a number. The first and only parameter is the hexadecimal data being passed in. All this function does is pass that value to the HEX2NUM UDF along with a literal 1 to indicate that this is packed data.

 

create function PKD2NUM (hexdata varchar(16))

  returns decimal(31, 0)

  language sql deterministic

begin

  return (HEX2NUM(hexData, 1));

end;

 

Next, I create the UDF that converts a packed value to a number. Again, the only parameter is the hexadecimal data being passed in. This function works just like the BIN2NUM UDF, except it passes a literal 2 instead of 1, to indicate that the value being passed in is binary.

 

create function BIN2NUM (hexdata varchar(16))

  returns decimal(31, 0)

  language sql deterministic

begin

  return (HEX2NUM(hexData, 2));

end;

 

So now the developer can either use PKD2NUM or BIN2NUM on the substring. This is easier to remember, simpler to code, less prone to error, and—more importantly—easier to read six months (or six years!) down the road when you're trying to figure out what some piece of code does. Now, younger programmers have probably noted that I still have some serious GORP (Grumpy Old RPG Programmer) tendencies: the names PKD2NUM and BIN2NUM both use three-character abbreviations that probably would be even more readable if they were spelled out, say PackedToNumeric and BinaryToNumeric). One of the really nice things about this technique is that you can use long mixed-cased names here to wrap around short 10-character uppercase-only RPG names. The SQL developers won't even know that those names exist.

A Closing Comment on Polymorphism in SQL

Hey! Where did the ten-cent words get into this? Well, one of the problems I identified in the previous article is that when you're extracting packed decimal numbers from alpha fields, you can't tell the number of decimals from the data. That's something that will have to be specified by the developer. We could add a new parameter to the RPG service program procedure to specify the number of decimals, but then you'd have to remember to specify the number of decimals even if you don't need it, which would be the case for numbers with zero decimal places and pretty much any binary number. Note: theoretically, you can specify binary fields with decimal positions, but I try to avoid that whenever possible. I only use binary data types for true integer data—counts, sequence numbers, order numbers, that sort of thing.

 

But with SQL you can take advantage of the concept of a signature and add a new version of the UDF that includes the number of decimals. The new UDF looks like this:

 

create function PKD2NUM (hexdata varchar(16), decimals int)

  returns decimal(31, 15)

  language sql deterministic

begin

  declare myresult decimal(31,15);

  return (HEX2NUM(hexData, 1) / (10 ** decimals));

end;    

 

If I call PKD2NUM with one parameter, I get the version above, which just calls the service program procedure and returns the results. If I call it with two parameters, I invoke this function instead. The second parameter must be an integer specifying the number of decimals. I call the HEX2NUM procedure and then divide the result of the packed data extraction by 10 to the power of the number of decimals; this effectively moves the decimal point to the left by the number of positions specified in the decimals variable. I can now do this:

 

select PKD2NUM(substr(JOESD,5,4),2) from JRNOUT where JOENTT = 'PT'

 

The result:

                              PKD2NUM

                  700.210000000000036

 

I realize it doesn't make a lot of sense to do this for an order number, but if this were instead a total invoice amount, you can see how this would be helpful. Also, note that because of the size of the fields, I'm seeing some rounding artifacts. This is an ongoing issue with SQL; its default use of floating point numbers isn't always helpful in the world of fixed precision arithmetic. But then again, this wasn't meant to be a treatise on SQL and business logic; it was a way to show you some of the flexibility available when using SQL to invoke service program procedures. I hope this has given you some more insights into SQL; go forth and be functional!

 

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

$0.00 Raised:
$

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: