仅在实际更改值时才触发表的更新

时间:2016-07-20 10:05:12

标签: sql sql-server triggers

有没有办法创建一个触发器,只有在实际数据发生变化时才更新表?

下面你可以看到我的触发器,如果​​idu_idmanager_id更新,它将触发。但是,如果您强制更改发生,如1更改为1,即使更新的表将保持不变,它仍然会触发。

ALTER TRIGGER [dbo].[TRG_UpdatePersonal]
   ON  [dbo].[HC_EMP] 
   FOR UPDATE AS IF ( UPDATE([manager_id]) OR UPDATE([idu_id])) 

    DECLARE @user_login VARCHAR(50)
    DECLARE @Action varchar (10)
    SELECT @user_login = dbo.udf_GetUserLogin()

BEGIN
IF UPDATE (idu_id)
Insert into [dbo].[HC_HISTORY]
(

    [EmpID]
   ,[ACTIONDATE]
   ,[TYPEID]
   ,[MESSAGE]
   ,[InitiatorID]
   ,[OldIdu]
   ,[NewIdu]
)
select

   d.[company_id]
   ,GETUTCDATE()
   ,3
   ,'Some Data'
   ,@user_login
   ,d.idu_id
   ,i.idu_id
from Deleted d join INSERTED i on d.company_id = i.company_id

IF UPDATE (manager_id)
Insert into [dbo].[HC_HISTORY]
(   
   [EmpID]
   ,[ACTIONDATE]
   ,[TYPEID]
   ,[MESSAGE]
   ,[InitiatorID]
   ,[OldManagerId]
   ,[NewManagerId]
)
select

   d.[company_id]
   ,GETUTCDATE()
   ,4
   ,'Some Other Data'
   ,@user_login
   ,d.manager_id
   ,i.manager_id
from Deleted d join INSERTED i on d.company_id = i.company_id
END

1 个答案:

答案 0 :(得分:1)

在where子句中添加过滤器。试试这个,

ALTER TRIGGER [dbo].[TRG_UpdatePersonal] ON [dbo].[HC_EMP]
FOR UPDATE
AS
IF (
        UPDATE ([manager_id])
            OR
        UPDATE ([idu_id])
        )
    DECLARE @user_login VARCHAR(50)
DECLARE @Action VARCHAR(10)

SELECT @user_login = dbo.udf_GetUserLogin()

BEGIN
    INSERT INTO [dbo].[HC_HISTORY] (
        [EmpID]
        ,[ACTIONDATE]
        ,[TYPEID]
        ,[MESSAGE]
        ,[InitiatorID]
        ,[OldIdu]
        ,[NewIdu]
        )
    SELECT d.[company_id]
        ,GETUTCDATE()
        ,3
        ,'Some Data'
        ,@user_login
        ,d.idu_id
        ,i.idu_id
    FROM Deleted d
    JOIN INSERTED i ON d.company_id = i.company_id
    WHERE d.idu_id <> i.idu_id

    INSERT INTO [dbo].[HC_HISTORY] (
        [EmpID]
        ,[ACTIONDATE]
        ,[TYPEID]
        ,[MESSAGE]
        ,[InitiatorID]
        ,[OldManagerId]
        ,[NewManagerId]
        )
    SELECT d.[company_id]
        ,GETUTCDATE()
        ,4
        ,'Some Other Data'
        ,@user_login
        ,d.manager_id
        ,i.manager_id
    FROM Deleted d
    JOIN INSERTED i ON d.company_id = i.company_id
    WHERE d.manager_id <> i.manager_id
END