Sidebar

The Hidden Power of Query, Part 1

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

IBM Query for AS/400 (a.k.a. Query/400 or Query) is the Clark Kent of the AS/400 world. On the surface, it’s a mild-mannered report writer that performs light-duty tasks with little fanfare. Its flexibility and usefulness are generally considered limited. Because Query doesn’t include built-in functions to translate a field into something else or allow users to set conditions and report in different ways based on the data, many companies look to more robust report writers to take on these challenging tasks.

But there’s a lot more to this tool than many people realize. Behind the humble façade is a powerful data formatter. The basic mathematical and character substring options available in Query can be combined like building blocks to perform much more complex logic.

Do you need to extract and reorganize numbers and character strings? Do you have to print text in only certain conditions? Those look like jobs for...Query!

Integer Division

One simple Query building block is integer division. Say you have an integer field that contains 18. If you define a result field with zero decimal places and set it to the integer field divided by 10, your new field is 2 (because Query will round 1.8 up to 2 by default). However, under integer division, the result is truncated, not rounded, yielding a value of 1 instead. In other words, the result field will always be the “tens” digit.

Integer division is made possible by setting Use Rounding to N in the Specify Processing Options panel.

This ability to extract numbers without having to change data type to character is very useful. You can change the positions of the numbers but still be able to perform arithmetic functions on the result. Take an integer date, for instance 19991231. Define a zero-decimal field called TEMP1 that will hold the date divided by 10,000. This gives you
1999. Divide this by 100 with another field called TEMP2, which will then contain 19. The two-digit year can then be extrapo-lated with a defined field that takes (TEMP1 - TEMP2 *
100). You’ve pulled out the 99, but kept it as an integer, so you can use it for other duration calculations.

In addition to parsing numeric data, the numbers can be concatenated together in different order while still maintaining their data type. For instance, if you want the integer


date 19991231 to appear as the number 123199, just apply the same logic on a slightly larger scale, as seen in Figure 1.

String Manipulation

If maintaining numeric data type is not an issue, an easy way to extract and reformat information is to use the SUBSTR and Concatenate (||) functions. SUBSTR(field, starting position, length) extracts characters, so if PARTNO = “12-456A,” SUBSTR(PARTNO,7,1) will be “A.” Concatenate attaches character strings together, so a field called REV can be defined as “REVISION “ || SUBSTR(PARTNO,7,1), which will become the string “REVISION A.”

However, SUBSTR parameters don’t have to be static fields, and type conversion can be embedded in the SUBSTR function. Using the integer DATFLD of 19991231 from the previous example, SUBSTR(DIGITS(DATFLD),5,2) produces the string “12.”

The starting position index can be dynamic as well, so if a field called DAYNUM is set to 7, SUBSTR(DIGITS(DATFLD),DAYNUM,2) produces the string “31.”

DAYNUM could also be a mathematical equation or anything else that results in a positive integer. This feature turns out to be another simple building block with hidden potential.

Data Translation

In many customized reports, the information that’s retrieved directly from the database is not in a form that the user can easily understand. If there were a way to decipher the raw data into more detailed messages, the report could be more user-friendly. Using the tools I’ve covered this far, Query can handle this type of data translation.

A character-type result field can act as a conversion table, and the integer division and SUBSTR functions can be used to extract elements from this table. Figure 2 (page
109) demonstrates how to print the word EVEN or ODD based on any given number. Integer division is applied to get the low-order digit, which is used to calculate a starting position in a conversion string. By padding each table entry with trailing blanks so there is a consistent element size, SUBSTR can print a status of the original number.

Data field translation has many other uses on reports. Dates become more meaningful as a 2 becomes FEBRUARY or a 7 becomes SATURDAY. Cryptic database codes spring to life as an error 12 is decoded into NO STOCKROOM ASSIGNED or a status code 4 now prints as NOT YET INVOICED. Higher-order digits can be translated in a way similar to the example in Figure 2, so it becomes possible to print 25 as TWENTY- FIVE.

