[英]How can I make this pl/sql cursor more efficient?
嗨,大家好,我有一個執行時間太長的pl / sql游標。 我想知道如何進行相同的過程,但性能更好,代碼也可能更好。 我是PL / SQL的新手。
Declare
Cursor Cursor1 is
select * from table1 where
field1 IS NULL
or
field2 IS NULL or field3 IS NULL or field4 is null or field5 IS NULL or field6 IS NULL;
Begin
For i in Cursor1 loop
if i.field1 IS NULL then
update table1 set field1=0 where recordId=i.recordId;
end if;
if i.field2 IS NULL then
update table1 set field2=0 where recordId=i.recordId;
end if;
if i.field3 IS NULL then
update table1 set field3=0 where recordId=i.recordId;
end if;
if i.field4 IS NULL then
update table1 set field4=0 where recordId=i.recordId;
end if;
if i.field5 IS NULL then
update table1 set field5=0 where recordId=i.recordId;
end if;
if i.field6 IS NULL then
update table1 set field6=0 where recordId=i.recordId;
end if;
End loop;
End;
基本的問題是,考慮到該字段的條件,如何更新一個特定記錄的字段。 問題是,如果條件適用於記錄中的許多字段,則更新可能會在同一記錄中多次發生。
謝謝...
可以通過一個UPDATE
進行相同的操作
UPDATE table1 SET
field1 = COALESCE(field1, 0)
, field2 = COALESCE(field2, 0)
, field3 = COALESCE(field3, 0)
, field4 = COALESCE(field4, 0)
, field5 = COALESCE(field5, 0)
, field6 = COALESCE(field6, 0)
WHERE field1 IS NULL OR field2 IS NULL OR field3 IS NULL
OR field4 IS NULL OR field5 IS NULL OR field6 IS NULL
這是另一種做法:
UPDATE TABLE1
SET FIELD1 = NVL(FIELD1, 0),
FIELD2 = NVL(FIELD2, 0),
FIELD3 = NVL(FIELD3, 0),
FIELD4 = NVL(FIELD4, 0),
FIELD5 = NVL(FIELD5, 0),
FIELD6 = NVL(FIELD6, 0);
原理:執行此更新的任何查詢都將進行全表掃描,因為它正在查找NULL,通常情況下不會對其進行索引,即使對它們進行了索引,優化器也有很大的機會選擇全仍然進行表格掃描。 為什么要浪費時間檢查六個不同字段的NULL?
分享並享受。
嘗試執行這樣的幾次更新,避免使用游標:
update table1 set field1=0 where field1 IS NULL;
update table1 set field2=0 where field2 IS NULL;
update table1 set field3=0 where field3 IS NULL;
update table1 set field4=0 where field4 IS NULL;
update table1 set field5=0 where field5 IS NULL;
update table1 set field6=0 where field6 IS NULL;
我認為沒有更有效的方法可以做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.