2011-08-12 32 views
1

我試圖創建觸發器:觸發器,可以登錄每一個INSERT變更,刪除

CREATE TRIGGER DataTrigger ON Data AFTER INSERT , DELETE 
AS 
BEGIN 
IF EXISTS(SELECT * FROM Inserted) 

INSERT INTO [dbo].[AuditTrail] 
     ([ActionType] 
     ,[TableName] 
     ,[Name] 
     ,[Time]) 

('INSERT' //Incorrect syntax near 'INSERT' 
    ,'Data' 
    ,SELECT col1 FROM Inserted 
    ,CURRENT_TIMESTAMP //Incorrect syntax near the keyword 'CURRENT_TIMESTAMP') 
END 

,但它一直在說,我有thoes錯誤,有人可以告訴我,我做錯了什麼?
P/S:檢測更新的最佳方法是什麼? 謝謝

回答

4
CREATE TRIGGER DataTrigger ON Data AFTER INSERT , DELETE 
AS 
BEGIN  
    INSERT INTO [dbo].[AuditTrail] 
     ([ActionType] 
     ,[TableName] 
     ,[Name] 
     ,[Time]) 
    SELECT 'INSERT' 
    ,'Data' 
    ,col1 
    ,CURRENT_TIMESTAMP 
    FROM Inserted 

END 

只是爲了澄清。

如果合併正確的話,如果插入多於一行,您的查詢將失敗,以上版本允許多次插入。

IF EXISTS是多餘的,這就是爲什麼它被刪除,如果沒有行將不會有插入到您的審計表。

如果要審覈DELETE你再次需要一個類似的聲明,但使用Deleted表,而不是Inserted

要審覈UPDATE,創建新的觸發器,對於每一個更新的行你得到Inserted條目隨着新的更新和Deleted與舊數據的條目,你可以加入這些,如果你想跟蹤新舊。

+0

不需要IF EXISTS(SELECT * FROM插入)中的語句,我們呢? – Xitrum

3
CREATE TRIGGER DataTrigger ON Data AFTER INSERT , DELETE 
AS 
BEGIN 

INSERT INTO [dbo].[AuditTrail] 
     ([ActionType] 
     ,[TableName] 
     ,[Name] 
     ,[Time]) 
SELECT 'INSERT', 'Data', col1, CURRENT_TIMESTAMP FROM Inserted 

END 
+0

呵呵,快回+1我們 –

1

我不完全確定你在這裏試圖完成什麼,所以我剛剛糾正了語法來讓它工作,但它應該有所幫助。我也曾嘗試處理刪除的情況下,也

CREATE TRIGGER DataTrigger 

ON Data 

AFTER INSERT , DELETE 
AS 
BEGIN 


    INSERT INTO [dbo].[AuditTrail]([ActionType],  
              [TableName],  
              [Name],  
              [Time]) 
    SELECT 'INSERT','Data', col1, CURRENT_TIMESTAMP 
    FROM Inserted 


    INSERT INTO [dbo].[AuditTrail]([ActionType],  
              [TableName],  
              [Name],  
              [Time]) 
    SELECT 'DELETE','Data', col1, CURRENT_TIMESTAMP 
    FROM Deleted 

END