25
Thu, Apr
0 New Articles

What's New with DB2 in V5R2

Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
In V5R2, IBM continues along its path to create a common database across all of its hardware platforms. DB2 Universal Database (UDB) for iSeries V5R2 adds some significant enhancements to this already robust database. In this article, I'll reveal what you can expect with the next release of DB2 UDB for iSeries.

Added SQL Standards Support

One frustration for programmers when moving between different "flavors" of Structured Query Language (SQL) can be dealing with what's not supported in a given SQL implementation. In V5R2, IBM is helping to reduce this frustration on the iSeries by adding support for enhanced SQL standards.

The first of the added SQL functionalities I'll examine is the CREATE TABLE LIKE command. This command allows you to build a new table using an existing table as a template. It also allows you to duplicate not only the record layout for a table, but also the data in the table itself in the same way that you would using the CL command CRTDUPOBJ. The code in Figure 1 would be used to copy data into a new table.

CREATE TABLE Orders2 
LIKE Orders 

Figure 1: The CREATE TABLE LIKE command can be used to duplicate data.


In this example, the new table ORDERS2 will be created in the same format used by the table ORDERS. This functionality can also be used to create a summary file, as shown in Figure 2.

CREATE TABLE SummarySales AS
SELECT cust, period, SUM(sales) AS TotalSales
FROM SalesData
GROUP BY cust, period
WITH DATA

Figure 2: This SQL example will create a summary file.


In this example, the file SummarySales will be created using the fields specified in the SELECT statement. Since this SELECT statement uses the GROUP BY clause and the SUM function, the resulting table will contain a sales summary by customer and period. The WITH DATA clause specifies that you want to copy the data from the source table into the destination table. Alternatively, you could specify WITH NO DATA to only copy the file layout.

Another useful addition to DB2 UDB in V5R2 is the ability to use the UNION clause when creating an SQL view. A UNION allows records to be selected from multiple tables with a common record layout and placed in one results set. Being able to use UNION within a VIEW means that you can now have easy access to data in multiple tables without having to read each table. Figure 3 shows an example of the CREATE VIEW statement using the UNION clause.

CREATE VIEW ALLTRANS AS  
SELECT ITEM, TRNTP, DATE, QTY
      FROM TRAN1999

UNION
SELECT ITEM, TRNTP, DATE, QTY
      FROM TRAN2000

UNION
SELECT ITEM, TRNTP, DATE, QTY
      FROM TRAN2001

Figure 3: The UNION clause can now be used within an SQL VIEW.


This example selects records from the files TRAN1999, TRAN2000, and TRAN2001. The resulting VIEW would display records from each of these tables within a single results set. So rather than reading all the records from TRAN1999, then all the records from TRAN2000, and finally all the records from TRAN2001, you can simply read all of the data from the VIEW ALLTRANS.

Also available in V5R2 of DB2 UDB is the IDENTITY column attribute. IDENTITY allows you to create a field as an auto-incrementing field. For each record created, this value will increment, which is useful anywhere you need a "next-up" number (order numbers, customer numbers, etc.). Figure 4 shows an example of how the IDENTITY column attribute would be used.

CREATE TABLE Orders(
Ordno INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 100, INCREMENT BY 1),
 Cust AS CHAR(10), 
Item AS CHAR(10), 
Qty AS INTEGER
)

Figure 4: IDENTITY columns are auto-incrementing numeric fields.


It's important to note that, while an IDENTITY will automatically increment each time a record is created, this value can be overridden on an INSERT or UPDATE statement if the OVERRIDE clause is used. As a result, the value of the IDENTITY column cannot be guaranteed to be unique unless it is used as part of the primary key or a unique index.

Another addition to V5R2 is the ROWID column. This column can be used to navigate to any row within any table directly. The ROWID value is kept unique even across multiple tables. This 40-byte field contains a unique identifier for each row in each table within your database.

The GLOBAL TEMPORARY TABLE statement is used to create a temporary table that is not registered in the system catalog. The table created can't be processes outside of the one that created it and is automatically deleted when the application ends. GLOBAL TEMPORARY TABLEs are always created in the SESSION schema, which on the iSeries is actually QTEMP library. When combined with the LIKE clause discussed earlier, this statement can be a great help in creating work files within an SQL procedure. Figure 5 contains an example of how this statement is used.

DECLARE GLOBAL TEMPORARY TABLE summary
LIKE sales_summ
ON COMMIT DELETE ROWS

Figure 5: GLOBAL TEMPORARY TABLE can be used for work file creation.


This example will create a temporary table named summary using the same format as the table named sales_summ. When the process that executed this statement is completed, the table will be removed. While the process is active, the temporary table won't be visible to any other applications.

