[英]Oracle Merge: Update single record in base table using multiple records from source table
I have a merge query as follows: 我有一个合并查询,如下所示:
merge into table1
using table2
on (table1.column1 = table2.column1)
when mateched then
update
set column2 = table2.column2;
Now it is giving me error like :unable to get a stable set of rows in the source tables 现在它给我这样的错误:无法在源表中获得稳定的行集
Now the issue is the source table, table2, is having multiple records for same column1 value and table1 is having only one record per column1 value.And I need all the table2 to update table1. 现在的问题是源表table2拥有针对相同column1值的多个记录,而table1每个column1值仅具有一条记录。而且我需要所有table2来更新table1。 can you pls help here?
您可以在这里帮忙吗?
" the issue is the source tabletable2, is having multiple records for same column1 value "
“问题是源tabletable2,对于同一column1值具有多个记录”
You need to ensure your sub-query returns only one row per value of column1
. 您需要确保子查询每个
column1
值仅返回一行。 Only you know what exact business rule you need to apply, but it could be something like this: 只有您知道需要应用什么确切的业务规则,但是可能是这样的:
merge into table1
using ( select column1, max(column2) as column2
from table2
group by column1 ) t2
on (table1.column1 = t2.column1)
when matched then
update
set column2 = t2.column2;
"I need all records from table2 to update table1. The reason is that I have a trigger on table1 which captures all transactions(inserts/updates) and loads to another history table. "
“我需要来自table2的所有记录来更新table1。原因是我在table1上有一个触发器,该触发器捕获所有事务(插入/更新)并加载到另一个历史记录表中。”
You can't use MERGE. 您不能使用MERGE。 In fact you're probably going to have to go procedural:
实际上,您可能必须执行程序操作:
begin
for t2rec in (select column1, column2
from table2
order by column1, column2 )
loop
update table1
set column2 = t2rec.column2
where column1 = t2rec.column1;
end loop;
end;
You'll need to order the loop statement to ensure the end state of table1
is right. 您需要对循环语句进行排序,以确保
table1
的结束状态正确。
Alternatively you could disable the journaling trigger and do this: 或者,您可以禁用日记记录触发器并执行以下操作:
insert into table1_journal
select table1.column1
, table2.column2
from table1
join table2
on table1.column1 = table2.column1
/
Then do the MERGE or a single row update. 然后进行合并或单行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.