嗨,我有一个非常复杂的sql语句,可以返回一些结果 一些结果在另一个具有相同Id的表中 我希望有一个像第一个的结果集加上属于另一个表的所有行的副本。
下面的代码是错误的,但显示了我想要实现的目标:
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;
答案 0 :(得分: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;
答案 1 :(得分: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;