我正在使用SQLite
,我正在使用XOR单表继承,我想创建一个触发器,使我能够:
InstructionRefs.id
RideHeightRefs
,请在插入前检查
在插入之前Ckeck在另一个继承的表InstructionRefs.id
中不存在StrappingRefs
。
我拿了一些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
如何修改代码以使其与sqlite语法兼容?
答案 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;