How can I convert my DECIMAL(11)
field from 12345678
to a character value of 00012345678
?

- 2,047
- 1
- 15
- 33

- 463
- 2
- 8
- 18
10 Answers
Only use the DIGITS
function, because this verifies the length of the field numeric or decimal, etc and completes with zeros to the left when is necessary.
SELECT DIGITS(FIELD) FROM ...
The length of the resulting string is always:
- 5 if the argument is a small integer
- 10 if the argument is a large integer
- 19 if the argument is a big integer
-
You may use `RIGHT()` around it to gain the desired number of digits. – not2savvy May 07 '20 at 13:00
Using http://pic.dhe.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2.doc.sqlref/castsp.htm for details on CAST
and http://pic.dhe.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2z10.doc.sqlref/src/tpc/db2z_scalarfunctionsintro.htm for string functions,
I assume this should do the trick -
SELECT LPAD( CAST(FIELD AS CHAR(11)) ,11,'0') AS PADDEDFIELD

- 5,799
- 4
- 34
- 30
-
-
Well, I tried, not a db2 user :) .... see here too http://stackoverflow.com/questions/4964244/pad-varchar-numbers-with-0s-in-db2 – AjV Jsy Mar 21 '13 at 09:41
-
1
-
Don't know if you've worked it out, however try this:
SELECT LPAD( DIGITS( fieldName ), 11, '0') ) as paddedFieldName FROM yourTable
The LPAD is the left padding, but the DIGITS function was the only way I got DB2 to treat the numeric value like a string.

- 6,131
- 11
- 45
- 51

- 31
- 1
If this is DB2 for i, and myColumn data type is DECIMAL with precision (11) and scale (0), then:
SELECT digits( myColumn ) FROM sysibm.sysdummy1
will return:
....+....1.
DIGITS
00001234567
Changing the number of leading zeros could be done in many ways. CASTing to a different precision before using DIGITS() is one way.

- 2,163
- 11
- 11
My LeftPad function without LeftPad function
REPEAT('0', 4-length(MY_COLUMN_VALUE))||CHAR(MY_COLUMN_VALUE) as NEW_COLUMN
MY_COLUMN_VALUE NEW_COLUMN
1 0004
23 0023
testing ...
SELECT '32' MY_VALUE, REPEAT('0', 4-length('23'))||CHAR('23') as LEFTPAB_MY_VALUE FROM sysibm.sysdummy1

- 3,469
- 1
- 23
- 18
SELECT SUBSTRING(
CHAR(100000000000+fieldName),
2,11
) as paddedFieldName
FROM yourTable
I only wanted to define my field once in the select statement so the above worked for me and is tidy

- 209,280
- 17
- 206
- 263

- 11
- 1
I just went the other direction: cast(field as int)

- 463
- 2
- 8
- 18
-
2What does that have to do with the question? I don't see any need of CASTing to INT. – user2338816 Apr 23 '15 at 08:57
-
1The db2 lpad function appears to be overloaded with integer as the first argument. – danny117 Apr 28 '17 at 15:34
From Numeric 8,0 (datenumfld=20170101) to 01/01/2017
This works for me:
DATE(TO_DATE(CHAR(datenumfld), 'YYYYMMDD')) as YourDate

- 2,711
- 5
- 20
- 41