SQLite - 将表1上的Trigger插入条件更新表2

时间:2015-03-01 05:03:24

标签: sqlite triggers insert

背景

我的触发器工作但是坏了。由于目标表[tbl_ccc_part]上的编码和UNIQUE值,触发器会将所有插入的值抛出到表中,并以静默方式删除违反UNIQUE条件的值。这导致[tbl_ccc_part]增加2,000条记录而不是几百条。

问题:

如何有效地限制此触发器,以便恢复原始意图。

预期的代码演练:

INSERT [tbl_ccc_inventory。[business_level_supplier_id]],[tbl_ccc_inventory。[stock_number]]的[tbl_ccc_inventory]和其他不相关的记录。

TRIGGER查看[tbl_ccc_part。[business_level_supplier_id]]和[tbl_ccc_part。[stock_number]]。如果 两者都匹配,请执行 INSERT。如果不是匹配,则INSERT记录。

CODE:

  CREATE TRIGGER trg_insert_ccc_inventory AFTER INSERT ON tbl_ccc_inventory
  /*  This trigger automatically updates tbl_ccc_part after entries are
      inserted into the tbl_ccc_inventory.  These entries make several
      assumptions about the values needed for tbl_ccc_part and should
      be verified for accuracy by someone. */
    BEGIN
      INSERT OR IGNORE INTO tbl_ccc_part
        (
          record_id,
          business_level_supplier_id,
          stock_number,
          oem_part_number,
          part_type,
          assembly_indicator,
          insurer_program,
          warranty_type,
          warranty_length,
          shippable_part
        )
      VALUES (
          "A",
          new.business_level_supplier_id,
          new.stock_number,
          new.stock_number,
          "OD",
          "N",
          "N/A",
          "LIMITED",
          "LIMITED",
          "Y");
  END;

1 个答案:

答案 0 :(得分:1)

要有条件地执行触发,请使用WHEN clause

CREATE TRIGGER xxx
AFTER INSERT ON tbl_ccc_inventory
WHEN NOT EXISTS (SELECT 1
                 FROM tbl_ccc_part
                 WHERE business_level_supplier_id = NEW.business_level_supplier_id
                   AND stock_number               = NEW.stock_number)
BEGIN
    INSERT ...;
END;