我有这个示例临时表。我在SQL服务器中使用COALESCE。我没有权限在Oracle中创建tableS。 Oracle中是否有一个Case语句在SQL Server中作为COALESCE使用?
CREATE TABLE #TEMP
(
ID INT,
FIELD1 VARCHAR (5),
FIELD2 VARCHAR (5),
FIELD3 VARCHAR (5)
)
INSERT INTO #TEMP VALUES('555','CVS','E','CIA')
SELECT
ID,
COALESCE(FIELD1 + '_' + FIELD2 + '_' + FIELD3, FIELD2 + '_' + FIELD1) AS STORE
FROM #TEMP
基本上,我想将查询上方的COALESCE替换为Oracle中的Case语句。
编辑:我确实在Oracle中使用了这个Field1 ||'_' ||Field2||'_'||Field3 AS Store
,但结果为我提供了Field3的额外下划线_
,我不想看到下划线。
答案 0 :(得分:3)
COALESCE(FIELD1 || '_' || FIELD2 || '_' || FIELD3, FIELD2 || '_' || FIELD1)
只会返回第一个词,因为即使所有3个字段都是NULL
,表达式也会评估为__
而不是NULL
。这相当于:
SELECT TRIM(
LEADING '_' FROM
FIELD1
|| NLV2( FIELD2, '_' || FIELD2, NULL )
|| NLV2( FIELD3, '_' || FIELD3, NULL )
)
FROM DUAL;
或
SELECT TRIM(
LEADING '_' FROM
FIELD1
|| CASE WHEN FIELD2 IS NOT NULL THEN '_' || FIELD2 END
|| CASE WHEN FIELD3 IS NOT NULL THEN '_' || FIELD3 END
)
FROM DUAL;
如果您想要反转字段1& 2当字段3为NULL
时:
SELECT TRIM(
BOTH '_' FROM
CASE
WHEN FIELD3 IS NOT NULL
THEN FIELD1
|| CASE WHEN FIELD2 IS NOT NULL THEN '_' || FIELD2 END
|| '_' || FIELD3
ELSE FIELD2 || '_' || FIELD1
END
)
FROM DUAL;