Additions to DB2 UDB for iSeries SQL procedure language--which is used for stored procedures, triggers, and functions--include the ability to use nested compound statements. This means that you can now create multiple levels of BEGIN/END groups within one another. Figure 6 contains an example of how this would look in a stored procedure.

CREATE PROCEDURE CheckCategory... BEGIN DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN SET PrevSQLState=SQLSTATE; SET ErrorState=ErrorOccurred; END; ,,, SET ErrorState=CleanState; SET MyCategory=SELECT Category FROM orders WHERE... ... BEGIN DECLARE CONTINUE HANDLER FOR SQLEXCEPTION... UPDATE inquiries SET inqCount=inqCount+1 WHERE MyCat... END;

Figure 6: Stored Procedures now support nested compound statements.


In addition to nested compound statements, the iSeries SQL procedure language now supports the ITERATE statement, which allows you to skip to the next iteration of a LOOP/END LOOP group. Figure 7 gives an example of this function.

loopa: LOOP
   FETCH crsr INTO orddate, amount;
   IF orddate
      ITERATE loopa;
   END IF;
   INSERT INTO neworders VALUES(orddate, amount);
END LOOP;

Figure 7: The ITERATE statement is used with a LOOP/END LOOP group.


In this example, on each pass through the loop, a record will be read from the cursor crsr. If the value of the field orddate is less than the field startdate, the ITERATE statement is executed to send control back to the start of the loop. Otherwise, the data read is added to the table neworders using the INSERT INTO statement.

Additional enhancements to stored procedure functions include SAVEPOIINTS. This is a means by which a stored procedure can create "bookmarks" within a transaction set. SAVEPOINTS are used along with the ROLLBACK TO statement to allow a stored procedure to roll the transactions back to a specified point. Figure 8 shows an example of the SAVEPOINTS statement.

loopa: LOOP FETCH crsr INTO orddate, amount; IF SQLCODE<0 THEN ROLLBACK TO SAVEPOINT svpt1; ELSE RELEASE svpt1; END IF; IF orddate

Figure 8: SAVEPOINTS allow transactions to be rolled back to a specified point.


In this example, if the SQLCODE value is less than 0, the transactions are rolled back to the previous SAVEPOINT. If not, the SAVEPOINT is released and processing continues. After the execution of the INSERT INTO statement, a new SAVEPOINT is created. DB2 UDB starts new SAVEPOINTS for each function or trigger. You also have the option of starting a new SAVEPOINT level from a procedure. This option is controlled through the use of the OLD SAVEPOINT LEVEL and NEW SAVEPOINT LEVEL statements. If OLD SAVEPOINT LEVEL is specified, a new SAVEPOINT level is not created. If NEW SAVEPOINT LEVEL is used, a new SAVEPOINT level will be created when the procedure is started. The SAVEPOINT names defined are local to the current SAVEPOINT level. Because SAVEPOINTS allow you to roll back transactions to a specific point, the transaction recovery is faster. SAVEPOINTS remain active until a COMMIT, RELEASE, ROLLBACK, or ROLLBACK TO statement is received. The COMMIT ON RETURN option allows you to define whether or a COMMIT should be issued automatically on return from a procedure. Valid values for this option are YES to commit transactions if the procedure successfully returns and NO, which causes no COMMIT.

SQL User Defined Table Functions (UDTF) allow you to create an SQL function that returns a result set. The UDTF can be used anywhere that you would normally use a table. This includes using them as part of view. Figure 9 shows a sample of a User-defined Table Function.

CREATE FUNCTION CustomerSales(Custno CHAR(10)) RETURN TABLE(Item CHAR(15), Perd INT(8), Units INT(10), Sales DEC(15,2)) LANGUAGE SQL RETURN SELECT Item, Perd, Units, Sales FROM SALESHST WHERE SALESHIST.CUST = CustomerSales.Custno

Figure 9: This User Defined Table Function returns sales data.


In this example, the function accepts the field CUSTNO as its only parameter. The results set returned contains data for all values matching the supplied parameter. The following SELECT statement is an example of how you would use this function:

SELECT * FROM CustomerSales('CUS12345');


When this command is executed, the result set returned will contain all records from the SALESHIST table where the CUST field matches the value supplied in the CUSTNO parameter.

UDTFs can also be used with external functions. One important difference when using an external UDTF is that these functions will return only one row at a time. DB2 UDB will internally call the external UDTF multiple times to return subsequent records. External UDTFs support all programs supported by SQL user defined functions. Figure 10 shows an example of how an external UDTF would be defined.

