您的位置:首页 > 数据库 > Oracle

使用Merge into优化一个垃圾存储过程

2013-12-22 21:43 399 查看
开发人员反应下面存储过程出结果太慢,表和字段名做了处理
declare
cursor c1 is
select * from user1.tab1;
v_count number:=0;
begin
for v1 in c1 loop
select count(1) into v_count
from user1.tab2
where row_id=v1.row_id;
if v_count=0 then
INSERT INTO user1.tab1
(row_id,
col_1,
col_2,
col_3,
col_4,
col_5,
....
/* 这里有很多字段 */)
VALUES
(v1.row_id,
v1.col_1,
v1.col_2,
v1.col_3,
v1.col_4,
v1.col_5,
.....);
else
UPDATE user1.tab1
SET col_1 = v1.col_1,
col_2 = v1.col_2,
col_3 = v1.col_3,
col_4 = v1.col_4,
col_5 = v1.col_5,
.....
WHERE row_id = v1.row_id;
end if;
commit;
end loop;
end;

分析存储过程,就可以知道开发人员的目的是想从tab2里面查找和tab1里面通过row_id关联匹配的条件,不匹配inset,匹配update,这种过程太TM坑爹了,游标里面传入一个值就要把tab2 QJ一次,这里QJ了3千多万次,像这样的例子完全可以通过Merge into来改写,而且是最最最简单的merge基本用法。
merge into user1.tab1 a
using user1.tabl2 v1
on (v1.row_id=a.row_id)
when matched then
UPDATE
SET a.col_1 = v1.col_1,
a.col_2 = v1.col_2,
a.col_3 = v1.col_3,
a.col_4 = v1.col_4,
a.col_5 = v1.col_5,
.....
when not matched then
INSERT
(a.col1,
a.col2,
a.col3,
a.col4,
a.col5
.....)
VALUES
(v1.row_id,
v1.col_1,
v1.col_2,
v1.col_3,
v1.col_4,
v1.col_5
......);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息