简体   繁体   English

插入后IBM DB2创建触发器

[英]IBM DB2 Create Trigger after insert

i'm having trouble trying to create a trigger for my db2 database. 我在尝试为我的db2数据库创建触发器时遇到了麻烦。 this is the first time that i try to use triggers, so please forgive my stupidity. 这是我第一次尝试使用触发器,因此请原谅我的愚蠢行为。

i have 3 tables which look like this: 我有3张桌子,看起来像这样:

  • table arnold with columns: "id" and "use" both integer 表arnold的列:“ id”和“ use”均为整数
  • table bertram with columns: "id" integer and "name" varchar 表bertram,其列为:“ id”整数和“ name” varchar
  • table connor with columns: "pos", "arnoldid", "bertramid" all integer 表connor的列:“ pos”,“ arnoldid”,“ bertramid”所有整数

now im trying to create a trigger that will automatically insert rows into table connor when a new row is inserted into table bertram. 现在我正在尝试创建一个触发器,当将新行插入表bertram中时,该触发器将自动将行插入表connor中。 it has to get the id of the newly created bertram row, and insert all rows of table arnold in which use is set to 1, and put their id's into the respective arnoldid column in the connor rows. 它必须获取新创建的bertram行的ID,并将表arnold的所有行(其中use设置为1)插入,并将其ID放入connor行的相应arnoldid列中。 also the pos column in all those connor rows has to be numbered from 1 up to the number of new rows. 所有这些connor行中的pos列也必须从1编号到新行的编号。

i came this far, but i think its very very wrong: 我走了这么远,但是我认为这是非常错误的:

CREATE TRIGGER usage AFTER INSERT ON bertram REFERENCING NEW AS newbert FOR EACH ROW
BEGIN ATOMIC
    SET newpos = 1;
    FOR looop AS mycursor CURSOR FOR SELECT * FROM arnold WHERE (use = 1) DO
        INSERT INTO connor (pos, bertramid, arnoldid) 
                    VALUES (newpos, newbert.id, mycursor.id);
        SET newpos = newpos +1;
    END FOR;
END

Thanks for any help!!! 谢谢你的帮助!!! :( :(

I haven't done a lot of trigger programming (or UDF, for that matter), but anytime you're using a CURSOR inside of SQL, you're usually doing it wrong. 我没有做过很多触发器编程(就此而言,还是UDF),但是任何时候 SQL 内部使用CURSOR时,通常都做错了。

I believe (but have not tested) the following should work: 我相信(但尚未测试)以下方法可以工作:

CREATE TRIGGER usage AFTER INSERT ON Bertram REFERENCING NEW ROW AS Newbert 
FOR EACH ROW MODE DB2ROW
BEGIN ATOMIC

INSERT INTO Connor(bertramId, arnoldId, pos)  -- elements reordered for clarity
SELECT newbert.id, a.id, (SELECT COUNT(b.id)
                          FROM Arnold as b
                          WHERE b.use = 1
                          AND b.id < a.id)
FROM Arnold as a
WHERE a.use = 1;
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM