Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeros

Tags:

sql

db2

Given data in a column which look like this:

00001 00
00026 00

I need to use SQL to remove anything after the space and all leading zeros from the values so that the final output will be:

1
26

How can I best do this?

Btw I'm using DB2

like image 473
Bob Avatar asked Dec 22 '22 02:12

Bob


1 Answers

This was tested on DB2 for Linux/Unix/Windows and z/OS.

You can use the LOCATE() function in DB2 to find the character position of the first space in a string, and then send that to SUBSTR() as the end location (minus one) to get only the first number of the string. Casting to INT will get rid of the leading zeros, but if you need it in string form, you can CAST again to CHAR.

SELECT CAST(SUBSTR(col, 1, LOCATE(' ', col) - 1) AS INT)
FROM tab
like image 147
bhamby Avatar answered Dec 26 '22 00:12

bhamby