繁体   English   中英

如何使此pl / sql游标更有效?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM