如果Oracle中的列为null,则从另一个表中提取值

时间:2014-08-12 07:56:17

标签: oracle oracle11g coalesce

我有以下格式的表格(table1)

FN               DESC_TXT       ST_CD
123              Text1             Q
124              (null)            Q
125              Text3             Q
126              Text4             P
127              (null)            Q

我想在ST_CD ='Q'时提取记录,然后如果DESC_TXT是(null) - 我需要检查另一个表(table2)并获取Desc.Another Table Structure is

FN     C_DESC_TXT       
124     Text2
127     Text5

所以我的输出是

FN               DESCRIPTION       
123              Text1             
124              Text2          
125              Text3         
127              Text5

我的代码如下:

SELECT T1.FN, COALESCE(T1.DESC_TXT, T2.C_DESC_TXT) AS DESCRIPTION
FROM table T1
LEFT JOIN table2 T2
ON T1.FN = T2.FN
where T1.ST_CD= 'Q'

然而我收到错误 - ORA-00932: inconsistent datatypes: expected NCHAR got NCLOB

因为我的DESC_TXT是NVARCHAR2而C_DESC_TXT是NCLOB。

当我尝试NVL

SELECT T1.FN, NVL(T1.DESC_TXT, T2.C_DESC_TXT) AS DESCRIPTION
FROM table T1
LEFT JOIN table2 T2
ON T1.FN = T2.FN
where T1.ST_CD= 'Q'

我得到以下错误:

ORA-22835: Buffer too small for CLOB to CHAR or BLOB to RAW conversion (actual: 2506, maximum: 2000)
22835. 00000 -  "Buffer too small for CLOB to CHAR or BLOB to RAW conversion (actual: %s, maximum: %s)"
*Cause:    An attempt was made to convert CLOB to CHAR or BLOB to RAW, where
           the LOB size was bigger than the buffer limit for CHAR and RAW
           types.
           Note that widths are reported in characters if character length
           semantics are in effect for the column, otherwise widths are
           reported in bytes.
*Action:   Do one of the following
           1. Make the LOB smaller before performing the conversion,
           for example, by using SUBSTR on CLOB
           2. Use DBMS_LOB.SUBSTR to convert CLOB to CHAR or BLOB to RAW.

是否有其他方法可以获得所需的输出?

1 个答案:

答案 0 :(得分:1)

您可以使用NVL

SELECT T1.FN, NVL(T1.DESC_TXT, T2.C_DESC_TXT) AS DESCRIPTION
FROM table T1
LEFT JOIN table2 T2
ON T1.FN = T2.FN
where T1.ST_CD= 'Q'

另一种选择是使用DBMS_LOB.SUBSTR将NCLOB转换为VARCHAR2:

SELECT T1.FN, NVL(T1.DESC_TXT, DBMS_LOB.SUBSTR(T2.C_DESC_TXT, 4000, 1)) AS DESCRIPTION
FROM table T1
LEFT JOIN table2 T2
ON T1.FN = T2.FN
where T1.ST_CD= 'Q'

第三种选择是使用DECODE

SELECT T1.FN, DECODE(T1.DESC_TXT, NULL, T2.C_DESC_TXT, T1.DESC_TXT) AS DESCRIPTION
FROM table T1
LEFT JOIN table2 T2
ON T1.FN = T2.FN
where T1.ST_CD= 'Q'