plsql遊標最後一行重複的問題,plsql遊標一行重複
大家仔細看一下,下面第一個預存程序,test01,有沒問題?看似沒問題,其實會造成重複行,test02將exit when的語句放到合適的位置上來。就不會出現最後一行重複列印的問題。
create or replace procedure test01 as cursor cursor1 is select * from v$session where rownum <= 5; record1 cursor1%rowtype;begin DBMS_OUTPUT.ENABLE(buffer_size => null); open cursor1; loop fetch cursor1 into record1; dbms_output.put_line(record1.sid); exit when cursor1%notfound; end loop; close cursor1;end;
-----------------------------------------------------------------------create or replace procedure test02 as cursor cursor1 is select * from v$session where rownum <= 5; record1 cursor1%rowtype;begin DBMS_OUTPUT.ENABLE(buffer_size => null); open cursor1; loop fetch cursor1 into record1; exit when cursor1%notfound; dbms_output.put_line(record1.sid); end loop; close cursor1;end;
plsql中如果我定義一個遊標,然後開啟這個遊標,然後loop迴圈把查詢出來的資料全部插入自己定義的表中
open那不會浪費太多時間。需要的時間就是兩部分。
1.定義遊標,擷取結果集的時候。---這個時間主要看你的sql查詢需要多長時間。
2.Loop的時候。----這個就是啟動並執行時間了。
不過建議大量資料的話不要用遊標來處理。
遊標的處理速度是很慢的。效率比較低。最好能做批量處理。
我以前用遊標做過資料處理,我那個商務邏輯比較複雜,每小時大概只能處理幾十萬資料。效率太低了。後來我都改成多步驟,用insert into select 。。from 這類的寫法去處理,能差百八十倍的速度。
sqlserver預存程序中使用遊標,查詢結果沒有第一條資料,但迴圈次數是對的,不過後面兩條資料重複,教
將fetch next from mycursor into @i,@name
放在while迴圈體的最後即可,即:
while(@fetch_status=0)
begin
print 'id: '+@i+ ' name: '+@name
fetch next from mycursor into @i,@name
end
這樣應該就可以了。