我有一张 table :
项目
itemID int autoincrement
itemName text
itemAvailability
itemID integer REFERENCES Items (itemID)
availability integer DEFAULT 0
我需要一个触发器来做:
当用户将一条记录添加到 Items 表中时,触发器必须自动将一条记录添加到 itemAvailability 表中。
itemAvailability.itemID=元素.itemID
此刻我来到了这一点并卡住了:
CREATE TRIGGER updateItemsAvailabilityTbl AFTER INSERT ON items
BEGIN
INSERT INTO itemAvailability (itemID)
VALUES (items.itemID)
END
嗯,这对我不起作用。请帮忙。
最佳答案
您的 CREATE TRIGGER 语句中有两个错误。 1. 如 documentation 中所写
trigger actions may access elements of the row being inserted, deleted or updated using references of the form "NEW.column-name" and "OLD.column-name", where column-name is the name of a column from the table that the trigger is associated with. OLD and NEW references may only be used in triggers on events for which they are relevant, as follows:
INSERT NEW references are valid
UPDATE NEW and OLD references are valid
DELETE OLD references are valid
所以你应该写new.itemID
而不是items.itemID
。 2. INSERT INTO 语句应该以分号结束。试试这个:
CREATE TRIGGER updateItemsAvailabilityTbl AFTER INSERT ON items
BEGIN
INSERT INTO itemAvailability (itemID)
VALUES (new.itemID);
END
关于ios - 触发自动向另一个表添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8105015/