如果 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 返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)