DB2 Coalesce function is returning nulls

点点圈 提交于 2019-12-13 05:21:00

问题


I am using DB2 for IBM i V6R1, and I am trying to convert a string value which sometimes has a valid representation of a number in it into a number. What I came up with was this:

select onorno, onivrf, coalesce(cast(substr(onivrf,1,5) as numeric),99999) as fred
from oinvol

sometimes the ONIVRF field has data like '00111-11', sometimes it has data like 'FREIGHT'.

The documentation leads me to believe that for data like this:

ONORNO ONIVRF
12     11010-11
13     FREIGHT
14     00125-22

I should get output like this:

ONORNO ONIVRF    FRED
12     11010-11  11010
13     FREIGHT   99999
14     00125-22  125

instead, I am getting this:

ONORNO ONIVRF    FRED
12     11010-11  11010
13     FREIGHT   NULL
14     00125-22  125

(If I skip the coalesce() and just use the Cast(substr(onivrf(1,5) as numeric), I get exactly the same results.)

What am I doing wrong here?


回答1:


If you're just trying to get rid of ONIVRFs that are all alphabetic characters, you can do something like this:

SELECT ONORNO, ONIVRF, 
    CASE 
        WHEN UCASE(SUBSTR(ONIVRF,1,5)) = LCASE(SUBSTR(ONIVRF,1,5)) THEN CAST(SUBSTR(ONIVRF,1,5) AS NUMERIC)
        ELSE 99999
    END AS fred
FROM OINVOL

It's a little hackish, because DB2 doesn't have a ISNUMERIC() equivalent. But alphabetic characters are the only ones that will be translated by the up- and lower-case functions.

I tested this on DB2 for z/OS (v9), and it worked, but I'm not sure if DB2 for iSeries is exactly the same. On mine, it did as @Joe Stefanelli said, and raised an error when it tried to cast an alphabetic string to NUMERIC.

Edit:

This might work better (assuming that you won't have any ONIVRFs that are all tildes). It shouldn't have the problem that @X-Zero mentions where some characters in languages other than English don't have lower and upper-case.

SELECT ONORNO, ONIVRF,
    CASE
        WHEN TRANSLATE(ONIVRF, '~~~~~~~~~~~', '0123456789-') = '~~~~~~~~' THEN CAST(SUBSTR(ONIVRF,1,5) AS NUMERIC)
        ELSE 99999
    END AS fred
FROM OINVOL


来源:https://stackoverflow.com/questions/8526442/db2-coalesce-function-is-returning-nulls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!