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.
问题:
在哪里可以获得更新触发器上更新记录的 ID 值?
QUESTION:
Where would I get the value of the ID of the updated record on a UPDATE 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' 开始,表 INSERTED 对 INSERT、UPDATE 触发器是通用的.
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屋!