通过T-SQL读取SQL事务日志

时间:2015-10-29 05:59:53

标签: sql-server tsql

这是我从备份文件中读取SQL事务日志(脱机日志)的脚本。

我希望所有 INSERT / UPDATE / DELETE 都由T-SQL执行(不包括使用SSMS GUI的操作)

DECLARE @From DATETIME, @To DATETIME
DECLARE @FilePath NVARCHAR(1000)

SET @FilePath = N'D:\abc.BAK'
SET @From ='2015/10/01 00:00:00'
SET @To ='2015/10/31 00:00:00'

SELECT *
INTO #Log
FROM fn_dump_dblog (
        NULL, NULL, N'DISK', 1, @FilePath,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT,
        DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT)

SELECT  l.[Transaction Name],
            objectName.schemaname AS [Schema],
            objectName.name AS [Object],
        SUSER_SNAME (l.[Transaction SID]) AS [User],
        l.[Begin Time],
        endTime.[End Time],
        l.[Transaction ID]        
FROM #Log AS l
INNER JOIN (
            SELECT l.[Transaction ID], l.[End Time]
            FROM #Log AS l
            WHERE Operation = 'LOP_COMMIT_XACT'       
) AS endTime ON l.[Transaction ID] = endTime.[Transaction ID]
INNER JOIN(
      SELECT [Transaction ID],AllocUnitName  FROM #Log AS l
      WHERE AllocUnitName IS NOT NULL
      GROUP BY [Transaction ID], AllocUnitName
) AS alloc ON l.[Transaction ID] = alloc.[Transaction ID]
LEFT JOIN (
      SELECT i.object_id, i.name AS IndexName,o.name,s.name+'.'+o.name+'.'+i.name AS keyname,s.name AS schemaname FROM sys.indexes AS i
      INNER JOIN sys.objects AS o ON i.object_id = o.object_id
      INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
) AS objectName ON alloc.AllocUnitName = objectName.keyname
WHERE Operation = 'LOP_BEGIN_XACT'
      AND [Transaction Name] IN ('INSERT','UPDATE','DELETE')
      AND l.[Begin Time] BETWEEN @From AND @To
ORDER BY l.[Transaction ID]

DROP TABLE #Log

所以问题是:

  1. 我已经测试过这个脚本,它适用于大多数情况。你知道有没有遗漏的案子吗?
  2. 对于这种情况你有更好的解决方案吗?

    感谢您的贡献

0 个答案:

没有答案