更新插入时的MSSql触发器(Updatecounter)

时间:2013-04-09 07:26:42

标签: sql-server triggers

我有一个名为Table1的表,其中包含两个字段Systemname和Updatecount。 每个带有Systemname“SAP”的插入都应将Updatecount设置为1(初始值)。 如果Field Systemname获得具有已定义值“SAP”的更新,则Field Updatecount应增加1。

如何定义触发器?

2 个答案:

答案 0 :(得分:5)

create trigger tr on Table1 for insert,update
as
begin
    if update(Systemname)
        update Table1
            set UpdateCount = (case when not exists(select * from deleted) then 1 else UpdateCount + 1 end)
        from Table1
        inner join inserted on Table1.[<YourPKField>] = inserted.[<YourPKField>]
        where inserted.Systemname = 'SAP'
end
GO

答案 1 :(得分:3)

这里有一篇关于触发器的好文章:

http://www.codeproject.com/Articles/38808/Overview-of-SQL-Server-database-Triggers

您需要创建:

CREATE TRIGGER [TRIGGER_ALTER_COUNT] ON [dbo].[tblTriggerExample] 
FOR INSERT, UPDATE
AS
BEGIN
 DECLARE @Var INT 
 SELECT @Var = COUNT(*) FROM INSERTED
 UPDATE [dbo].[tblTriggerExample] SET AlterCount = AlterCount + Var  
          ,LastUpdate = GETDATE()
    WHERE TransactionID = @TransID
 SELECT @Var = COUNT(*) FROM UPDATED WHERE SystemNAme = 'Var'
 UPDATE [dbo].[tblTriggerExample] SET AlterCount = AlterCount + @Var
          ,LastUpdate = GETDATE()
    WHERE TransactionID = @TransID
END