子查询在触发器上返回了多个值

时间:2016-03-18 11:41:35

标签: sql sql-server

我创建了一个触发器来更新另一个表中的行,由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

2 个答案:

答案 0 :(得分:2)

你的诊断是正确的。我想您想要使用ifupdate替换为joininserted来填充 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);

ParentController

答案 1 :(得分:0)

只有更新了一条记录时,您的更新才有效。如果在批处理/事务中有多个记录已更新,则INSERTED将在其中包含多个记录,这时代码将出错。您可以尝试以下查询:

for (int a = 0; a < arr.Length; a++)