CREATE FUNCTION DOCMATCH (VARCHAR(30), VARCHAR(255))
      RETURNS TABLE (DOCID CHAR(16))
      EXTERNAL NAME 'MYLIB/RAJIV(UDFMATCH)'
      LANGUAGE C
      PARAMETER STYLE DB2SQL
      NO SQL
      DETERMINISTIC
      CARDINALITY 20

Figure 10: External UDTFs use iSeries programs to return data to SQL.


In this example, the DETERMINISTIC option tells DB2 UDB that on subsequent calls using the same parameters, the same data will be returned. The CARDINALITY option is used to define the estimated number of rows that will be returned by the function. This parameter is valid for both external UDTFs and SQL UDTFs.

Scalar Subselect functionality has also been extended to allow a subselect statement to be used anywhere that an expression can be used. This includes being able to use a subselect within the INSERT INTO statement's VALUES clause. Figure 11 shows an example of how a subselect might be used.

SELECT Custno, Cusnam, (SELECT MAX(Orddat) FROM OrdrHdr 
       WHERE OrdrHdr.Custno = CustMast.Custno) AS LastOrd
FROM CustMast

Figure 11: This subselect is used to select the last order date by customer.


In this example, you select the MAX(Orddat) to get the last order date for the current customer. The results would be a customer listing with last order date information.

In another example of IBM's efforts to extend existing SQL functionality in V5R2, ORDER BY clause restrictions have been removed. Prior to this, only fields that were specified in the SELECT list could be included as part of the ORDER BY clause. In V5R2, you'll be able to specify any field in your source tables as part of the ORDER BY clause, regardless of whether or not those tables appear as part of your SELECT list. Figure 12 shows an example of a statement that will be allowed in V5R2 that would not have been allowed in prior releases.

SELECT CUSNAM, CUSADD, CUSCTY, CUSSTE, CUSZIP FROM CUSTMAST ORDER BY CUSNO

Figure 12: The ORDER BY clause is more flexible in V5R2.


In this example, you select the name and address fields from the customer master file and sort the output by the customer number field.

ODBC and JDBC

The additions to the SQL functionality within V5R2 of DB2 UDB for iSeries are only part of the story. There are also several enhancements to the JDBC and ODBC functions. Commonly used SQL catalog views and tables will be available in V5R2, including those listed in Figure 13.

SQLCOLPRIVILEGES & SQLTABLEPRIVILEGES
SQLCOLUMNS
SQLFOREIGNKEYS & SQLPRIMARYKEYS
SQLPROCEDURES & SQLPROCEDURECOLS
SQLSCHEMAS
SQLTABLES
SQLSPECIALCOLUMNS
SQLSTATISTICS
SQLTYPEINFO & SQLUDTS

Figure 13: New SQL catalog tables and views in V5R2.


All of the views will now exist in the SYSIBM library to conform to other ports of DB2 UDB. In addition, enhancements to JDBC include support for JDBC Version 3.0. These enhancements include support for SAVEPOINTS and multiple concurrently open stored procedure result sets. Also added is support for connections and statements pooling within the JDBC Datasource classes. The Java Transaction API (JTA) is now available with full support for the X/Open XA protocol.

ODBC enhancements abound as well, including support for large objects (LOBs) up to 2 GB. The current limit is 15 MB. There are two new ODBC drivers available, one for the 64-bit version of the Windows operating system and the other for Linux clients. Support for the SQLTablePrivileges and SQLColPrivileges views has also been extended. These two functions allow you to define a user's rights to a given table or column within a table.

Software Updates

In addition to all of the changes mentioned so far, there are also updates to some of the software components related to DB2 UDB for iSeries. To start, the DB2 OLAP Miner has been added to DB2 OLAP Server 7.1. This utility adds data mining capabilities to the existing OLAP tool. It uses sophisticated algorithms called "deviation detection" to identify slices within OLAP cube data that deviate from the norm. These values can then be used to drive your OLAP analysis, giving you a more pinpointed way to analyze your OLAP data.

Data migration toolkits have been added as well, including the Oracle Migration Toolkit, which converts data from Oracle into DB2 UDB for iSeries.

Support for integration with the iSeries Linux operating system is also available, including support for connecting to DB2 UDB for iSeries from the Linux LPAR via DB2 Connect software, ODBC, and JDBC.

I hope this has helped to pique your anticipation for the V5R2 version of DB2 UDB for iSeries. For more information, check out the DB2 UDB for iSeries Web site.

Special thanks to Kent Milligan from the DB2 UDB for iSeries Technology Team for helping me get the scoop on what's new in V5R2 for DB2 so that I could share it with you.

Mike Faust is the MIS Manager for The Lehigh Group in Macungie, PA. Mike has nearly 15 years of experience with midrange computers and personal computers. Check out Mike's book "The iSeries & AS/400 Programmer's Guide to Cool Things" available from MC Press.



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: