T-SQL触发器更新 [英] T-SQL Trigger Update
问题描述
我有一个包含3个字段的表[ID,名称,LastUpdated]。
LastUpdated的默认值为 GetDate(),因此在添加新记录时它会自动填充自身。
I have a table with 3 fields [ID, Name, LastUpdated].
LastUpdated has a default value of "GetDate() so it automatically fills itself when a new record is added.
当我改为在TABLE上运行UPDATE时,我希望将此字段重置为当前的GetDate()。
When I instead run an UPDATE on TABLE, I would like to have this field reset itself to the current GetDate().
CREATE TRIGGER dbo.Table1_Updated
ON dbo.Table1
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.Table1 SET LastUpdated = GETDATE()
END
GO
但是因为我没有WHERE子句,所有记录都会更新。
But because I don't have a WHERE Clause, ALL records get updated.
问题:
在哪里我可以在UPDATE触发器上获得更新记录的ID的值吗?
QUESTION:
Where would I get the value of the ID of the updated record on a UPDATE Trigger?
我是否要更新触发器内表的字段,调用一个新的Trigger事件(以此类推)?
Would the fact that I'm updating a field of the table inside the Trigger, re-call a new Trigger event (and so on) ?
推荐答案
从'INSERTED'中,表INSERTTED对于两个INSERT都是通用的,向上DATE触发器。
From 'INSERTED', table INSERTED is common to both the INSERT, UPDATE trigger.
CREATE TRIGGER dbo.Table1_Updated
ON dbo.Table1
FOR INSERT, UPDATE /* Fire this trigger when a row is INSERTed or UPDATEd */
AS BEGIN
UPDATE dbo.Table1 SET dbo.Table1.LastUpdated = GETDATE()
FROM INSERTED
WHERE inserted.id=Table1.id
END
这篇关于T-SQL触发器更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!