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

2021-09-10 00:00:00 tsql sql-server-2008 sql-server

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

Is it possible to use CASE to return a certain string if there are no results from my SELECT statement?

示例:

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 来完成我想要实现的目标,但我正在使用第 3 方应用程序并且结果必须采用表格形式(因此仅限 SELECT 语句).

The above does not work since if the account number I am searching for isn't present in my logs table then there would be no results and the message 'We Do Not Have Records For This Customer' would never materialize.
I can do what I am trying to achieve using pure T-SQL with a PRINT command, but I am working with a 3rd party app and the results must be in table form (so SELECT statements only).

推荐答案

你可以使用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';

相关文章