2014-01-21 61 views
1

如何使用SQL Server 2005中的其他代碼替換合併查詢,代碼爲 以獲得相同的功能。用一些其他代碼代替SQL Server中的合併

alter trigger [Emp_Update_Logging] on [Employee_Test] 
    after update 
    as 


    MERGE INTO dbo.Emp_Log EL 
    USING INSERTED I 
     ON EL.EID = I.Emp_ID 
    WHEN MATCHED THEN 
    UPDATE 
     SET EL.ModifiedDate = getdate() 
    WHEN NOT MATCHED THEN 
     INSERT(EID,ModifiedDate) 
     VALUES(I.Emp_ID,getdate()); 

    go 

回答

2

你基本上需要,打破了MERGE到兩個操作 - 一個INSERT對於尚不存在這些行,和UPDATE對於那些已經存在的那些行。

像這樣的東西可能會奏效:

ALTER TRIGGER [Emp_Update_Logging] ON [Employee_Test] 
AFTER UPDATE 
AS 
    -- insert those rows from Inserted that don't exist yet 
    INSERT INTO dbo.Emp_Log(EID, ModifiedDate) 
     SELECT I.Emp_ID, GETDATE() 
     FROM Inserted i 
     WHERE NOT EXISTS (SELECT * FROM dbo.Emp_Log WHERE EID = i.Emp_ID) 

    -- update those rows that already exist 
    UPDATE dbo.Emp_Log 
    SET ModifiedDate = GETDATE() 
    FROM Inserted i 
    WHERE EXIST (SELECT * FROM dbo.Emp_Log WHERE EID = i.Emp_ID) 

然而,由於這是一個UPDATE觸發器,我認爲你將永遠不會有不存在尚未行 - 畢竟,這只是觸發火災發生時已更新現有行 .....