【问题标题】:Change Tracking of a specific column in SQL Server [closed]SQL Server中特定列的更改跟踪[关闭]
【发布时间】:2015-10-26 06:05:50
【问题描述】:

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

【问题讨论】:

    标签: sql sql-server database sql-server-2012 change-tracking


    【解决方案1】:

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

    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
    

    但请注意,如果触发器太多、触发器操作代价高昂或者它是一个经常更新的表,则性能可能会受到影响。

    【讨论】:

      【解决方案2】:

      您可以创建历史表:

      历史

      account_ID
      column_name
      old_value
      new_value
      

      在该表中,您使用表 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 ind new_value 中插入

      对不起我的英语。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多