I would like to update a table within my db2 database and remove the zeros that are between the alphabetic and numeric values.
For example I have the column element: CompanyName. I would like to get all the CompanyName's that have the zero(s) between alphabetic and numeric values, ie ABCD001234, and replace it with ABCD1234. There are over 30000 of these values, so a script is needed.
Some more examples of the trimming are shown below:
ABCD1234 -> ABCD1234 (no change)
JFKD011011 -> JFKD11011
A000000001 -> A1
Z000000000 -> Z0
Preferably, I would like a script that I can test without the UPDATE, and then add the UPDATE statement after the results look correct.
try this:
select
trim(translate(CompanyName, ' ', '0123456789')) ||
cast(translate(CompanyName, ' ', 'ABCDEFGIJKLMNOPQRSTUVWXYZ') as integer)
from yourtable
Assuming your column is called COL1, in table TABLE1, you can obtain new values as desidered in NEWSTR. From there you can easily prepare the UPDATE:
SELECT COL1, SUBSTR(COL1, 1, ZX)
|| CAST( CAST(SUBSTR(COL1, ZX+1,99) AS INT) AS VARCHAR(18)) AS NEWSTR
FROM
(SELECT COL1, LENGTH(COL1) AS ZY, LENGTH(RTRIM(TRANSLATE(COL1, ' ', '0123456789 '))) AS ZX FROM TABLE1) X
;
To make a test:
SELECT COL1, SUBSTR(COL1, 1, ZX)
|| CAST( CAST(SUBSTR(COL1, ZX+1,99) AS INT) AS VARCHAR(18)) AS NEWSTR
FROM
(SELECT COL1, LENGTH(COL1) AS ZY, LENGTH(RTRIM(TRANSLATE(COL1, ' ', '0123456789 '))) AS ZX FROM
(SELECT 'ABCD1234' AS COL1 FROM sysibm.sysdummy1 UNION ALL SELECT 'JFKD011011' AS COL1 FROM sysibm.sysdummy1
UNION ALL SELECT 'A000000001' AS COL1 FROM sysibm.sysdummy1 UNION ALL SELECT 'Z000000000' AS COL1 FROM sysibm.sysdummy1
) K
) X
Output:
COL1 NEWSTR
---------- ---------
ABCD1234 ABCD1234
JFKD011011 JFKD11011
A000000001 A1
Z000000000 Z0
In MSSQL it should be easier, using PATINDEX() function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.