在sql触发器更新中处理多行

时间:2013-11-26 13:02:24

标签: sql-server tsql triggers sql-update

如何将多行处理为更新触发器/如何修改我的实际触发器以获得当前行为?如果我只更新一行效果很好,但如果我在同一时间更新多行,我会收到错误:

  

Msg 512,Level 16,State 1,Procedure TriggerUpdateAdvert,Line 9
  子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

这是我的触发器:

 ALTER TRIGGER dbo.TriggerUpdateAdvert
 ON dbo.Advert FOR UPDATE
 AS
    DECLARE @OldStatus INT;
    DECLARE @NewStatus INT;
    DECLARE @ID UNIQUEIDENTIFIER;

    SET @ID=(SELECT I.ID_Advert FROM INSERTED I);
    PRINT @ID
    SET @OldStatus=(SELECT D.Status FROM DELETED D WHERE D.ID_Advert=@ID);
    SET @NewStatus=(SELECT I.Status FROM INSERTED I WHERE I.ID_Advert=@ID);


    IF(@OldStatus!=@NewStatus)
    BEGIN
    print @OldStatus
    print @NewStatus
        IF(@NewStatus=1 or @NewStatus=3)
        BEGIN
            UPDATE Advert SET Published_Date=GETDATE() WHERE ID_Advert=@ID
        END
    END


 GO

编辑:

我创建了下一个代码:

        UPDATE A
        SET A.Published_Date=GETDATE()
        FROM Advert A
        INNER JOIN Inserted I ON A.ID_Advert=I.ID_Advert
        INNER JOIN Deleted D ON D.ID_Advert=A.ID_Advert
        WHERE I.Status!=D.Status  AND (I.Status IN (1,3) AND D.Status NOT IN (1,3)) 

你有什么想法吗?

2 个答案:

答案 0 :(得分:2)

避免在触发器中使用PRINT。

并按照以下方式定义:

 ALTER TRIGGER dbo.TriggerUpdateAdvert
 ON dbo.Advert FOR UPDATE
 AS
   UPDATE Advert SET Published_Date=GETDATE() 
   WHERE ID_Advert IN (
     SELECT i.id 
     FROM inserted i 
     INNER JOIN deleted d 
     ON i.ID_Advert = d.ID_Advert
     WHERE i.Status <> d.Status
     AND i.Status IN (1,3)
   )
 END

答案 1 :(得分:1)

UPDATE a SET Published_Date = CURRENT_TIMESTAMP
  FROM dbo.Advert AS a
  INNER JOIN inserted AS i ON a.ID_Advert = i.ID_Advert
  INNER JOIN deleted AS d  ON i.ID_Advert = d.ID_Advert
  WHERE i.Status IN (1,3) AND d.Status <> i.Status;