27
Sat, Apr
1 New Articles

TechTip: V5R3's New SQL BIFs, Part 3

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

In my past two TechTips, I reviewed 11 of the new built-in SQL functions added to the iSeries implementation of DB2 UDB in V5R3. Now, let's take a look at the 14 remaining new functions. I'll break the functions down into groupings based on the type of values handled by the function.

Date Functions

SQL functions can make dealing with date and time values much easier. The DAYNAME function returns a string containing the mixed-case weekday name for the supplied date. The value supplied on the function's single parameter must be a date, timestamp, or character string representation of a date or timestamp value. The following statement is an example of using the DAYNAME function.

SELECT DAYNAME('2005-05-15 ') 
   FROM SYSIBM.SYSDUMMY1

When executed, this example returns the string "Sunday."

Similarly, the MONTHNAME function returns a mixed-case string containing the month name for the supplied date, timestamp, or string representation of a date or timestamp. The statement below is an example of the MONTHNAME function.

SELECT MONTHNAME('2005-05-15 ') 
   FROM SYSIBM.SYSDUMMY1

When executed this example returns the value "May."

The two functions can be combined to return a "long date format" representation of the date, as shown here.

SELECT DAYNAME(DTEFLD) || ', ' || MONTHNAME(DTEFLD) || 
       ' ' || DAY(DTEFLD) || ', ' || YEAR(DTEFLD) 
       AS  LongDate
   FROM MYLIB.MYFILE

Assuming the value of DTEFLD is a date value representing the date 5/15/2005, this example will return "Sunday, May 15, 2005."

The EXTRACT function retrieves a portion of a specified date, time, or timestamp field. If a date value is specified, valid options for the portion of the time to be retrieved are YEAR, MONTH, and DAY. If a time value is specified, valid options are HOUR, MINUTE, and SECOND. Any of these can be retrieved from a timestamp value. Below are examples of both possible uses of this function.

SELECT EXTRACT(YEAR FROM MYDATE)
   FROM MYLIB.MYFILE
SELECT EXTRACT(MINUTE FROM MYTIME)
   FROM MYLIB.MYFILE

The functionality offered by this function can also be achieved using the YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND built-in functions.

The TIMESTAMP_ISO function returns a timestamp representation of the supplied date, time, or character string representation of a date or time value. The example below illustrates the use of the TIMESTAMP_ISO function with a date value and a time value.

SELECT TIMESTAMP_ISO(DATE('2005-05-15 ')),   
       TIMESTAMP_ISO(TIME('11:30:30 ')) 
   FROM SYSIBM.SYSDUMMY1

Because a timestamp value contains date and time values in one field, the TIMESTAMP_ISO function appends zeros for the time portion of the timestamp when a date value is provided, and it uses the CURRENT DATE value for the date portion of the timestamp if the value provided is a time value. In the case of the example here, the statement will return the values "2005-05-15-00.00.00.000000" and
"2005-05-15-11.30.30.000000," respectively, assuming the statement is executed on 5/15/2005.

String Functions

In V5R3, eight functions have been added for manipulating character string values. Some of these functions convert string data into other data types. Others manipulate the data contained within the string.

A binary string is a sequence of bytes containing the string data. Binary strings always use CCSID 65535. The BINARY function converts a supplied string to another format. It returns a fixed-length binary string version of the supplied character string. The first parameter of the BINARY function defines the string to be converted to binary. This parameter can be any character string value or field. An optional second parameter defines the length of the string in bytes. If the length specified is less than the length of the source string provided, characters will be truncated from the right side of the string. The statement below is a sample of the BINARY function.

SELECT BINARY('This is a BINARY string',10) 
   FROM SYSIBM.SYSDUMMY1                    

Because the length value provided is less than the length of the source string, the value returned by this statement will be "This is a ."

