如何通过写入触发器维护MS SQL中的表日志(每个更改)历史记录

时间:2018-02-06 06:21:12

标签: sql sql-server triggers

我们只想通过写入触发器维护MS SQL中的表日志(每个更改)历史记录

我试过但没有工作

CREATE TRIGGER [dbo].[update_ServiceDescriptionTable]
ON ServiceDescriptionMaster
After UPDATE
AS
BEGIN
        declare @Rate money;
        Select @Rate = Rate from inserted;

        update [dbo].[ServiceDescriptionMasterlog] set Rate = @Rate 
        where Service_Description = '';
END

1 个答案:

答案 0 :(得分:1)

雅好。 如果要维护evry更改日志,则可以在所有字段中插入相同的日志表,如下所示:

1)创建与" ServiceDescriptionMasterlog"相同的表格。 with one Extra Field(Column)Entry_DateTime set default bind getdate()method。

2)在" ServiceDescriptionMaster"上写一个触发器表格如下:

ALTER TRIGGER [dbo].[ServiceDescriptionMaster_OnUpdate]
ON [dbo].[ServiceDescriptionMaster]
After UPDATE
AS
BEGIN
       SET NOCOUNT ON; 
       INSERT INTO [dbo].[ServiceDescriptionMasterLog]
       (S_No,Rate,.....)
       select S_No,Rate,.....
       from Deleted;
END

你也可以继续删除:

ALTER TRIGGER [dbo].[ServiceDescriptionMaster_OnDelete]
ON [dbo].[ServiceDescriptionMaster]
For Delete
AS
BEGIN
       SET NOCOUNT ON; 
       INSERT INTO [dbo].[ServiceDescriptionMasterLog]
       (S_No,Rate,.....)
       select S_No,Rate,.....
       from Deleted;
END