본문 바로가기

Note

[SQL] Multi Action Trigger

일반적인 트리거는 테이블에 이벤트 특정 한 개의 작업 (삭제 혹은 입력, 변경)을 하게 되어 있다.

그러나 9.7 FixPack4 부터는 여러 작업을 수행할 수 있도록 트리거 기능이 개선되었다.

업무에 따라, 회사마다 정책에 의해서 트리거를 쓸 수도 있고, 안쓸수도 있지만 “특정 이벤트에 여러 작업을 해야 되는 요건”이 있다면 multi action trigger를 검토할 필요성이 있을 것 같다.

1번 테이블에 데이터가 입력되거나 변경되는 경우, 2번 테이블에 insert 및 update 작업이 기록되도록 하여 multi action이 적용하는지를 테스트 해 보았다.

테이블 생성

db2 “create table t1 (c1 integer, c2 timestamp)
db2 “create table t2 (c1 varchar(10), c2 timestamp)

 

트리거 생성

db2 +p -td"@" -v << EOF

connect to sample @

CREATE OR REPLACE TRIGGER tr1
  BEFORE INSERT OR UPDATE ON t1
  FOR EACH ROW
begin
    IF (INSERTING) THEN
         insert into t2 values ('inserting',current timestamp);
    END IF;

    IF (UPDATING ) THEN
         insert into t2 values ('updating',current timestamp);
    END IF;
end
@
terminate @
EOF

1번 테이블에 데이터 입력 및 2번 테이블의 insert 실행기록 확인

$ db2 "insert into t1 values (1,current timestamp),(2,current timestamp)"
DB20000I  The SQL command completed successfully.

$ db2 "select * from t2"

C1         C2
---------- --------------------------
inserting  2011-10-19-16.19.27.047307
inserting  2011-10-19-16.19.27.075943

  2 record(s) selected.

 

1번 테이블의 데이터 변경 및 2번 테이블의 update 실행기록 확인

$ db2 "update t1 set c1=11 where c1 =1"
DB20000I  The SQL command completed successfully.

$ db2 "select * from t2"

C1         C2
---------- --------------------------
inserting  2011-10-19-16.19.27.047307
inserting  2011-10-19-16.19.27.075943
updating   2011-10-19-16.20.24.818192

  3 record(s) selected.