简体   繁体   English

SQLite-将表1上的触发器插入到条件更新表2中

[英]SQLite - Insert Trigger on TABLE 1 to conditional update TABLE 2

Background: 背景:

My trigger works but is broken. 我的触发器有效,但是坏了。 Because of the coding and the UNIQUE value on the target table [tbl_ccc_part], the trigger throws all of the inserted values into the table and silently drops the ones that violate the UNIQUE condition. 由于目标表[tbl_ccc_part]上的编码和UNIQUE值,触发器将所有插入的值都扔到表中,并以静默方式删除违反UNIQUE条件的值。 This causes [tbl_ccc_part] to grow by 2,000 records instead of a couple of hundred. 这导致[tbl_ccc_part]增加了2,000条记录,而不是几百条。

Question: 题:

How do I effectively limit this trigger so that I get back to the original intent. 如何有效地限制此触发器,以便回到最初的意图。

Intended Code Walkthrough: 预期的代码演练:

INSERT on [tbl_ccc_inventory] of [tbl_ccc_inventory.[business_level_supplier_id]],[tbl_ccc_inventory.[stock_number]], and other non-relevant records. 插入[tbl_ccc_inventory。[business_level_supplier_id]],[tbl_ccc_inventory。[stock_number]]的[tbl_ccc_inventory]和其他不相关的记录。

TRIGGER looks through [tbl_ccc_part.[business_level_supplier_id]] AND [tbl_ccc_part.[stock_number]]. 触发器将浏览[tbl_ccc_part。[business_level_supplier_id]]和[tbl_ccc_part。[stock_number]]。 If there is a match on both, do not INSERT. 如果两个匹配, 不要插入。 If there is not a match, INSERT record. 如果匹配,则插入记录。

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;

To execute a trigger conditionally, use the WHEN clause : 要有条件地执行触发器,请使用WHEN子句

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;

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

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