如果SELECT语句没有结果,则使用CASE返回字符串

时间:2013-02-18 16:48:44

标签: sql-server sql-server-2008 tsql

如果我的SELECT语句没有结果,是否可以使用CASE返回某个字符串?

示例:

DECLARE @accountnumber AS VARCHAR(10)

SET @accountnumber = 'account number to search'

SELECT 
    CASE
    WHEN account IS NOT NULL
    THEN 'We Have Records of this Customer'
    WHEN account IS NULL
    THEN 'We Do Not Have Records For This Customer'
    END AS 'result'
FROM call_records
WHERE account = @accountnumber
GROUP BY account

上述方法不起作用,因为如果我正在搜索的帐号不在我的日志表中,那么就没有结果,并且“我们没有这个客户的记录”的消息永远不会实现。 /> 我可以使用带有PRINT命令的纯T-SQL来实现我想要实现的目标,但我正在使用第三方应用程序,结果必须是表格形式(因此只有SELECT语句)。

2 个答案:

答案 0 :(得分:22)

您可以使用EXISTS

SELECT 
    CASE
    WHEN EXISTS(
        SELECT 1 FROM call_records
        WHERE account = @accountnumber
    ) 
    THEN  'We Have Records of this Customer'
    ELSE  'We Do Not Have Records For This Customer'
    END AS 'result';

答案 1 :(得分:6)

尝试:

DECLARE @accountnumber AS VARCHAR(10)

SET @accountnumber = 'account number to search'

SELECT 
    CASE
    WHEN account IS NOT NULL
    THEN 'We Have Records of this Customer'
    WHEN account IS NULL
    THEN 'We Do Not Have Records For This Customer'
    END AS 'result'
FROM (select 1 dummy) dummy
left join call_records ON account = @accountnumber
GROUP BY account