【发布时间】:2019-12-18 15:36:04
【问题描述】:
我正在 Oracle 11g 中执行 MERGE 操作,但它们返回的行数比预期的要多。
create table sales(product varchar2(20),month date, amount number(10))
insert into sales values('LG','01-Jan-17',20000);
insert into sales values('sony','01-Jan-18',22000);
insert into sales values('panasonic', '22-dec-17',18000);
create table sales_history(product varchar2(20),month date, amount number(10))
insert into sales_history values('sony', '22-dec-17',24000);
insert into sales_history values('panasonic', '22-dec-17',18000);
select * from sales;
select * from sales_history
merge into sales_history sh using(select product,month,amount from sales)s
on (s.product=sh.product)
when matched then update set sh.month=s.month,sh.amount=s.amount
when not matched then insert(sh.product,sh.month,sh.amount)
values(s.product,s.month,s.amount);
我尝试在 Pl/SQL 中执行相同的查询,这将给我相同的结果,但它返回的行更多是重复的行。为什么会这样?
set serveroutput on
declare
s_product varchar2(20);
s_month date;
s_amount number(10);
p_product s_product%type;
m_month s_month%type;
a_amount s_amount%type;
cursor sc1 is
select product,month,amount from sales;
cursor shc2 is
select product,month,amount from sales_history;
begin
open sc1;
open shc2;
loop <<l1>>
fetch sc1 into s_product,s_month,s_amount;
fetch shc2 into p_product,m_month,a_amount;
if s_product = p_product then
if s_month <> m_month then
update sales_history set month = s_month where product = s_product;
end if;
if s_amount <> a_amount then
update sales_history set amount = s_amount where product = s_product;
end if;
else
INSERT INTO sales_history(product, month, amount)
SELECT product, month, amount FROM sales;
dbms_output.put_line('DATA IS UPDATED');
end if;
exit when sc1%notfound;
exit when shc2%notfound;
end loop l1;
close sc1;
close shc2;
end;
select * from sales_history
【问题讨论】:
-
合并查询返回的行数与您写入的行数一样多。它将始终返回销售数量,因为您正在为每一行执行更新或插入操作。如果您有想要的结果,请用它更新问题。
标签: sql plsql oracle11g sql-merge