2013-10-22 89 views

回答

6

CREATE_USER is absolutely a trackable DDL event,因爲是DROP_USER,並且兩者都自SQL Server 2005.以來。BOL is hard-pressed for decent examples, though。事實是,DDL觸發事件數據模式不夠靈活,總是有一個以你想要的方式命名的實體(如UserName)。這不是直觀的,也可以是你的問題的根源,但實際上你需要從ObjectName拉創建的用戶名:

USE [your_database_name]; 
GO 

CREATE TRIGGER CatchUser 
ON DATABASE 
FOR CREATE_USER, DROP_USER 
AS 
BEGIN 
    SET NOCOUNT ON; 

    DECLARE @x XML = EVENTDATA(); 

    -- INSERT dbo.LoggingTable(Columns) 
    SELECT 
    EventType = @x.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(256)'), 
    UserName = @x.value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(256)'), 
    LoginName = @x.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(512)'), 
    StartTime = @x.value('(/EVENT_INSTANCE/PostTime)[1]', 'datetime'); 
END 

但是,如果你只是想在事後審覈這些數據,如果您足夠頻繁地進行輪詢,您還可以從默認跟蹤中獲取此信息。

DECLARE @path NVARCHAR(260); 

SELECT @path = REVERSE(SUBSTRING(REVERSE([path]), 
    CHARINDEX(CHAR(92), REVERSE([path])), 260)) + N'log.trc' 
FROM sys.traces WHERE is_default = 1; 

SELECT EventType = CASE EventSubClass WHEN 3 THEN 'CREATE_USER' 
    WHEN 4 THEN 'DROP_USER' END, TargetUserName, LoginName, StartTime 
FROM sys.fn_trace_gettable(@path, DEFAULT) 
WHERE EventClass = 109 -- Create DB User Event 
AND DatabaseName = N'your_database_name' 
ORDER BY StartTime DESC; 

這將得到增加和下降,你應該能夠從EventSubClass告訴它是哪個事件,但我的經驗是不與the documentation匹配 - 我得到3加,4滴,但他們說1是Add,2是Drop,3是授權訪問,4是撤銷訪問。 聳肩