You can even set the index to be based on the current time to print a different message each time your report is run.

SUBSTR(TABLE,SECOND(CURRENT(TIME))*10+1,10)

Though powerful, I’m not sure how often this particular use will come in handy. Although, when concatenated with data from other defined tables that are indexed using the current microsecond, Query becomes an amusing random rumor generator!

SUBSTR’s length parameter can be a dynamic variable as well, so users can retrieve different size elements from the same table. It takes a few extra defined fields to tell Query about the starting position and length of each table element, but when this is done, reports have a much more natural look. For instance, go back to the suggestion of printing the month name based on a given date. Using 10-character fixed-length elements in your table means that 9/30 would print as “September 30,” but 5/30 would print as “May 30.” The extra seven spaces padding the end of May can be cleaned up using a method outlined in Figure 3.


Start with a table that lists all the month names back-to-back. Include a second table that lists the 2-digit starting position of each month name in the first table (JANUARY starts in table position 1, FEBRUARY starts in position 8, etc.), and a third table to define the length of each month name (JANUARY is 7 characters long, FEBRUARY is 8, etc.) The month is extracted from a data field using integer division. This number can then be used as an index to look up information across the multiple tables.

The starting position and length values are extracted from the tables in character form. One method of converting them to integer so they can be used by SUBSTR to index the main table is to use the MICROSECOND function. Appending any numeric character to the end of a time stamp string and then extracting the integer with MICROSECOND is a neat little trick that comes in handy in all kinds of situations.

In the Figure 3 example using 1000530 as an input date, the month (5) is used to extract a starting position (26) and string length (3). Once these parameters are set, a single call to SUBSTR(TABLE,26,3) will pull out the characters “MAY” without trailing blanks.

When creating a table of text that exceeds the space provided in the Define Result Field, simply break the table into multiple result fields and concatenate them all together into one final table using the || function. Query/400 allows a Result Field to be up to 32,766 characters long.

Conditional Logic

One of the most common reasons for dismissing Query as limited is the fact that no conditional logic is available. There’s no If-Then-Else function to let the report choose what data to print or to print only in certain cases. Again, using the simple techniques I described, users can set a Boolean indicator by generating a 1 or 0 based on a numeric field. This indicator can then be multiplied by other fields to effectively turn them on (NUM * 1 = NUM) or off (NUM * 0 = 0).

The DIGITS() function is a good example. When given a number, DIGITS converts the number to character. When given a negative number, it converts it to character, but the sign is dropped. This is usually an important tidbit of information that should be kept with the original number. Get it back by setting a Boolean indicator.

Figure 4 shows how to break down a number into 1 if it’s a negative number, or 0 if it’s positive.

The formula is (X - 0.001)^2 / (X^2 + 0.00001). By subtracting a small amount from the numerator before squaring, the result is just over 1.0 if the original number is negative. Otherwise the result is just under 1.0. Adding 0.00001 to the denominator makes sure that there’s never a divide-by-zero error condition. By placing the result in a zero- decimal field and suppressing the rounding function, the on/off switch is set.

With this integer variable called RESULT that tells you if your number is positive or negative, SUBSTR can use it as an index. Define a 2-character result field called SIGN, set to “ -” (blank, dash). Then when you convert any number to character, use the following to append either a blank or a negative sign onto your converted number.

DIGITS(NUMBER) || SUBSTR(SIGN,RESULT+1,1)

This example sets the Boolean indicator by comparing a single number to zero, but you can really use any two numbers. Take the difference between two numbers, DIFF = A - B. If you run DIFF through the formula, the RESULT will be 0 if A is greater than B or 1 if A is less than or equal to B. The value can be used to calculate a dynamic SUBSTR index or as a multiplication factor to manipulate other numeric fields. Now your report can produce different output depending on the comparison of the original numbers. For an example, see “Query/400 Finds the Larger of Two Numbers” in September 2000
“TechTalk.”

