6

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

如何定义触发器?

4

2 回答 2

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
于 2013-04-09T07:38:14.963 回答
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
于 2013-04-09T07:41:35.403 回答