如何从事务日志文件中获取用户在SQL Server(.ldf文件)中没有像ApexSqlLog这样的应用程序

时间:2012-10-18 13:26:10

标签: sql sql-server tsql

如何从SQL Server中的事务日志文件中获取用户?

我尝试了这个查询,但它没有给我正确的用户

SELECT 
CASE 
  WHEN (SELECT NAME 
          FROM SYS.SERVER_PRINCIPALS lgn 
         WHERE Rtrim(lgn.SID) = Rtrim(log2.[TRANSACTION SID])) IS NOT 
       NULL THEN 
  'login: ' 
+ Upper((SELECT NAME FROM SYS.SERVER_PRINCIPALS lgn WHERE Rtrim(lgn.SID) 
  = Rtrim 
(log2.[TRANSACTION SID]))) 
  ELSE 'db user: ' 
       + Upper((SELECT NAME FROM SYS.SERVER_PRINCIPALS lgn WHERE Rtrim( 
       lgn.SID) 
       = Rtrim(log2.[TRANSACTION SID] ))) 
END 
AS 'Login_or_User', 
log1.*, 
CASE log1.__$OPERATION 
  WHEN 1 THEN 'DELETE' 
  WHEN 2 THEN 'INSERT' 
  WHEN 4 THEN 'UPDATED VALUE' 
  WHEN 3 THEN 'PREVIOUS UPDATED VALUE' 
  ELSE NULL 
END 
AS operation, 
CONVERT(VARCHAR(19), log2.[BEGIN TIME])                                                                                                                 AS 'Begin Time',
LEFT(log.ALLOCUNITNAME, Charindex('.', log.ALLOCUNITNAME) - 1) 
AS 'Schema', 
LEFT(RIGHT(log.ALLOCUNITNAME, Len(log.ALLOCUNITNAME) - 
                                   Charindex('.', log.ALLOCUNITNAME)), 
Charindex('.', RIGHT(log.ALLOCUNITNAME, 
Len(log.ALLOCUNITNAME) 
- 
                                                                                                               Charindex('.', log.ALLOCUNITNAME))) - 1) AS 'Object',
SYS.Fn_cdc_hexstrtobin(Substring(log.[CURRENT LSN], 1, 8) 
                       + Substring(log.[CURRENT LSN], 10, 8) 
                       + 
Substring(log.[CURRENT LSN], 19, 4))                                                                                           currentlsn
  FROM DBO.TEMPTABLE log1 
       LEFT JOIN ::FN_DBLOG(NULL, NULL) log 
              ON log1.__$SEQVAL = SYS.Fn_cdc_hexstrtobin( 
                                  Substring(log.[CURRENT LSN], 1, 8) 
                                  + Substring(log.[CURRENT LSN], 10, 8) 
                                  + Substring(log.[CURRENT LSN], 19, 4)) 
       LEFT JOIN ::FN_DBLOG(NULL, NULL)log2 
              ON log.[TRANSACTION ID] = log2.[TRANSACTION ID] 
       LEFT JOIN SYS.ALLOCATION_UNITS au 
              ON log.ALLOCUNITID = au.ALLOCATION_UNIT_ID 
       LEFT JOIN SYS.PARTITIONS p 
              ON p.PARTITION_ID = au.CONTAINER_ID 
       LEFT JOIN SYS.OBJECTS so 
              ON so.OBJECT_ID = p.OBJECT_ID 
       LEFT JOIN SYS.SERVER_PRINCIPALS spa 
              ON spa.SID = log2.[TRANSACTION ID] 

此代码用于检查已启用CDC(CHange数据捕获)的数据库然后选择特定表以获取其上的更改

1 个答案:

答案 0 :(得分:0)

您始终可以在表上设置触发器以捕获对该表插入,更新或删除数据的任何用户的PK,getdate()和suser_id()。然后,您可以跟CDC一起追踪它,以满足您的需求。我意识到人们希望远离触发器,但它是一个简单易用的解决方案。