|
5
Tom Keyt说过:
You should do it in a single SQL statement if at all possible.
If you cannot do it in a single SQL Statement, then do it in PL/SQL.
If you cannot do it in PL/SQL, try a Java Stored Procedure.
If you cannot do it in Java, do it in a C external procedure.
If you cannot do it in a C external routine, you might want to seriously think about why it is you need to do it
当然,这世界上没有绝对正确的真理,我在工作经常遇到一个简单的SQL Statement可以做却最后使用了PLSQL。一个简单例子,一个有上10亿records的table中某一个column,如果是NULL,update到‘A’,这个update statement在我们公司的系统里必死(golden gate, rollback......)。
cursor本身没有问题,更不是洪水猛兽。每一个SQL都会用到cursor,cursor是无法避免的。我们所要避免的是用cursor一个一个的loop,我一般都用以下这个模式:
open cursor;
loop
fetch c bulk collect into l_c1, l_c2, ....... LIMIT 1000;
for i in 1 .. l_c1.count
loop
process....
end loop;
forall i in 1 .. l_c1.count
insert into ..... values ( L_c1(i), .... );
end loop;
exit when c%notfound;
end loop;
close cursor
LIMIT的值可以自己调整,一般来说我都是用10000,有时候1000。当然要是不愿意”麻烦“的也不要太担心,Oracle Database automatically optimizes it in Oracle Database 10g and above,我记得11g是相当于limit 200(不确定),但是我还是更愿意自己写。 |
|