如何为 AS400 Table 创建 SQL 触发器

How to create a SQL trigger for AS400 Table

我是 Java 开发者,但不是 RPG 开发者。对于我的一个项目,我需要为 AS400 table (TABLE A) 创建一个 SQL AFTER INSERT 触发器并将新创建的行复制到另一个table (TABLE乙)。两者 table 具有相同的结构。 如果有人可以指导我完成该过程,我将不胜感激。请注意,我完全有权在 AS400 上进行任何类型的处理。提前致谢。

编辑 AS400 是一个包含 SQL 引擎 (DB2)

的 IBM 设备

IBM DB2 for i CREATE TRIGGER reference

您有几个选择,模式粒度

MODE DB2SQL is valid for AFTER triggers. MODE DB2SQL AFTER triggers are activated after all of the row operations have occurred.

MODE DB2ROW triggers are activated on each row operation. MODE DB2ROW is valid for both the BEFORE and AFTER activation time.

FOR EACH ROW Specifies that the database manager executes the triggered-action for each row of the subject table that the triggering operation modifies. If the triggering operation does not modify any rows, the triggered-action is not executed.

FOR EACH STATEMENT Specifies that the database manager executes the triggered-action only once for the triggering operation. Even if the triggering operation does not modify or delete any rows, the triggered action is still executed once. FOR EACH STATEMENT cannot be specified for a BEFORE trigger. FOR EACH STATEMENT cannot be specified for a MODE DB2ROW trigger.

文档的 REFERENCING 子句很好地 table 展示了它们如何交互。

假设您原来的 table 完成了多行插入,那么每个语句触发一次触发器会提高性能...

CREATE OR REPLACE TRIGGER TRIGGER_NAME AFTER INSERT
ON TABLE_A
  REFERENCING NEW TABLE AS TABLE_N 
  FOR EACH STATEMENT MODE DB2SQL

  begin atomic
    insert into TABLE_B 
      select * from TABLE_N;
  end

交替,逐行...

CREATE OR REPLACE TRIGGER TRIGGER_NAME AFTER INSERT
ON TABLE_A
  REFERENCING NEW ROW AS N 
  FOR EACH ROW MODE DB2ROW

  begin atomic
    insert into TABLE_B 
      values(n.col1, n.col2, n.col3, <....>);
  end

如果一次只向 TABLE_A 中插入一行,则这两个语句将一次向 TABLE_B.

中插入一行

如果一次插入将 10 行插入 TABLE_A,则 FOR EACH STATEMENT MODE DB2SQL 将一次插入 10 行到 TABLE_B;而 FOR EACH ROW MODE DB2ROW 将进行 10 次单独的插入。

有时,您必须使用 FOR EACH ROW,例如对于 BEFORE TRIGGER。

但是(通常)在 SQL 中,您最好尽可能进行基于集合的操作。