如何使用:NEW或:OLD运算符在oracle触发器中获取所有新值。像新的。*)

时间:2019-05-20 14:40:29

标签: oracle triggers oracle12c

我试图在触发器中获取所有新值和旧值,然后再将其插入到另一个表中,但是我只能获取特定值而不是所有数据。

我尝试了:NEW。*和:OLD。*,它对于postgress很好,但对于oracle却不行。

$args = [
    'post_name__in' => [ 'slug-1', 'slug-2' ],
    'post_type'     => 'page',
    'post_status'   => 'publish',
];
$result = get_posts( $args );

我遇到错误: 错误(10,8):PLS-00049:错误的绑定变量“ NEW”。

1 个答案:

答案 0 :(得分:0)

好吧,别急了。不要使用快捷方式。

测试用例:

SQL> create table test as select * From dept;

Table created.

SQL> create table test_log as select * From dept where 1 = 2;

Table created.

SQL> alter table test_log add (id number, action varchar2(1), datum date);

Table altered.

SQL> create sequence seqlog;

Sequence created.

SQL>

触发。分别引用每列。 :NEW.*在Postgres中有效的事实并不意味着它在Oracle中有效。

SQL> create or replace trigger trg_test
  2    before insert or update or delete on test
  3    for each row
  4  begin
  5    if updating then
  6       insert into test_log (deptno, dname, loc, id, action, datum)
  7         values
  8         (:old.deptno, :old.dname, :old.loc, seqlog.nextval, 'U', sysdate);
  9       insert into test_log (deptno, dname, loc, id, action, datum)
 10         values
 11         (:new.deptno, :new.dname, :new.loc, seqlog.nextval, 'U', sysdate);
 12    elsif inserting then
 13       insert into test_log (deptno, dname, loc, id, action, datum)
 14         values
 15         (:new.deptno, :new.dname, :new.loc, seqlog.nextval, 'I', sysdate);
 16    elsif deleting then
 17       insert into test_log (deptno, dname, loc, id, action, datum)
 18         values
 19         (:old.deptno, :old.dname, :old.loc, seqlog.nextval, 'D', sysdate);
 20    end if;
 21  end;
 22  /

Trigger created.

SQL>

测试:

SQL> alter session set nls_Date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> update test set loc = 'Croatia' where deptno = 10;

1 row updated.

SQL> delete from test where deptno = 20;

1 row deleted.

SQL> insert into test (deptno, dname, loc) values (99, 'IT', 'Zagreb');

1 row created.

SQL> select * From test_log order by id;

    DEPTNO DNAME          LOC                   ID A DATUM
---------- -------------- ------------- ---------- - -------------------
        10 ACCOUNTING     NEW YORK               5 U 20.05.2019 21:44:33
        10 ACCOUNTING     Croatia                6 U 20.05.2019 21:44:33
        20 RESEARCH       DALLAS                 7 D 20.05.2019 21:44:43
        99 IT             Zagreb                 8 I 20.05.2019 21:44:52

SQL>