SQLite中的条件触发继承

时间:2018-06-13 14:21:40

标签: sql sqlite triggers single-table-inheritance

我正在使用SQLite,我正在使用XOR单表继承,我想创建一个触发器,使我能够:

  1. 如果表InstructionRefs.id
  2. 中已创建RideHeightRefs,请在插入前检查
  3. 在插入之前Ckeck在另一个继承的表InstructionRefs.id中不存在StrappingRefsenter image description here 我拿了一些oracle PL / SQL代码并更改了它,我想从IF NOT EXISTS (SELECT id...)开始写错了:

    CREATE TRIGGER IF NOT EXISTS insert_instructionRefs_trigger BEFORE INSERT ON InstructionRefs
    BEGIN
    IF NOT EXISTS (SELECT id FROM RideHeightRefs AS RHR INNER JOIN InstructionRefs IR ON RHR.id = IR.id)
    BEGIN
    SELECT RAISE(FAIL, '"RideHeightRefs" key is unknown. Insertion in "instructionRefs" is impossible.')
    END'
    IF NOT EXISTS (SELECT * FROM (SELECT RideHeightRefs FROM StrappingRefs UNION ALL SELECT RideHeightRefs FROM InstructionRefs) T WHERE RideHeightRefs IN (SELECT RideHeightRefs FROM NEW)) BEGIN SELECT RAISE(FAIL, '"RideHeightRefs" key is used in another table. Insertion in "StrappingRefs" is impossible.') END END

  4. 如何修改代码以使其与sqlite语法兼容?

1 个答案:

答案 0 :(得分:1)

要检查基表中的相应行是否存在,只需使用foreign key constraint

SQLite没有IF语句。要检查某些内容,请在SELECT FAIL中添加WHERE子句,或使用触发器的WHEN子句:

CREATE TRIGGER IF NOT EXISTS insert_instructionRefs_trigger
BEFORE INSERT ON InstructionRefs
WHEN EXISTS (SELECT *
             FROM StrappingRefs
             WHERE id = NEW.id)
BEGIN
  SELECT RAISE(FAIL, '"RideHeightRefs" key is used in another table. Insertion in "StrappingRefs" is impossible.');
END;