如何重用子查询

Hop*_*ppe 4 oracle subquery oracle11g

我有一个很长的存储过程。在存储过程中,多次重复下面(括号中)的子查询。

and datasetid IN 
  (select datasetid from Reportingdatasetmembers
    where  ReportingDatasetID = param_in_ReportingDataSetID)
Run Code Online (Sandbox Code Playgroud)

我可以合并重复的代码吗?即,在 SQL Server 中,我会声明一个表变量。然后将行插入到表变量中。然后查询表变量。至少,这有助于应用 DRY 原则。

是否有一种等效的方法可以将其整合到 Oracle 中?Oracle 表集合似乎不是减少代码库。

我认为 CTE 是不可能的,因为它们不能重复使用?

Bon*_*ist 5

子查询分解(在其他数据库平台中也称为 CTE)是您所需要的,例如:

with dataset as (select datasetid
                 from   Reportingdatasetmembers
                 where  ReportingDatasetID = param_in_ReportingDataSetID)
select ...
from   some_table_1
where  ...
and    datasetid in (select datasetid from dataset)
union all
select ...
from   some_table_2
where  ...
and    datasetid in (select datasetid from dataset);
Run Code Online (Sandbox Code Playgroud)