oracle怎么写循环更新,oracle–在plsql中使⽤for循环更新
你不需要FOR LOOP,只需要⼀个UPDATE即可完成⼯作:
UPDATE emp
SET comm = extra
WHERE comm IS NULL AND extra IS NOT NULL;
—编辑—-
我没有注意到,在预期的输出deptno 10更新为20,更新deptno需要另⼀个查询:
UPDATE emp
SET deptno = 20
WHERE deptno = 10;
—-编辑—–
如果要将更改的值插⼊另⼀个表,请尝试使⽤RETURNING..BULK COLLECT和FORALL的过程:
CREATE OR REPLACE PROCEDURE pro_cedure( p_dept_id number )
IS
TYPE changed_table_type IS TABLE OF changed%ROWTYPE;
changed_buff changed_table_type;
BEGIN
SELECT deptno, comm, extra BULK COLLECT INTO changed_buff
FROM emp
WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id
FOR UPDATE;
UPDATE emp
SET comm = extra
WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id;
FORALL i IN 1 .. unt
INSERT INTO changed VALUES changed_buff( i );
END;
/
如果您不打算在⼀次调⽤中处理⼤量记录(超过1000 …或最多⼏千),则该过程应该有效.如果⼀个dept_id可以包含⼀万或更多⾏,那么这个过程可能会很慢,因为它会消耗⼤量的PGA内存.在这种情况下,需要另⼀种以块的形式进⾏批量收集的⽅法.
– 编辑—如何存储序列值——-
我假设更改的表有4列,如下所⽰:
CREATE TABLE "TEST"."CHANGED"
( "DEPTNO" NUMBER,
"OLDVAL" NUMBER,
"NEWVAL" NUMBER,
"SEQ_NEXTVAL" NUMBER
) ;
我们将序列值存储在seq_nextval列中.
在这种情况下,过程可能如下所⽰:
create or replace
PROCEDURE pro_cedure( p_dept_id number )
IS
TYPE changed_table_type IS TABLE OF changed%ROWTYPE;
changed_buff changed_table_type;
BEGIN
SELECT deptno, comm, extra, val
BULK COLLECT INTO changed_buff
FROM emp
WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id
FOR UPDATE;
UPDATE emp
SET comm = extra
WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id;
批量更新sql语句
FORALL i IN 1 .. unt
INSERT INTO changed VALUES changed_buff( i );
END;
—编辑—带光标的版本⽤于⼩数据集—–
是的,对于⼩型数据集批量收集不会显着提⾼速度,并且在这种情况下使⽤for..loop的普通光标就⾜够了.
下⾯是如何将游标与更新⼀起使⽤的⽰例,注意FOR UPDATE⼦句,当我们计划使⽤WHERE CURRENT OF⼦句更新从游标获取的记录时,它是必需的.
这次在INSERT语句中计算序列值.
create or replace
PROCEDURE pro_cedure( p_dept_id number )
IS
CURSOR mycursor IS
SELECT deptno, comm, extra
FROM emp
WHERE comm IS NULL AND extra IS NOT NULL
AND deptno = p_dept_id
FOR UPDATE;
BEGIN
FOR emp_rec IN mycursor
LOOP
UPDATE emp
SET comm = extra
WHERE CURRENT OF mycursor;
INSERT INTO changed( deptno, oldval, newval, seq_nextval) VALUES( emp_rec.deptno, emp_recm,
a, val );
END LOOP;
END;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。