2016-02-05 32 views
2

嗨我有一个非常复杂的SQL语句,返回一些结果。
某些结果在另一个具有相同Id的表中。
我想有一个结果集像第一个加上所有属于另一个表的行的副本。SQL选择语句联合所有本身

下面的代码是错误的,但显示了我想实现:

Select myRules.* 
From (Complicated sql statement) myRules 
Union All 
Select from myRules 
inner join Table2 
on myRules.Id =Table2.Id; 

这可能吗?

PS1。我不想触及复杂的sql语句。
PS2。我得到的错误是,myRules表或视图不存在

编辑:根据您的回答我尝试创建一个返回游标的过程,但我得到了在该行的错误我打开游标:

procedure Get_Rules(in_Id  in tableA.Reconciliation_Id%type, 
        io_cursor in out t_ref_cursor) is 
begin 
With myRules as (
complicated sql statement) 

open io_cursor for -- ERRORS here: missing SELECT keyword 
select * 
    from myRules 
    union all 
select * 
    from myRules 
    inner join Table2 
    on myRules.Id = Table2.Id; 
end Get_Rules; 
+1

您是否尝试过的CTE? (公用表格表达。) – jarlh

回答

4

是的,这是完全有效的union all与同桌另一个查询的查询。在这种情况下,最好使用with

with myRules as (
    complicated sql statement 
) 
select * 
from myRules 
union all 
select * 
from myRules 
inner join Table2 
on myRules.Id = Table2.Id; 

如果你想在一个光标使用with,将其嵌入的游标,而不是存储过程:

procedure Get_Rules(in_Id  in tableA.Reconciliation_Id%type, 
        io_cursor in out t_ref_cursor) is 
begin 
    open io_cursor for 
    with myRules as (
    complicated sql statement 
) 
    select * 
    from myRules 
    union all 
    select * 
    from myRules 
    inner join Table2 
    on myRules.Id = Table2.Id; 
end Get_Rules; 
+0

您能否检查我的编辑? – Nianios

+0

@Nianios我只是扩大了我的答案 –

+0

非常感谢 – Nianios

3

使用CTE(公共表表达式):

with myRules as 
(
Complicated sql statement 
) 
Select myRules.* 
From myRules 
Union All 
Select from myRules 
inner join Table2 
on myRules.Id = Table2.Id;