SQL Server中特定列的更改跟踪

SQL Server中特定列的更改跟踪,sql,sql-server,database,sql-server-2012,change-tracking,Sql,Sql Server,Database,Sql Server 2012,Change Tracking,我在SQL Server数据库中有一个重要的Account表列平衡属性。我在程序中跟踪并记录此属性,但也希望在数据库级别跟踪并保存此列的更改。我不想跟踪表的所有属性,因为它对我来说并不重要。请帮助我找到一个好的解决方案。您可以使用触发器插入更改、插入或删除一种类型的审核表 但需要注意的是,如果触发器太多、触发器操作太昂贵或是经常更新的表,性能可能会受到影响。您可以创建历史记录表: 历史 在该表中,插入表Account的所有更改。 为此,您可以使用触发器: CREATE TRIGGER accou

我在SQL Server数据库中有一个重要的Account表列平衡属性。我在程序中跟踪并记录此属性,但也希望在数据库级别跟踪并保存此列的更改。我不想跟踪表的所有属性,因为它对我来说并不重要。请帮助我找到一个好的解决方案。

您可以使用触发器插入更改、插入或删除一种类型的审核表


但需要注意的是,如果触发器太多、触发器操作太昂贵或是经常更新的表,性能可能会受到影响。

您可以创建历史记录表:

历史

在该表中,插入表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子句很重要,因为插入新行时需要在旧值中插入null,删除行时需要在新值中插入null

对不起我的英语

account_ID
column_name
old_value
new_value
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