SELECT RAISE
如果员工未处于活动状态,您想使用带有错误的 before 触发器,如下所示:
CREATE TRIGGER IF NOT EXISTS I_Service_Active
BEFORE INSERT ON Service
BEGIN
SELECT RAISE(FAIL, 'Cannot insert Service record since Employee is not active')
FROM Employee E
WHERE E.id_emp = NEW.id_emp
AND NOT E.active;
END;
你不能对约束做同样的事情,因为这需要一个约束表达式中不允许的子查询。
带有测试数据的完整示例:
CREATE TABLE IF NOT EXISTS Employee (
id_emp integer PRIMARY KEY,
name char(50),
active boolean);
CREATE TABLE IF NOT EXISTS Service (
id_ser integer PRIMARY KEY,
description char(256),
id_emp integer NOT NULL,
FOREIGN KEY (id_emp) REFERENCES Employee(id_emp));
CREATE TRIGGER IF NOT EXISTS I_Service_Active
BEFORE INSERT ON Service
BEGIN
SELECT RAISE(FAIL, 'Cannot insert Service record since Employee is not active')
FROM Employee E
WHERE E.id_emp = NEW.id_emp
AND NOT E.active;
END;
INSERT INTO Employee (id_emp, name, active)
VALUES (1, 'Sam', 1);
INSERT INTO Employee (id_emp, name, active)
VALUES (2, 'John', 0);
-- SUCCEEDS
INSERT INTO Service (id_ser, description, id_emp)
VALUES (1, 'Sam Service', 1);
-- FAILS
INSERT INTO Service (id_ser, description, id_emp)
VALUES (2, 'John Service', 2);