Generating Lots Values From A DB2 Sequence Object

I was working on a Groovy script that inserts lots of data into a database, but I needed to generate a new key from a sequence object and keep track of the old one. So I need to invoke NEXTVAL for each key, but considering how many thousands of records I was inserting, I didn't want to call the database for each key individually.

There's no way to batch up SELECT statements, but I thought I could perhaps generate a big SELECT statement that includes all the keys I needed.

SELECT 1 AS OLD_KEY, MYSEQUENCE.NEXTVAL FROM SYSIBM.SYSDUMMY1
UNION ALL
SELECT 2 AS OLD_KEY, MYSEQUENCE.NEXTVAL FROM SYSIBM.SYSDUMMY1

The problem with this approach is that when you request NEXTVAL multiple times in the same SELECT statement, it returns the same value each time. So I ended up generating one new key assigned to all of my old keys. No good, so I had to try something else. I decided to insert into a GLOBAL TEMPORARY TABLE.

db.execute('''DECLARE GLOBAL TEMPORARY TABLE SESSION.GEN_IDS (
  ORIG_ID DECIMAL(12,0), NEW_ID DECIMAL(12,0)) ON COMMIT PRESERVE ROWS''')

db.withBatch('INSERT INTO SESSION.GEN_IDS VALUES (?, MYSEQ.NEXTVAL)') { 
  BatchingPreparedStatementWrapper ps ->
    oldKeys.each { ps.addBatch(it) }
  }

def mappings = target.rows('SELECT * FROM SESSION.GEN_IDS').collectEntries {
 Map data -> [(data.ORIG_ID) : data.NEW_ID]
}

db.execute('DROP TABLE SESSION.GEN_IDS')

Problem solved. The collectEntries method will create a map for the old and new values. Of course, then I learned about the JDBC getGeneratedKeys method, which makes this approach much less useful, but I'm still glad I learned how to use the GLOBAL TEMPORARY TABLEs.

Accessing Numeric Value Somewhere in a DB2 Column

We recently had some inconsistent data in our database that required a pretty special query. The column contained what should have been a three byte marketing territory number, but depending on what application/user entered the data, the value could be stored almost anywhere in the column, and be 1 to 3 bytes. The following query gets that numeric value.

LPAD(
  TRANSLATE(
    REPLACE(
      TRANSLATE(MISC1_KEY || MISC2_KEY, ' ', X'00'),
    ' ', ''),
  '', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),
3, '0') AS TERRITORY,

The query has four steps, working from the inside out:
  1. Combine the two columns together and replace and null values with a space, X'00' is the hex code for null.
  2. Remove any spaces from the column, originally I wanted to do this with the next TRANSLATE step, but for some reason the spaces seem to be ignored with TRANSLATE
  3. Remove any alpha characters, the column also sometimes contained state abbreviations. It would be nice if we could use something like ^[0..9], but DB2 doesn't support that, and on z/OS it doesn't even support hex ranges. 
  4. Finally pad the number with leading zeros to make it three bytes long. 
It's quite a few steps, but the end result is a consistent three byte code. Especially useful when used with a CTE or a sub-select.

Generate COBOL Copybook Output From DB2 Using JCL

Several of my last few posts have involved data manipulation, and for the most part I've been using Groovy. However, what I really like about Groovy is writing less code, and there are times when other tools, JCL in this case, can help me write even less code.

IBM provides two programs, IKJEFT01 and DSNTIAUL which allows you to pipe the results of a SQL statement into an output stream (SYSPRINT or a flat file). So, assuming that I had a simple COBOL copybook like this.

01 MY-NAME-FILE.
   03 FIRST  PIC X(10).
   03 MIDDLE PIC X(10).
   03 LAST   PIC X(10).

I could easily pipe the first, middle, and last name from a DB2 file into a flat file using an JCL that looked something like this (fill in your DBNAME and PLANNAME values).

//TESTJOB JOB PROD,'USER',CLASS=A,MSGCLASS=V,REGION=0M,
// NOTIFY=&SYSUID                                        
//COLUMNS  EXEC PGM=IKJEFT01                             
//SYSTSPRT DD   SYSOUT=*                                 
//SYSPRINT DD   SYSOUT=*                                 
//SYSUDUMP DD   SYSOUT=*                                 
//SYSREC00 DD   SYSOUT=T01.MYDATASET
//SYSPUNCH DD DUMMY                                      
//SYSTSIN  DD *                                          
DSN SYSTEM(DBNAME)                                         
RUN PROGRAM(DSNTIAUL) PLAN(PLANNAME) PARMS('SQL') -     
    LIB('DBNAME.RUNLIB.LOAD')                           
