SQLite触发器有条件地增加值

时间:2015-04-22 20:52:09

标签: sqlite triggers

我想根据新插入/更新的记录增加一列,但到目前为止我所做的并没有用。

所以我的表ProcedureCommands有一个Sequence列,它是一个整数。例如,每当使用Sequence值5创建新记录时,我希望所有具有相同ProcedureIdSequence值> = 5的记录增加1。 / p>

表格脚本

CREATE TABLE ProcedureCommands (
ProcedureCommandId INTEGER PRIMARY KEY AUTOINCREMENT
                           NOT NULL,
ProcedureId        INTEGER NOT NULL,
Sequence           INTEGER NOT NULL);

INSERT INTO ProcedureCommands(ProcedureId, Sequence) VALUES(1, 3);
INSERT INTO ProcedureCommands(ProcedureId, Sequence) VALUES(1, 4);
INSERT INTO ProcedureCommands(ProcedureId, Sequence) VALUES(1, 5);
INSERT INTO ProcedureCommands(ProcedureId, Sequence) VALUES(1, 6);
INSERT INTO ProcedureCommands(ProcedureId, Sequence) VALUES(2, 4);
INSERT INTO ProcedureCommands(ProcedureId, Sequence) VALUES(2, 5);

触发脚本

CREATE TRIGGER Update_Sequence UPDATE OF Sequence ON ProcedureCommands FOR EACH ROW
BEGIN
UPDATE ProcedureCommands
   SET Sequence = CASE WHEN Sequence >= new.Sequence THEN Sequence = Sequence + 1 ELSE Sequence END
 WHERE ProcedureId = new.ProcedureId;
END;

不幸的是,所写的Trigger不起作用。如何在插入/更新后有条件地增加字段?

1 个答案:

答案 0 :(得分:2)

处理新记录的触发器是INSERT触发器。

Sequence = Sequence + 1比较两个值,并返回比较结果。在这种情况下,两个值永远不能相等,因此结果始终为零。

并且您不希望更新插入的行本身,因此您必须使用>而不是>=

如果您不想更新某些行,则可以更轻松地将过滤器放入WHERE子句中:

CREATE TRIGGER Update_Sequence
AFTER INSERT ON ProcedureCommands
FOR EACH ROW
BEGIN
    UPDATE ProcedureCommands
    SET Sequence = Sequence + 1
    WHERE ProcedureId = new.ProcedureId
      AND Sequence    > new.Sequence;
END;