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

Using CASE to Return a String If No Results From SELECT Statement(如果 SELECT 语句没有结果,则使用 CASE 返回字符串)
本文介绍了如果 SELECT 语句没有结果,则使用 CASE 返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果我的 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';

这篇关于如果 SELECT 语句没有结果,则使用 CASE 返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Number of working days between two dates(两个日期之间的工作日数)
How do I use dateadd to get the first day of last year?(如何使用 dateadd 获取去年的第一天?)
SQL- Count occurrences of a specific word within all stored procedures(SQL- 计算所有存储过程中特定单词的出现次数)
SQL query to make a column of numbers a string(使一列数字成为字符串的 SQL 查询)
T-SQL: Best way to replace NULL with most recent non-null value?(T-SQL:用最新的非空值替换 NULL 的最佳方法?)
Count days in date range with set of exclusions which may overlap(使用一组可能重叠的排除项计算日期范围内的天数)