从具有多列和多个表的select插入

时间:2017-06-21 20:54:16

标签: sql triggers db2

我需要使用Insert Statement创建一个SQL Trigger,从不同的表中选择多个列。像这样:

CREATE OR REPLACE TRIGGER ACTIV_TRG 
AFTER INSERT ON TRANS_LOG
REFERENCING NEW AS TR  
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
    INSERT INTO ACTIVITIES values ( 
    (SELECT MAX(SEQNBR) FROM ACTIV_LOG where TRAN_ID = 'XXX'),
    TR.ACCOUNT,
    TR.EVENT, 
    SELECT TRAN_ID ,
    TRAN_DT ,
    TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX',
    CURRENT TIMESTAMP
)
END;

问题是当我尝试在子查询中选择多个列时。 我知道我是否将Sub Query分开:

(TRAN_ID  FROM ACTIV_DEL where TRAN_ID = 'XXX'),
(TRAN_DT  FROM ACTIV_DEL where TRAN_ID = 'XXX'),
(TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX'),

会起作用,但肯定必须有一种更好,更有效的方法来做到这一点。

提前致谢。

当然,必须有一个比这更好的解决方案:

CREATE OR REPLACE TRIGGER ACTIV_TRG 
AFTER INSERT ON TRANS_LOG
REFERENCING NEW AS TR  
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
   INSERT INTO ACTIVITIES values ( 
   (SELECT MAX(SEQNBR) FROM ACTIV_LOG where TRAN_ID = 'XXX'),
   TR.ACCOUNT, ---> FIELD FROM TRANS_LOG (TRIGGER SOURCE)
   TR.EVENT,   ---> FIELD FROM TRANS_LOG (TRIGGER SOURCE)
   SELECT TRAN_ID  FROM ACTIV_DEL where TRAN_ID = 'XXX',  ---> REPETING SELECT
   SELETC TRAN_DT  FROM ACTIV_DEL where TRAN_ID = 'XXX',  ---> REPETING SELECT
   SELECT TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX',  ---> REPETING SELECT
   CURRENT TIMESTAMP
)
END;

2 个答案:

答案 0 :(得分:1)

我会使用以下选择执行插入:

    SELECT (SELECT MAX(SEQNBR) FROM ACTIV_LOG where TRAN_ID = 'XXX'),
        TR.ACCOUNT,
        TR.EVENT,
        TRAN_ID ,
        TRAN_DT ,
        TRAN_LN,
        CURRENT TIMESTAMP
        FROM ACTIV_DEL
        where TRAN_ID = 'XXX'

答案 1 :(得分:0)

这样的东西?

CREATE OR REPLACE TRIGGER ACTIV_TRG 
AFTER INSERT ON TRANS_LOG
REFERENCING NEW AS TR  
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
    INSERT INTO ACTIVITIES 
        SELECT (SELECT MAX(f0.SEQNBR) FROM ACTIV_LOG f0 where f0.TRAN_ID = f1.TRAN_ID),
        TR.ACCOUNT,
        TR.EVENT,
        f1.TRAN_ID ,
        f1.TRAN_DT ,
        f1.TRAN_LN,
        CURRENT TIMESTAMP
        FROM ACTIV_DEL f1
        where f1.TRAN_ID = 'XXX'

END;