Reputation: 209
I am currently stuck on concatenating three fields from a table into a single string. These three fields are of different datatypes.
Select
CASE COALESCE(CHAR_COLUMN,'XXX') WHEN 'XXX'
THEN 'CHAR_COLUMN is null'
else 'CHAR_COLUMN='''||CHAR_COLUMN||'''' END
||' and '||
CASE COALESCE(DT_COLUMN,TIMESTAMP('1980-01-01-00.00.00'))
WHEN TIMESTAMP('1980-01-01-00.00.00') THEN 'DT_COLUMN is null'
else 'DT_COLUMN='''||DT_COLUMN||'''' END
||' and '||
CASE COALESCE(NUM_COLUMN,111) WHEN 111
THEN 'NUM_COLUMN is null'
else 'NUM_COLUMN='''||NUM_COLUMN||'''' END
from
S_DATATABLE
This works perfectly fine in DB2/AIX64 9.1.7
but not in DB2 z/OS 10.1.5
.
Error
when ran separately for numeric column
An unexpected token ",111" was found following ",111". Expected tokens may include: "CONCAT || / MICROSECONDS MICROSECOND SECONDS SECOND MINUTES". SQLSTATE=42601
when ran separately for date column
SQL0171N The data type, length or value of the argument for the parameter in position "2" of routine "||" is incorrect. Parameter name: "||". SQLSTATE=42815
Please suggest what changes need to be done for this DB2 version. Thanks in advance.
Upvotes: 0
Views: 1420
Reputation: 19011
First of all, regardless of the DB2 version concatenation requires character operands; you cannot concatenate a string and an integer -- DB2 will attempt to implicitly convert non-character data types to characters. It is best if you do explicit conversion to avoid errors.
Secondly, your SQL seems unnecessarily complex. Instead of
CASE COALESCE(NUM_COLUMN,111)
WHEN 111
THEN 'NUM_COLUMN is null'
else 'NUM_COLUMN='''||NUM_COLUMN||''''
END
you can simply do this:
CASE WHEN NUM_COLUMN IS NULL
THEN 'NUM_COLUMN is null'
ELSE 'NUM_COLUMN='||VARCHAR(NUM_COLUMN)
END
Note that in your original code you compare NUM_COLUMN
with a character literal, which will also cause implicit conversion. Not all DB2 platforms support implicit conversion between all data types, so once again, do not rely on it but use explicit conversion instead.
Upvotes: 4