触发以自动将元组添加到关系

时间:2019-05-25 22:52:30

标签: sql sqlite relational-database

我正在尝试在SQLITE上创建一个触发器,以在将某些内容添加到某个表时自动将元组添加到另一个表,但是首先,我想检查添加的内容是否属于另一个第三表。

这是我的触发器:

DROP TRIGGER IF EXISTS atualizaBibliotecas;

CREATE TRIGGER atualizaBibliotecas
AFTER INSERT ON FoiComprado
FOR EACH ROW
BEGIN
    SELECT CASE 
    WHEN 
    (
        SELECT count(*)
        FROM Album 
        WHERE idItem = NEW.idItem
    ) <> 0
    THEN INSERT INTO Possui(idItem, email, dataAquisicao) VALUES(11,'aaaa@bbbb.com', '2019-05-14');
END;

这是我收到的错误:

Error: near line 8: near "INSERT": syntax error

第8行:

CREATE TRIGGER atualizaBibliotecas

2 个答案:

答案 0 :(得分:1)

我相信你想要:-

CREATE TRIGGER atualizaBibliotecas
AFTER INSERT ON FoiComprado
FOR EACH ROW
   WHEN 
    (
        SELECT count(*)
        FROM Album 
        WHERE idItem = NEW.idItem
    ) <> 0
    BEGIN
    INSERT INTO Possui(idItem, email, dataAquisicao) VALUES(11,'aaaa@bbbb.com', '2019-05-14');
END;

答案 1 :(得分:0)

SQLite在其触发器中不支持控制流逻辑。您可以将其表示为条件insert

INSERT INTO Possui (idItem, email, dataAquisicao)  
   SELECT 11, 'aaaa@bbbb.com', '2019-05-14'
   WHERE NOT EXISTS (SELECT 1 FROM Album a WHERE a.idItem =  NEW.idItem);

我为您对插入进行硬编码11感到惊讶。我希望有NEW.idITEM