Oracle:有条件地在WITH子句中运行SELECT

问题描述 投票:0回答:1

我们有一个相当冗长的存储过程(Oracle 12),它包含一系列以这种方式相互构建的WITH子句:

WITH temp1 AS (SELECT ... FROM tableA WHERE ...),
WITH temp2 AS (SELECT ... FROM temp1, tableB WHERE ...),
WITH temp3 AS (SELECT ... FROM temp2, tableC WHERE ...),

从temp3实体完成最后的SELECT

SELECT ... FROM temp3;

这可行,但最近我们被要求'bookend'最终选择,以便它有一个虚拟的第一行和一个虚拟的最后一行。即如果'temp3'包含三行,那么最终的SELECT将返回5行,包括两个虚拟行。但是,如果temp3不包含数据,则两个虚拟行也不应出现,并且用户返回空记录集。

如果temp3包含数据,我们如何才能进行最终选择?如果temp3现在有行,则返回空记录集?

sql oracle common-table-expression
1个回答
2
投票

怎么样:

with temp1 as ( . . . ),
     temp2 as ( . . . ),
     temp3 as ( . . . )
select t
from (select dummyrow1 from dual union all
      select . . . from temp3 union all
      select dummyrow2 from dual
     ) t
where exists (select 1 from temp3);

如果你关心行的排序,那么你应该在最外面的order by中包含一个select

© www.soinside.com 2019 - 2024. All rights reserved.