在没有返回结果时返回字符串的正确方法是什么。 以下不起作用
SELECT
TOP 1 CASE
WHEN
CustomerName IS NULL
THEN
'Unknown'
WHEN
CustomerName = ''
THEN
'Unknown'
ELSE
CustomerName
END
AS
CustomerName FROM CUSTOMER WHERE CustomerCode = 222
答案 0 :(得分:1)
如果您的表格中没有Unknown
的行不是CustomerName
或NULL
,那么您似乎想要返回''
。
SELECT COALESCE((SELECT TOP 1 CustomerName FROM
CUSTOMER WHERE CustomerCode = 222
AND CustomerName IS NOT NULL
AND CustomerName <> ''),'Unknown') CustomerName
答案 1 :(得分:1)
如果我理解了这个问题,即使WHERE子句不匹配,你想要返回一个值,并且你想要&#39; Unknown&#39;替换空字符串或NULL值:
SELECT TOP 1 COALESCE(NULLIF(CustomerName,''),'Unknown')
FROM (
SELECT CustomerName FROM CUSTOMER WHERE CustomerCode = 222
UNION ALL
SELECT NULL
) t
ORDER BY CustomerName DESC
答案 2 :(得分:-1)
试试这可能是它的工作..
SELECT DISTINCT TOP 1 CASE WHEN ISNULL(CustomerName,'') <>'' THEN CustomerName ELSE 'Unknown'
END as CustomerName FROM CUSTOMER WHERE CustomerCode = 222
或
SELECT TOP 1 CustomerName FROM
(SELECT DISTINCT TOP 1 CASE WHEN ISNULL(CustomerName,'') <>'' THEN CustomerName ELSE 'Unknown'
END as CustomerName ,1 No FROM CUSTOMER WHERE CustomerCode = 222
UNION
SELECT 'Unknown',2)
AS T ORDER BY No