Asynchronous Triggers in SQL Server 2005/2008

后端 未结 10 1041
-上瘾入骨i
-上瘾入骨i 2020-12-08 09:51

I have triggers that manipulate and insert a lot of data into a Change tracking table for audit purposes on every insert, update and delete.

This t

10条回答
  •  半阙折子戏
    2020-12-08 10:14

    SQL Server 2014 introduced a very interesting feature called Delayed Durability. If you can tolerate loosing a few rows in case of an catastrophic event, like a server crash, you could really boost your performance in schenarios like yours.

    Delayed transaction durability is accomplished using asynchronous log writes to disk. Transaction log records are kept in a buffer and written to disk when the buffer fills or a buffer flushing event takes place. Delayed transaction durability reduces both latency and contention within the system

    The database containing the table must first be altered to allow delayed durability.

    ALTER DATABASE dbname SET DELAYED_DURABILITY = ALLOWED
    

    Then you could control the durability on a per-transaction basis.

    begin tran
    
    insert into ChangeTrackingTable select * from inserted
    
    commit with(DELAYED_DURABILITY=ON)
    

    The transaction will be commited as durable if the transaction is cross-database, so this will only work if your audit table is located in the same database as the trigger.

    There is also a possibility to alter the database as forced instead of allowed. This causes all transactions in the database to become delayed durable.

    ALTER DATABASE dbname SET DELAYED_DURABILITY = FORCED
    

    For delayed durability, there is no difference between an unexpected shutdown and an expected shutdown/restart of SQL Server. Like catastrophic events, you should plan for data loss. In a planned shutdown/restart some transactions that have not been written to disk may first be saved to disk, but you should not plan on it. Plan as though a shutdown/restart, whether planned or unplanned, loses the data the same as a catastrophic event.

    This strange defect will hopefully be addressed in a future release, but until then it may be wise to make sure to automatically execute the 'sp_flush_log' procedure when SQL server is restarting or shutting down.

提交回复
热议问题