您好,我有一个非常复杂的 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 表或 View 不存在
编辑:根据您的回答,我尝试创建一个返回游标的过程,但在打开游标的行中出现错误:
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;
最佳答案
是的,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;
关于SQL select 语句 union all with itself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227808/