防止/显示没有结果集的另一种方法

时间:2014-11-05 22:09:44

标签: sql sql-server-2008 rdbms

如果tab1 AND tab2仅返回NO结果,那么我想要 最终选择0,0 ......将被退回。

select tab1.openedcnt, tab2.closedcnt, 'ModuleA' AS Module
from
(select count(*) openedcnt,'constant1' const
WHERE 1=1) tab1
   cross join
(select count(*) closedcnt,'constant2' const
WHERE 1=2 )tab2-- simulating no result set returned
union
select 0,0,'ModuleA'  

结果......

openedcnt   closedcnt   Module
0   0   ModuleA
1   0   ModuleA

我无法摆脱交叉加入。 where语句仅用于此示例。

例如......如果tab1返回结果而tab2没有 然后我希望得到......的结果。

openedcnt   closedcnt   Module
1   0   ModuleA

如果tab1 AND tab2没有返回结果,那么我希望得到......

的结果
openedcnt   closedcnt   Module
0   0   ModuleA

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

嗯。我认为您可以直接使用union allnot exists来执行此操作。这是一个想法:

with tab1 as (
      select count(*) openedcnt, 'constant1' const
      where 1=1
     ),
     tab2 as (
      select count(*) closedcnt, 'constant2' const
      where 1=2
     )
select tab1.*
from tab1
union all
select tab2.*
from tab2
union all
select 0, 0, 'ModuleA'
where not exists (select 1 from tab1) and not exists (select 1 from tab2);

注意使用CTE使查询更容易编写和读取。