使用EXISTS返回1或0作为子查询字段?

时间:2013-11-12 09:16:37

标签: sql

我正在努力想出这个。 我想做的是这样:

select [fields],
       ((select <criteria>) return 0 if no rows returned, return 1 if any rows returned) as SubqueryResult
where a=b

这可能吗?

3 个答案:

答案 0 :(得分:3)

请尝试:

select [fields],
       case when (select COUNT(*) from YourTable with criteria)>0 then 
            1 
       else 
            0 
       end 
       as SubqueryResult
where a=b

答案 1 :(得分:0)

在T-sql中,您可以将给定要求的Exists子句用作:

select [fields],
       case when exists (select <criteria> from <tablename> ) then 1 
            else 0 
            end as SubqueryResult
from <tablename>     
where a=b

答案 2 :(得分:0)

同样在TSQL中,您可以使用ISNULL()SELECT TOP 1

来完成
select [fields],
       ISNULL((SELECT TOP 1 1 FROM YourTable WHERE <criteria> ),0)
       as SubqueryResult
where a=b