【问题标题】:Checking existence of a record in a SQL table using case statement使用 case 语句检查 SQL 表中是否存在记录
【发布时间】:2019-04-08 21:56:38
【问题描述】:

下面的查询在服务表中存在 ID 的记录时返回“找到”,但在服务表中不存在记录时不返回“未找到”。我不知道为什么。

select case when  exists (select idaccount from services  where idaccount 
=s.idaccount )
 then 'Found'
 else 'NotFound'  end as GSO  
 from services s 
 where s.idaccount in ( 1421)

【问题讨论】:

  • 记录不存在返回什么?没有行,对吧?
  • 是 没有行返回
  • idaccountt 错字还是您有意引用另一个字段?
  • 是的,这是一个错字,已更正
  • 忽略您的大小写表达。您正在选择行。如果不存在匹配行,则生成空结果集;您的案例表达式没有要评估的内容。

标签: sql sql-server database tsql


【解决方案1】:

如果存在,您的查询只会返回一行,因此 case 语句是多余的,您也可以编写

SELECT 'Found' FROM services s WHERE s.idaccount IN (1421)

虽然意义不大,但您可以编写如下内容:

SELECT CASE
         WHEN EXISTS (SELECT 1 FROM services WHERE idaccount = 1421)
         THEN 'Found'

         ELSE 'NotFound'
       END

注意最外面的SELECT 缺少FROM 子句。更快的方式来写同样的东西:

SELECT COALESCE((SELECT 'Found' FROM services WHERE idaccount = 1421), 'NotFound')

【讨论】:

  • 谢谢你,接受你的回答。
【解决方案2】:

你的内部CASE WHEN EXISTS只有在外部查询找到数据时才会被评估,这就是你永远不会看到“NotFound”的原因。

下面的版本不仅更短,而且它也可以工作,因为CASE WHEN EXISTS 总是被评估:

select case when exists (
        select 1 from services where idaccount = 1421
    )
    then 'Found'
    else 'NotFound' end as GSO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2021-06-18
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多