使用pl sql过程在内部循环中更新语句

时间:2013-06-10 12:19:38

标签: oracle

我尝试使用以下pl sql过程将我的表更新为field1,编译和执行完成没有任何错误,当我调用此过程时放置更新不起作用我不知道为什么!我用光标使用了{for update of .... current of)语句,代码在

下面
create or replace procedure p1 is
r1 table1%rowtype;
r2 table2%rowtype;
cursor c1 is select * from table1 for update of field1;
cursor c2 is select * from table2;
begin
open c1;
loop <<outer>>
    fetch c1 into r1;
    open c2;
        loop <<inner>>
            fetch c2 into r2;
               if condition then
               dbms_output.put_line('ok');            
               update table1
               set field1= 1
               where current of c1;                    
               end if;
        exit when c2%notfound;
        end loop inner;       
    close c2; 
    exit when c1%notfound;
end loop outer;
close c1;
end;
/

注意:IF语句中的条件是正确的,因为当我执行该过程时,每次执行循环时,语句(dbms_output.put_line('ok');)都成功执行,当我删除update语句时(对于....的更新)当前的语句,但是当我将update语句与(用于更新.... current of)语句放在同一条件时,update语句不起作用。

2 个答案:

答案 0 :(得分:2)

1)

    open c2;
        loop <<inner>>
            fetch c2 into r2;
               if condition then
               dbms_output.put_line('ok');            
               update table1
               set field1= 1
               where current of c1;  -- <---- YOU CANNOT USE THAT
               end if;
        exit when c2%notfound;
        end loop inner;       
    close c2; 

2) Rewrite to plain SQL:

CREATE TABLE table1(field1 NUMBER, field2 NUMBER);
CREATE TABLE table2(field1 NUMBER, field2 NUMBER);

INSERT INTO table1(field1, field2) VALUES(111, 121);
INSERT INTO table1(field1, field2) VALUES(112, 122);
INSERT INTO table1(field1, field2) VALUES(113, 123);
INSERT INTO table1(field1, field2) VALUES(114, 124);
INSERT INTO table1(field1, field2) VALUES(115, 125);

INSERT INTO table2(field1, field2) VALUES(111, 121);
INSERT INTO table2(field1, field2) VALUES(112, 122);
INSERT INTO table2(field1, field2) VALUES(213, 123);
INSERT INTO table2(field1, field2) VALUES(214, 124);
INSERT INTO table2(field1, field2) VALUES(215, 125);
COMMIT;

UPDATE  table1
SET     field1 = 1
WHERE   EXISTS
(
        SELECT  1
        FROM    table2
        WHERE   table1.field1 = table2.field1
        AND     table1.field2 = table2.field2
);
-- 2 rows updated.

SELECT * FROM table1;
/*
1   121
1   122
113 123
114 124
115 125
*/

答案 1 :(得分:0)

如何检查更新是否有效?

如果在另一个会话中查询该表,则在pl / sql代码之后执行commit语句之前,您将看不到代码所做的任何更改。