我创建了一个触发器来更新另一个表中的行,由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 :(得分:2)
你的诊断是正确的。我想您想要使用if
将update
替换为join
个inserted
来填充 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++)