Similarly, the VARBINARY function returns a varying-length binary representation of the supplied character string. The difference between the fixed-length binary string and a varying-length binary string is that the varying-length binary string does not include trailing blanks, while the fixed-length string does. The VARBINARY function accepts the same two parameters as the BINARY function. Below is a sample of the VARBINARY function.

SELECT VARBINARY('This is a VARBINARY string',30) 
   FROM SYSIBM.SYSDUMMY1                    

When executed, this statement returns the full string "This is a VARBINARY string." The difference between the two types becomes evident when determining the length of each string.

The statement below uses the OCTET_LENGTH function to retrieve the length in bytes of the same string as fixed-length and varying-length binary values.

SELECT OCTET_LENGTH(VARBINARY('This is a string',30)) ,
       OCTET_LENGTH(BINARY('This is a string',30))
   FROM SYSIBM.SYSDUMMY1                    

When executed, this statement returns the length of the supplied string minus trailing blanks for the first column and including trailing blanks for the second. In this case, that results in values of 16 and 30, respectively.

While the value returned by the OCTET_LENGTH function is expressed in bytes, the BIT_LENGTH function allows us to retrieve the length of a supplied string or numeric value in bits. Below is a modified version of the previous statement using the BIT_LENGTH function.

SELECT BIT_LENGTH(VARBINARY('This is a string',30)) ,
       BIT_LENGTH(BINARY('This is a string',30))
   FROM SYSIBM.SYSDUMMY1                    

This time, the results are expressed as bits rather than bytes, resulting in values of 128 and 240, respectively. Note that the values returned by this function are equal to the byte length multiplied by 8.

The INSERT function allows us to create a character string that contains the value from a source string after inserting a specified secondary string value at a defined location. Optionally, we can replace a specified number of characters from the source string. The first parameter defines the source string, while the second parameter defines the starting location for string insertion. The third parameter defines the number of characters from the source string to be replaced. If 0 is specified, no characters from the source string are removed. The fourth parameter identifies the value to be inserted. The statement below, for example, inserts the word "not" in the supplied source string.

SELECT INSERT('I am a crook', 6, 0, 'not ')
   FROM SYSIBM.SYSDUMMY1                    

The result of this statement is the value "I am not a crook." If, however, we changed the number of replacement characters defined on parameter 3 and used a different replacement value as shown below, the results would be somewhat different.

SELECT INSERT('I am a crook', 6, 7, 'crooked!')
   FROM SYSIBM.SYSDUMMY1                    

The result of this string would be the value "I am crooked!"

Similarly the REPLACE function is used to create a string that contains a manipulated version of a source string. While the INSERT function inserts or replaces characters at a defined location in the source string, REPLACE searches a source string defined on its first parameter for a search string defined on its second parameter and replaces that value with a replacement string defined on the third parameter. Below is a sample of a statement using the REPLACE function.

SELECT REPLACE('Apple Pie', 'Apple' , 'Cherry')
   FROM SYSIBM.SYSDUMMY1                    

The result of this function is the string "Cherry Pie."

You can also specify a null string as the replacement value to completely remove the search string from source data. The example below illustrates using this function to remove an unwanted character from the source string.

SELECT REPLACE('Orlando,', ',' , '')
   FROM SYSIBM.SYSDUMMY1                    

In this example, the unwanted comma character will be removed, and the result will be "Orlando."

The REPEAT function allows us to create a string that is a repetition of the string supplied on its first parameter the number of times specified on the second parameter. The statement below illustrates the use of this function to create an indentation effect in the resulting string.

SELECT REPLACE('.', INDNT) + ITEM
   FROM MYLIB.MYFILE

This example uses the REPEAT function to insert a number of decimal point characters based on the value of the field INDNT. This string is concatenated with the value of the field ITEM to create an indented item listing as shown in Figure 1.

http://www.mcpressonline.com/articles/images/2002/SQL_tech_tip_3V400--061005.png

Figure 1: Here's the REPEAT function in action. (Click image to enlarge.)

