您可以使用NULLIF
將空字符串變爲NULL
。然後連接NULL
與';'仍然是NULL
,並且可以變成空字符串ISNULL
:
WITH masters (comment1, comment2) AS (
SELECT NULL, NULL UNION ALL
SELECT ' 1', NULL UNION ALL
SELECT NULL, '2 ' UNION ALL
SELECT '3 ', ' 4' UNION ALL
SELECT '' , '' UNION ALL
SELECT ' 5', '' UNION ALL
SELECT '' , '6 ' UNION ALL
SELECT '7 ', ' 8'
)
SELECT
ISNULL(
(
ISNULL(NULLIF(LTRIM(RTRIM(masters.comment1)), '') + ';', '')
+ NULLIF(LTRIM(RTRIM(masters.comment2)), '')
)
, ISNULL(LTRIM(RTRIM(masters.comment1)), '')) Note1
FROM masters;
更新:Jorge Campos有一個很好的,很容易使用CASE
閱讀解決方案:
WITH masters (comment1, comment2) AS (
SELECT NULL, NULL UNION ALL
SELECT ' 1', NULL UNION ALL
SELECT NULL, '2 ' UNION ALL
SELECT '3 ', ' 4' UNION ALL
SELECT '' , '' UNION ALL
SELECT ' 5', '' UNION ALL
SELECT '' , '6 ' UNION ALL
SELECT '7 ', ' 8'
)
SELECT ISNULL(LTRIM(RTRIM(masters.comment1)), '') +
CASE WHEN ISNULL(LTRIM(RTRIM(masters.comment1)), '') <> ''
AND ISNULL(LTRIM(RTRIM(masters.comment2)), '') <> ''
THEN ';'
ELSE ''
END +
ISNULL(LTRIM(RTRIM(masters.comment2)),'') AS Note1
FROM masters;
不知道NULLIF('','')'='NULL'。謝謝! –
如果你比較'ab'='ab',它們也是相等的。不使用LIKE雖然'ab'是'假' –