Using CASE to Return a String If No Results From SELECT Statement(如果 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 返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果 SELECT 语句没有结果,则使用 CASE 返回字符串


- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01