SQLite update trigger changes all rows in the table

后端 未结 2 1764
太阳男子
太阳男子 2021-01-12 09:12

Problem: a simplest possible update trigger writes a new value to all table rows instead of just the row being updated. Here is the table:

[names]

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 09:47

    Both OLD.xxx and NEW.xxx refer to the table row that caused the trigger to run. The UPDATE statement inside the trigger runs independently; if you want to restrict it to one table row, you have to explicitly do this in its WHERE clause by filtering on that statement's table values, i.e., names.id or just id.

    When the original UPDATE statement does not change the id column, the old and new id values are the same, and the expression OLD.id=NEW.id is true for all records in the table, as seen by the inner UPDATE statement.

    The correct trigger looks like this:

    CREATE TRIGGER "namelenupd"
    AFTER UPDATE OF name ON "names"
    BEGIN
        UPDATE "names" SET len = length(NEW.name) WHERE id = NEW.id;
    END;
    

提交回复
热议问题