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 返回字符串


基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在多列上分布任意行 2021-01-01