问题
Long story short, in SQLite, I have a sortOrder field that takes care of, well, a changeable sort order of items in a table. I have triggers that:
After Inesrt: the trigger updates all of the sortOrder fields by +1 if they are > than the field for the one inserted.
After Delete: the trigger updates all of the sortOrder fields by -1 if they are > than the field for the one deleted.
On Update (sortOrder). This adds or subtracts from the sortOrder field depending upon whether the number was moved higher or lower than its previous spot.
Now the problem. All of the update table set sortOrder = whatever triggers the On Update.
So is there a way to turn the updating off during other trigger functions?
回答1:
Make this table a view that just gets the data from a base table. Implement INSTEAD OF triggers for INSERT/UPDATE/DELETE that redirect all operations to the base table. Then you can update the sort order in the base table without any of the triggers firing.
It might be easier to update the sort order with code in your program.
回答2:
Well, I found a way. Some folks won't like it, I'm sure, but it's doing the same thing that must be done in code at time. One might want to set a Boolean variable to say that we're filling a box so that the event OnChange can check it and not do anything.
So, as this was all a test, the table is called testTbl that, as well as an id row had an Integer row called sortOrder. This is the trigger that is call AFTER INSERT. It allows the sortOrder to be inserted and it assures that it appears at the proper spot.
DROP TRIGGER "main"."trig_testTbl";
CREATE TRIGGER "main"."trig_testTbl" AFTER INSERT ON "testTbl" FOR EACH ROW
BEGIN
/* tell the trigUpdate table that we're updating*/
UPDATE trigUpdate SET doNotUpdate = 1 WHERE tblName = 'testTbl';
/* do what we need to do */
UPDATE testTbl SET sortOrder = sortOrder + 1
WHERE sortOrder >= New.sortOrder
AND rowid <> New.rowid;
/* Tell it we're done*/
UPDATE trigUpdate SET doNotUpdate = 0 WHERE tblName = 'testTbl';
END;
You'll note the first line after BEGIN sets a field to 1 (True) in a table called trigUpdate.
Here is the WHEN clause on the AFTER UPDATE of sortOrder. There are two triggers that are both called AFTER UPDATE on sortOrder. One is when the new sortOrder is less than the old one, and the other is vica-versa.
New.SortOrder > Old.SortOrder And (SELECT doNotUpdate FROM trigUpdate WHERE tblName = 'testTbl') <> 1
来源:https://stackoverflow.com/questions/26347756/is-there-a-way-to-prevent-update-triggers-from-being-triggered-within-a-delete-a