You thought Query wasn’t that super!


Scratching the Surface

This is just an introduction to see through to the hidden power and flexibility of Query.

Query can do a lot more with just the basic set of available functions. Calculating duration using numeric dates (so 991201 - 991130 equals 1 day and not the mathematical value of 71) and using file join and output reporting options to recursively search a tree- structure were once thought to be beyond the scope of the software. These and other building block techniques will be explored in future articles. With enough building blocks, you can make a tall building—and Query can leap it in a single bound.

If your integer date field "DATFLD" contains 19991231:

Define Field Size Decimals Definition Value

CYM 6 0 DATFLD / 100 199912 CYM00 8 0 CYM * 100 19991200 DD 2 0 DATFLD - CYM00 31
CY 4 0 CYM / 100 1999
MM 2 0 CYM - (CY * 100) 12
C 2 0 CY / 100 19
YY 2 0 CY - (C * 100) 99 NEWDATE 7 0 (MM * 10000) 123199

+ (DD * 100) + YY

Field Expression Len Dec

TEXT ‘EVENODD EVENODD EVENODD EVENODD EVENODD’ TEMP1 input / 10 4 0 INDEX input - (temp * 10) 1 0 TEMP2 ubstr(text,index*4+1,4)

Result: 12345 translates to the string “ODD“

Figure 1: Numeric data can be reformatted without changing the data type.

Figure 2: You can define a text field as a table and substring individual elements.


GIVEN THE INTEGER DATE 1000530: Field Expression Len Dec Description TABLE 'JANUARYFEBRUARYMARCHAPRILMAYJUNE Data elements of various size

JULYAUGUSTSEPTEMBEROCTOBERNOVEMBE RDECEMBER'

POSITION '010816212629333743525967' Starting position of each element SIZE '785534469788' Character length of each element CYYMM DATFLD / 100 5 0 Date variable (Ex: 10005)

CYY DATFLD / 10000 3 0 Date variable (Ex: 100) MONTH CYYMM - (CYY * 100) 2 0 Date variable (Ex: 5) YEAR 1900 + CYY 4 0 Date variable (Ex: 2000) START_CHAR SUBSTR(POSITION,MONTH*2-1,2) Start position of Month (Ex: 26) LEN_CHAR SUBSTR(SIZE,MONTH,1) Character length of Month (Ex: '3') START MICROSECOND(TIMESTAMP('2000-01-01 Convert Character to Number

-00.00.00.0000'||START_CHAR)) LENGTH MICROSECOND(TIMESTAMP('2000-01-01 Convert Character to Number

-00.00.00.00000'||LEN_CHAR)) LABEL SUBSTR(TABLE,START,LENGTH)||' '|| Produce "MAY 30, 2000" from

SUBSTR(DIGITS(DATFLD),6,2)||', ' the number 1000530 ||DIGITS(YEAR) (NUMBER - 0.001)^2

(NUMBER^2) + 0.00001

When NUMBER < 0, RESULT = 1 When NUMBER >= 0, RESULT = 0

Field Len Dec Expression

NUMER 15 5 (NUMBER - 0.001) * (NUMBER - 0.001) DENOM 15 5 (NUMBER * NUMBER) + 0.00001 RESULT 1 0 NUMER / DENOM

Figure 3: Text strings of different sizes can be handled by varying SUBSTR’s length parameter.

Figure 4: This equation can be used to change any number to a 1 or 0 for use as a conditional indicator.


BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

RESOURCE CENTER

  • WHITE PAPERS

  • WEBCAST

  • TRIAL SOFTWARE

  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things


    Read Node.js for Enterprise IBM i Modernization Now!

     

  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!

     

  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.

     

  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline

     

     

  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.

     

  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact

     

  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using NodeRun.com as a pre-built development environment

     

     

  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.

     

     

  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.

     

     

  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails

     

  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.

     

     

  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave 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.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY 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.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.