//SYSIN    DD *                                          
SELECT  LPAD(FIRST_NAME, 10, ' ')
     || LPAD(MIDDLE_NAME, 10, ' ') 
     || LPAD(LAST_NAME, 10, ' ')
FROM MY_NAME_TABLE; 
/*                                                      

Okay, its not the most intuitive, but it is a simple script that can be run as part of a job stream that creates a file compatible with the copybook that I provided above. The SQL concats the three columns together and pads the fields with spaces. The padding may be unnecessary depending on how the columns are defined, but just wanted to get across the point that the records that will be written to the file will be the 30 bytes that match the copybook.

But what happens with a slightly more complex copybook, specifically a copybook involving binary data.

01 MY-NAME-FILE.
   03 FIRST  PIC X(10).
   03 MIDDLE PIC X(10).
   03 LAST   PIC X(10).
   03 ZIP    PIC 9(9) COMP-3.

Yikes! Binary data, how can you format a column in a SELECT statement to produce binary data that could be written to a file. Well, there is the HEX command in DB2, so you could potentially create a binary string and figure out how to convert it, but the IBM programs make it much easier than that. Using the same JCL above, change the SQL to be like this:

//SYSIN    DD *                                          
SELECT FIRST_NAME,
       MIDDLE_NAME,
       LAST_NAME,
       ZIP_CODE,
FROM MY_NAME_TABLE; 
/*    

I'm making an assumption here that the ZIP_CODE field is defined in the database as INTEGER, or DECIMAL(9, 0), because if it is, the default formatting of the data of DSNTIAUL will cause the ZIP_CODE field to be written out as binary data that fits perfectly into PIC 9(9) COMP-3 variable. This is different than the default formatting used by tools on a windows platform, like say Data Studio, but because DSNTIAUL is written to run on a z/OS, it assumes that COBOL datatypes will be used.

If your data isn't defined as binary (COMP), then that actually become trickier, and you might have to do something like REPLACING(CHAR(ZIP_CODE), '.', '') to get rid of that decimal point. I didn't get into that very far, cause the dataset that I needed to produce was using COMP-3 fields for it's numeric data.

Pivot Database Rows Into A Single Column

There are times when a result single record is desired instead of multiple rows, for instance when joining a main table again multiple records in a child table. Say that I have an email and recipients table as follows

EMAILS
--------------------------------------------------
ID | SUBJECT      | EMAIL_TEXT   | SENDER
1  | Great Prices | See circular | AwesomeRetailer 

RECIPIENTS
------------------------
EMAIL_ID | RECEIPIENT
1        | bob@aol.com
1        | al@aol.com



Using a JOIN, you'd get back the following records.

ID | SUBJECT      | EMAIL_TEXT   | SENDER          | RECEIPIENT
1  | Great Prices | See circular | AwesomeRetailer | bob@aol.com
1  | Great Prices | See circular | AwesomeRetailer | al@aol.com

Which gives you all the information you need, but the id, subject, text, and from values are repeated, which means that as you're parsing through the results in Java, you have to 'look back' at the previous value to see if you're processing the same email, or a new one.

Alternatively, you can use the XMLAGG aggregate function to combine the records into a single row. This function will combine data together, then you just have to unpack it to make it into a string using the XMLSERIALIZE function. This approach requires a sub-select, because the XMLAGG function operates off a result set.


SELECT ID,
       SUBJECT,
       EMAIL_TEXT,
       SENDER,
       RTRIM((SELECT CAST(XMLSERIALIZE(XMLAGG(XMLTEXT(ADDR || ';')) AS CLOB)
         AS VARCHAR(500)) FROM RECIPIENTS_TABLE WHERE ID = EMAIL_ID)) AS RECIPIENTS
  FROM EMAILS

results in

ID | SUBJECT      | EMAIL_TEXT   | SENDER          | RECEIPIENTS
1  | Great Prices | See circular | AwesomeRetailer | bob@aol.com; al@aol.com