2012-10-10 48 views
2

我已經爲SQL Server 2008中的表寫入了一個SQL觸發器。它在'inserted'表中只有一行時工作正常。如何修改此觸發器在有多行時正確工作?性能是關鍵,所以我想遠離遊標,臨時表等(如果可能的話)。當插入的表包含多行時,修改SQL觸發器以工作

本質上,觸發器檢查是否更改了'ClientID'或'TemplateID'字段。如果它們是,並且OriginalClientID或OriginalTemplateID字段爲空,它會填充它們(因此,一次只設置一次OriginalXXX字段,以便始終可以看到第一個值是什麼)。

CREATE TRIGGER [dbo].[trigSetOriginalValues] 
    ON [dbo].[Review] 
    FOR INSERT, UPDATE 
AS 
BEGIN 
    IF (NOT UPDATE(TemplateID) AND NOT UPDATE(ClientID)) return 

    DECLARE @TemplateID int 
    DECLARE @OriginalTemplateID int 
    DECLARE @ClientID int 
    DECLARE @OriginalClientID int 
    DECLARE @ReviewID int 

    SET @ReviewID = (SELECT ReviewID FROM inserted) 
    SET @ClientID = (SELECT ClientID FROM inserted) 
    SET @TemplateID = (SELECT TemplateID FROM inserted) 
    SET @OriginalTemplateID = (SELECT OriginalTemplateID FROM inserted); 
    SET @OriginalClientID = (SELECT OriginalClientID FROM inserted); 

    IF (@OriginalTemplateID IS NULL AND @TemplateID IS NOT NULL) 
    BEGIN 
     UPDATE [dbo].[Review] SET OriginalTemplateID = @TemplateID WHERE [email protected] 
    END 

    IF (@OriginalClientID IS NULL AND @ClientID IS NOT NULL) 
    BEGIN 
     UPDATE [dbo].[Review] SET OriginalClientID = @ClientID WHERE [email protected] 
    END 
END 

回答

5

這應該是你的觸發器:

UPDATE A 
SET A.OriginalTemplateID = B.TemplateID 
FROM [dbo].[Review] A 
INNER JOIN INSERTED B 
    ON A.ReviewID = B.ReviewID 
WHERE A.OriginalTemplateID IS NULL AND B.TemplateID IS NOT NULL 

UPDATE A 
SET A.OriginalClientID = B.ClientID 
FROM [dbo].[Review] A 
INNER JOIN INSERTED B 
    ON A.ReviewID = B.ReviewID 
WHERE A.OriginalClientID IS NULL AND B.ClientID IS NOT NULL 

雖然你仍然可以做到這一點在單UPDATE,但更復雜的過濾器。