IBM Query for AS/400 (a.k.a. Query/400 or Query) is the Clark Kent of the AS/400 world. On the surface, its a mild-mannered report writer that performs light-duty tasks with little fanfare. Its flexibility and usefulness are generally considered limited. Because Query doesnt 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 theres 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). Youve 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 dont 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 thats 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 Ive 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, Im 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!
SUBSTRs 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. Theres 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 its a negative number, or 0 if its 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 theres 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 wasnt 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 buildingand 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 SUBSTRs length parameter.
Figure 4: This equation can be used to change any number to a 1 or 0 for use as a conditional indicator.
LATEST COMMENTS
MC Press Online