How can I handle multiple rows into a update trigger/how to modify my actual trigger to have the current behaviour? If I update only one row works great but if I update multiple rows in the same time I get the error:
Msg 512, Level 16, State 1, Procedure TriggerUpdateAdvert, Line 9
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
This is my trigger:
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
Edit:
I created next code:
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))
Do you have any ideas?
Insertedpseudo table can contain multiple rows - so in that case - which of those multiple rows are you selecting here???SET @ID=(SELECT I.ID_Advert FROM INSERTED I);.... you need to rewrite your trigger to take multiple rows into account and handle them appropriately!