合并会比更新更好,原因很简单,一次执行更新一行会导致大量不必要的上下文切换和索引/表访问。甲骨文在批量方面运作得更好。
为了能够在此处使用合并语句,您必须使用ID
、COMMENT
和创建一个中间表USERID
。
只有在您可以执行合并之后
merge into RecordTable a using TEMP_recordtable b
on (a.id = b.id)
when matched then update set
a.COMMENT=b.COMMENT ,
a.MODIFIEDDate = SYSTIMESTAMP,
a.UserID = b.UserID
编辑:没有临时表的更新
演示表
SQL> create table m1 (id number , name varchar2(30) , updated date);
Table created.
SQL> insert into m1 values (1 , 'Haki', sysdate);
1 row created.
SQL> insert into m1 values (3 , 'Simon', sysdate);
1 row created.
SQL> commit;
SQL> select * from m1;
ID NAME UPDATED
---------- ------------------------------ -------------------
1 Haki 03/10/2013 09:39:37
3 Simon 03/10/2013 09:38:17
如果要在 sql 中使用集合,则需要在 db 中声明它们
SQL> create type rec as object (id number , name varchar2(10))
2 /
Type created.
SQL> create type rec_arr as table of rec;
2 /
Type created.
现在我们创建列表并将其合并到我们的表中
SQL> ed
Wrote file afiedt.buf
1 declare
2 myarr rec_arr := rec_arr( rec (1 , 'Haki') , rec (2 , 'Raul'));
3 begin
4 merge into m1 using table(myarr) b on (m1.id = b.id)
5 when matched then update set
6 m1.name = b.name ,
7 m1.updated = sysdate
8 when not matched then insert (id , name , updated)
9 values (b.id , b.name , sysdate);
10* end;
SQL> /
PL/SQL procedure successfully completed.
SQL> select * from m1;
ID NAME UPDATED
---------- ------------------------------ -------------------
1 Haki 03/10/2013 09:40:16
3 Simon 03/10/2013 09:38:17
2 Raul 03/10/2013 09:40:16
3 rows selected.
如您所见,现有记录已更新,新记录已插入。