ORACLE更新返回OLD和NEW值

时间:2017-10-25 08:13:48

标签: sql oracle tsql plsql oracle12c

是否与PL / SQL(Oracle 12c)中的此T-SQL查询等效?

=IF(E7>MAX(E2:E6),"Increased for 5 steps","")

查询更新表A,同时返回更新前和更新后记录的状态。

触发器不是我的解决方案,也不是以前的SELECT记录和更新后的SELECT记录。

1 个答案:

答案 0 :(得分:2)

不是直接的,但使用RETURNING INTO你将能够达到同样的效果:

CREATE TABLE A(columnA VARCHAR2(10), columnB INT);
INSERT INTO A(columnA, columnB) VALUES ('Test', 10);
INSERT INTO A(columnA, columnB) VALUES ('Row 2', 20);
CREATE TABLE audit_table(col_new VARCHAR2(10),col_old VARCHAR2(10));

DECLARE
   TYPE rec IS RECORD (actual A.columnA%TYPE, old A.columnA%TYPE);
   TYPE col_a_t IS TABLE OF rec;
   v_a col_a_t;
BEGIN
  UPDATE (SELECT A.*, (SELECT A.columnA FROM dual) AS old_columnA FROM A)
  SET columnA = 'XYZ'
  WHERE columnB < 30
  RETURNING columnA, old_columnA BULK COLLECT INTO v_a;
  COMMIT;

  -- printing for debug
  FOR i IN v_a.first .. v_a.last LOOP
     dbms_output.put_line('Old =>' || v_a(i).old || ' new => ' || v_a(i).actual);
  END LOOP;

  -- additional
  FORALL i IN v_a.first .. v_a.last
    INSERT INTO audit_table VALUES v_a(i);
  COMMIT;
END;
/

SELECT * FROM A;
SELECT * FROM audit_table;

<强> DBFiddle Demo

意见取自:Returning Old value during update