This example shows how a simple bill-of-material structure could be visually illustrated using the REPEAT function.

The RIGHT function operates much the way similar functions work in other languages. This function allows us to extract from the right side of a string supplied on the first parameter a number of characters specified on the second parameter. The statement below is a sample of using the RIGHT function.

SELECT RIGHT(TRIM(CITYST), 2)
   FROM MYLIB.ADDRESSES

This example illustrates the use of the RIGHT function to extract the two rightmost characters from the field CITYST. This field represents a fixed-length character field, so the TRIM function is used to remove trailing blanks prior to extracting the characters. Assuming this field contained a city name and state abbreviation, this statement would return the two-character state abbreviation from the field.

Remaining Functions

The two remaining new functions are not at all similar, but they don't fall into the other categories.

The DATABASE function simply returns the value of the CURRENT SERVER special register. This value will generally be the name of your iSeries database.

SELECT DATABASE()            
   FROM SYSIBM.SYSDUMMY1     

The statement above will return a value that identifies the database to which the current connection is made. This value can be the name of your iSeries or another remote database name if a CONNECT statement has been used to connect to that remote database.

The MULTIPLY_ALT function gives you an alternate method for dealing with the multiplication of large numbers within an SQL statement. This is because of the way SQL deals with decimal places when multiplying two numbers. Basically, an SQL statement adds up the scale of the two numbers being multiplied and uses that value as the scale for the result. So if a decimal with a length of 25 with 10 decimals is multiplied by a decimal with a length of 10 with 5 decimals, the result will be a decimal with a length of 31 with 15 decimals. This will cause an overflow in the result field because the value can't be stored in that field.

This MULTIPLY_ALT function uses a more complex method of calculating the scale for the result value. As a result, this function is less likely to return an overflow value. Below is a sample statement that uses both a standard multiplication operator (*) and the MULTIPLY_ALT function.

SELECT (12345678901234567898989898.99 * 1.00000005),            
  MULTIPLY_ALT(12345678901234567898989898.99 , 1.00000005)   
  FROM SYSIBM/SYSDUMMY1                                           

Note that while we are multiplying the same two values in each column, the first column returns an overflow value (+++++++++++++++++++++++++++++++++++++++) while the second column returns the result 12,345,679,518,518,512,960,718,293.9394. Notice that the resulting value is rounded to four decimal places.

Continuing the Expansion

The set of 25 functions added to SQL in V5R3 shows IBM's commitment to the continued expansion of this language. If, however, you don't see the function you need today, go ahead and write one. User-defined functions are a great way of expanding the SQL language on your own. For more details on this, check out my book SQL Built-In Functions and Stored Procedures from MC Press.

Mike Faust is an application programmer for Fidelity Integrated Financial Solutions in Maitland, Florida. Mike is also the author of the books The iSeries and AS/400 Programmer's Guide to Cool Things and Active Server Pages Primer and SQL Built-In Functions and Stored Procedures. You can contact Mike at This email address is being protected from spambots. You need JavaScript enabled to view it..

Mike Faust

Mike Faust is a senior consultant/analyst for Retail Technologies Corporation in Orlando, Florida. Mike is also the author of the books Active Server Pages Primer, The iSeries and AS/400 Programmer's Guide to Cool Things, JavaScript for the Business Developer, and SQL Built-in Functions and Stored Procedures. You can contact Mike at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Mike Faust available now on the MC Press Bookstore.

Active Server Pages Primer Active Server Pages Primer
Learn how to make the most of ASP while creating a fully functional ASP "shopping cart" application.
List Price $79.00

Now On Sale

JavaScript for the Business Developer JavaScript for the Business Developer
Learn how JavaScript can help you create dynamic business applications with Web browser interfaces.
List Price $44.95

Now On Sale

SQL Built-in Functions and Stored Procedures SQL Built-in Functions and Stored Procedures
Unleash the full power of SQL with these highly useful tools.
List Price $49.95

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: