2016-03-18 70 views
0

我創建了一個觸發器來更新另一個表中的行,由dbo.update中的更新語句觸發。此觸發器失敗的原因可能是因爲它試圖更新多於一條記錄。我試圖改變這一點,但沒有結果。我想知道:做這件事的正確方法是什麼?子查詢在觸發器上返回了多個值

CREATE TRIGGER 
    [dbo].[Update] 
ON 
    [dbo].[Records] 
FOR UPDATE 
AS 
    BEGIN 
    SET NOCOUNT ON 
     IF (SELECT State FROM INSERTED) = '1' 
     Begin 
     UPDATE dbo.Issue SET state = 1 WHERE EventID = (SELECT EventID FROM INSERTED) 

     DECLARE @IssueID INT 
     SET @issueID = (SELECT IssueID FROM Issue WHERE EventID = (SELECT EventID FROM INSERTED)) 
     UPDATE dbo.Action SET state = 1 WHERE IssueID = @issueID 

    end 
     IF (SELECT State FROM INSERTED) = '0' 
     Begin 
     UPDATE dbo.Issue SET state = 0 WHERE EventID = (SELECT EventID FROM INSERTED) 

     SET @issueID = (SELECT IssueID FROM Issue WHERE EventID = (SELECT EventID FROM INSERTED)) 
     UPDATE dbo.Action SET state = 0 WHERE IssueID = @issueID 

    end 
END 
+0

'IF(SELECT State FROM INSERTED)='1'' ...使用遊標讀取表格。 – jarlh

回答

2

您對診斷正確無誤。我想你想使用join的兩個update s到更換整個ifinserted:當只有一個記錄更新

UPDATE i 
    SET state = ii.state 
    FROM dbo.Issue i JOIN 
     inserted ii 
     ON i.EventID = ii.EventID 
    WHERE ii.state IN (0, 1); 

UPDATE a 
    SET state = ii.state 
    FROM dbo.Action a JOIN 
     dbo.Issue i 
     ON a.EventId = i.EventId JOIN 
     inserted ii 
     ON a.IssueId = ii.IssueId 
    WHERE ii.state IN (0, 1); 
+0

該查詢的工作原理 – TheGameiswar

0

你更新纔會工作。如果在批次/交易中更新了多個記錄,則INSERTED將在其中包含多個記錄,這就是您的代碼出錯時的情況。您可以嘗試以下查詢:

UPDATE dbo.Issue 
SET state = INSERTED.State 
FROM 
INSERTED 
WHERE dbo.Issue.EventId = INSERTED.EventId 
AND INSERTED.State in (0, 1) 

UPDATE dbo.Action 
SET State = INSERTED.State 
FROM 
INSERTED 
JOIN Issue on INSERTED.EventID = Issue.EventID 
WHERE 
INSERTED.State in (0,1) 
+0

這看起來很像以前的答案。 –