2013-12-10 39 views
0

我在sql server 2008中創建了一個下面的觸發器,只要在我的W_Data表列PLName中發生更改,它就不會觸發。我在A_Ticket中看到相同的列數。任何人都可以幫我嗎?SQL Server 2008更新觸發器在指定列中發生任何更改時不起作用

CREATE TRIGGER dbo.tr_W_Data 
    ON dbo.W_Data 
    after update 
    AS 
     declare @date datetime 

     select @date = max(Start_Date) from dbo.W_Schedule 

     set NOCOUNT ON; 

     if update(PLName) 

    begin 
     update t set 
     I_S1_O = (select count(*) from W_Data w where [Priority] = 'S1' and [Type] <> 'R' and [A_Group] <> '1' and [C_Date]< @date and w.[Product_Name] = t.[Product_Name]), 
     I_S1_R = (select count(*) from W_Data w where [Priority] = 'S1' and [Type] <> 'R' and [A_Group] <> '1' and [C_Date]>= @date and w.[Product_Name] = t.[Product_Name]), 
     I_S1_Re = (select count(*) from W_Data w where [Priority] = 'S1' and [Type] <> 'R' and [R_Group] <> '1' and [R_Group] is not NULL and w.[Product_Name] = t.[Product_Name]), 
     ..... 
     from ATicket t 
    end 
    go 
+0

這是因爲你的條件。如果update(plname)是什麼意思? –

+0

@AmirrezaKeshavarz任何更新發生在W_Data中的PLName列中,這應該執行更新查詢 – Sathish

+0

您沒有在觸發器中引用任何僞表「插入」或「更新」 - 因此您並不真正查看那些行已更新...... –

回答

0

基本上,觸發器,你應該總是引用InsertedDeleted假表。對於UPDATE聲明,Deleted將包含舊值(更新前),而Inserted將包含新值。

然後,您應該加入這些僞表格,告訴您哪些行已針對您自己的數據表進行了更新,以便對這些數據表執行某些操作 - 或將審計記錄寫入另一個表 - 或者其他內容 - 無論您希望如何做。

但要注意:觸發將火每行一次,幷包含一個單排在Inserted - 它會火每條語句一次,因而往往不是包含多行數據更新。

所以基本上,你的觸發器應是這個樣子:

CREATE TRIGGER dbo.tr_W_Data 
ON dbo.W_Data 
AFTER UPDATE 
AS 
    DECLARE @date DATETIME 

    SELECT @date = MAX(Start_Date) FROM dbo.W_Schedule 

    UPDATE t 
    SET 
    I_S1_O = (select count(*) from dbo.W_Data w where [Priority] = 'S1' and [Type] <> 'R' and [A_Group] <> '1' and [C_Date]< @date and w.[Product_Name] = t.[Product_Name]), 
    I_S1_R = (select count(*) from dbo.W_Data w where [Priority] = 'S1' and [Type] <> 'R' and [A_Group] <> '1' and [C_Date]>= @date and w.[Product_Name] = t.[Product_Name]), 
    I_S1_Re = (select count(*) from dbo.W_Data w where [Priority] = 'S1' and [Type] <> 'R' and [R_Group] <> '1' and [R_Group] is not NULL and w.[Product_Name] = t.[Product_Name]), 
     ..... 
    FROM dbo.ATicket t 
    INNER JOIN Inserted i ON ....(whatever JOIN condition makes sense)..... 
    INNER JOIN Deleted d ON ....(whatever JOIN condition makes sense)..... 
    WHERE 
     d.PLName <> i.PLName -- take those rows where the "PLName" column has been updated 
+0

我已經修改了相同的,但是當我更新表完成並顯示(1行受影響)(7行受影響)。但計數沒有在A_ticket中更新。你能否提出建議,何時觸發器會爲我的案件開火。抱歉提出愚蠢的問題。 – Sathish

+0

@Sathish:每次你更新**你的'dbo.W_Data'表時,觸發器都會觸發。 –