2010-07-02 93 views
3

以下是SQL Server 2005更新觸發器。對於isActive標誌更改的email_subscriberList表上的每個更新,我們都會將審計記錄插入到email_Events表中。這對於單個更新工作正常,但批量更新只記錄最後更新的行。如何轉換下面的代碼以更新每行的插入內容?用於批量更新的SQL Server更新觸發器

CREATE TRIGGER [dbo].[Email_SubscriberList_UpdateEmailEventsForUpdate_TRG] 
ON [dbo].[Email_subscriberList] 
FOR UPDATE 
AS 
DECLARE @CustomerId int 
DECLARE @internalId int 
DECLARE @oldIsActive bit 
DECLARE @newIsActive bit 
DECLARE @email_address varchar(255) 
DECLARE @mailinglist_name varchar(255) 
DECLARE @email_event_type varchar(1) 

SELECT @oldIsActive = isActive from Deleted 
SELECT @newIsActive = isActive from Inserted 

IF @oldIsActive <> @newIsActive 

BEGIN 

IF @newIsActive = 1 
    BEGIN 
    SELECT @email_event_type = 'S' 
    END 
ELSE 
    BEGIN 
    SELECT @email_event_type = 'U' 
    END 


SELECT @CustomerId = customerid from Inserted 
SELECT @internalId = internalId from Inserted 
SELECT @email_address = (select email from customer where customerid = @CustomerId) 
SELECT @mailinglist_name = (select listDescription from Email_lists where internalId = @internalId) 

INSERT INTO Email_Events 
(mailshot_id, date, email_address, email_event_type, mailinglist_name) 
VALUES 
(@internalId, getDate(), @email_address, @email_event_type,@mailinglist_name) 

END 
+0

你是如何進行批量更新的? – Rup 2010-07-02 14:52:00

+0

多個應用程序將更新此表。 – 2010-07-02 14:54:34

回答

2

例如

未測試

CREATE TRIGGER [dbo].[Email_SubscriberList_UpdateEmailEventsForUpdate_TRG] 
ON [dbo].[Email_subscriberList] 
FOR UPDATE 
AS 


INSERT INTO Email_Events 
(mailshot_id, date, email_address, email_event_type, mailinglist_name) 
SELECT i.internalId,getDate(),c.email, 
case i.isActive when 1 then 'S' else 'U' end,e.listDescription 
from Inserted i 
join deleted d on i.customerid = d.customerid 
and i.isActive <> d.isActive 
join customer c on i.customerid = c.customerid 
join Email_lists e on e.internalId = i.internalId 
+0

不會記錄所有更新,不只是那些IsActive更改的更新? – 2010-07-02 15:11:13

+0

增加了另一個連接 – SQLMenace 2010-07-02 15:38:50

2

左外連接,爲萬一有在客戶或email_Lists沒有相關條目(如在當前的代碼是可能的) - 使它們內如果您知道會有數據存在(即外鍵已到位),則加入。

CREATE TRIGGER [dbo].[Email_SubscriberList_UpdateEmailEventsForUpdate_TRG] 
ON [dbo].[Email_subscriberList] 
FOR UPDATE 
AS 

INSERT INTO Email_Events 
    (mailshot_id, date, email_address, email_event_type, mailinglist_name) 
select 
    i.InternalId 
    ,getdate() 
    ,cu.Email 
    ,case i.IsaActive 
     when 1 then 'S' 
     else 'U' 
    end 
    ,el.ListDescription 
    from inserted i 
    inner join deleted d 
    on i.CustomerId = d.CustomerId 
    and i.IsActive <> d.IsActive 
    left outer join Customer cu 
    on cu.CustomerId = i.CustomerId 
    left outer join Email_Lists el 
    on el.InternalId = i.InternalId 

測試的很好,特別是對於併發問題。觸發器內的這些連接讓我感到緊張。