使用case语句检查SQL表中记录的存在

时间:2019-04-08 21:56:39

标签: sql sql-server database tsql

当服务表中存在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)

2 个答案:

答案 0 :(得分:4)

您的查询将仅返回存在的行,因此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

请注意,最外面的FROM中缺少SELECT子句。编写相同内容的更快方法:

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

答案 1 :(得分:1)

如果外部查询找到数据,则内部CASE WHEN EXISTS 仅得到评估,这就是为什么您永远不会看到“未找到”的原因。

下面的版本不仅更短,而且因为CASE WHEN EXISTS总是被求值,所以它将起作用:

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