SQL 服务器中特定列的更改跟踪

Change Tracking of a specific column in SQL Server

我在 SQL 服务器数据库中有一个重要的列(Balance 属性 of Account table)。我在我的程序中跟踪并记录此 属性,但我也想在数据库级别跟踪和保存此列的更改。我不想跟踪 table 的所有属性,因为它对我来说并不重要。请帮我找到一个好的解决方案。

您可以使用触发器来插入更改、插入或删除到一种类型的审计table。

https://msdn.microsoft.com/en-AU/library/ms189799(v=sql.110).aspx

CREATE TRIGGER yourInsertTrigger ON Account
FOR INSERT
AS

INSERT INTO yourAuditTable
        (balance, user_id, user_name)
    SELECT
        inserted.balance, user_id, user_name
        FROM inserted
go

请注意,如果触发器过多、触发器操作成本高昂或者 table 经常更新,性能可能会受到影响。

你可以创造历史table:

历史

account_ID
column_name
old_value
new_value

在 table 中,您使用 table Account 插入每个更改。 为此,您可以使用触发器:

CREATE TRIGGER account_UID on Account
FOR INSERT,UPDATE,DELETE
AS
BEGIN
  -- for update
  INSERT INTO history (account_ID, column_name, old_value, new_value)
    SELECT I.account_ID, 'balance', D.balance, I.balance
      FROM inserted as I left join deleted as D on I.account_ID = D.account_ID
    where D.account_ID is not null and I.balance <> D.balance

  -- for insert
  INSERT INTO history (account_ID, column_name, old_value, new_value)
    SELECT I.account_ID, 'balance', null, I.balance
      FROM inserted as I left join deleted as D on I.account_ID = D.account_ID
    where D.account_ID is null

  -- for delete
  INSERT INTO history (account_ID, column_name, old_value, new_value)
    SELECT D.account_ID, 'balance', D.balance, null
      FROM deleted as D left join inserted as I on D.account_ID = I.account_ID
    where D.account_ID is not null
END   

where 子句很重要,因为在插入新行时需要在 old_value 中插入 null,在删除行

时需要在 null 中插入 new_value

对不起我的英语。