1

I've got problems with my triggers (add and delete):

ALTER TRIGGER [trgAfterShoppingInserted]
ON [ShopingList] AFTER INSERT 
AS BEGIN
   DECLARE @cardId char(6), @points int, @userId int

   SET @cardId = (SELECT cardId FROM inserted)
   SET @points = (SELECT points FROM inserted)
   SET @userId = (SELECT userId from [Card] WHERE id = @cardId)
   IF @userId = 0
   BEGIN
   Update [Card]
   set points = points + @points
   where id =@cardId
   END
   ELSE
   Update [Card]
   set points = points + @points
   where id =@cardId OR
   userId = @userId
END


ALTER TRIGGER [trgAfterShoppingDeleted]
ON [ShopingList] AFTER DELETE 
AS BEGIN
   DECLARE @cardId char(6), @points int, @userId int

   SET @cardId = (SELECT cardId FROM inserted)
   SET @points = (SELECT points FROM inserted)
   SET @userId = (SELECT userId from [Card] WHERE id = @cardId)
   IF @userId = 0
   BEGIN
   Update [Card]
   set points = points - @points
   where id =@cardId
   END
   ELSE
   Update [Card]
   set points = points - @points
   where id =@cardId OR
   userId = @userId
END

The problem is on the SET @cardId..

The error is:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

how is it possibile ?

thanks for any help

4

2 回答 2

2

如果您的 insert 或 delete 语句应该插入或删除多行,则这两个触发器都将不起作用。您需要停止假设您的触发器仅处理单行 - 事实并非如此。您需要重写触发器以一次处理多行(在InsertedDeleted表中)

作为一个例子 - 你可以重写你的trgAfterShoppingDeleted东西是这样的:

ALTER TRIGGER [trgAfterShoppingDeleted]
ON [ShopingList] AFTER DELETE 
AS BEGIN
   UPDATE [Card]
   SET points = points - i.points
   FROM Inserted i
   WHERE Card.id = i.id AND i.UserId = 0

   UPDATE [Card]
   SET points = points - @points
   FROM Inserted i
   WHERE i.UserId <> 0 AND (Card.id = i.id OR Card.userId = i.userId)
END

您需要考虑数据集- 不要假设触发器伪表中有单行,也不要在触发器中进行 RBAR(逐行处理)处理。

于 2012-09-28T15:11:59.010 回答
1

deleted表包含作为给定DELETE语句的一部分被删除的记录,如果DELETE条件匹配多条记录,则可以包含多行。

这就是您的情况发生的情况,当您尝试cardIddeleted包含多条记录的表中进行选择时,select 语句将返回多个值,因此触发器会引发该异常。

于 2012-09-28T14:52:47.390 回答