插入触发器之前的 SQLite

SQLite before insert trigger

PKA 违反使用 BEFORE INSERT TRIGGER 时,我正在尝试将重复数据插入 table B,如下例所示:

CREATE TABLE A( Col INTEGER, Coll TEXT(25), CONSTRAINT PKA PRIMARY KEY(Col, Coll) ON CONFLICT IGNORE);
CREATE UNIQUE INDEX IX_A ON A(Col, Coll);

CREATE TABLE B( Col INTEGER, Coll TEXT(25));
CREATE INDEX IX_B ON B(Col, Coll);

CREATE TRIGGER Trig
BEFORE INSERT
ON A
WHEN (Col = New.Col AND Coll = New.Coll)
BEGIN
      INSERT INTO B(Col, Coll) VALUES(New.Col, New.Coll);
END;

但是,Col 列似乎无法在那里访问,因此它抛出:

no such column: Col

即使我将条件更改为

New.Col IN(SELECT Col FROM A)
AND
New.Coll IN(SELECT Coll FROM A)

我收到另一条错误消息:

UNIQUE constraint failed: A.Col, A.Coll

虽然不应该因为 ON CONFLICT IGNORE

您不需要索引:

CREATE UNIQUE INDEX IX_A ON A(Col, Coll);

因为您已经将 (Col, Coll) 定义为 PRIMARY KEY 而且,使用此索引,尽管您为重复行定义了 ON CONFLICT IGNORE,但如果您尝试插入重复行,因为未为索引定义 ON CONFLICT IGNORE
所以放弃它:

DROP INDEX IF EXISTS IX_A;

现在,将触发器的代码更改为:

CREATE TRIGGER Trig
BEFORE INSERT
ON A
WHEN EXISTS (SELECT 1 FROM A WHERE Col = New.Col AND Coll = New.Coll)
BEGIN
      INSERT INTO B(Col, Coll) VALUES(New.Col, New.Coll);
END;

EXISTS 检查 table A 是否已经包含列值与要插入的列值相同的行,如果是,则将新行插入table B.

你也可以这样写触发器:

CREATE TRIGGER Trig
BEFORE INSERT
ON A
BEGIN
      INSERT INTO B(Col, Coll)
      SELECT Col, Coll FROM A
      WHERE (Col, Coll) = (New.Col, New.Coll);
END;