I think there is a logical error in the else part. The else part applies only to the statement in red below; so the insertion will happen regardless.ELSE IF @@ROWCOUNT = 0 (SELECT Date,ItemID,[Item Name],Category,Units,Quantity FROM Inserted) BEGININSERT INTO dbo.Inventory(Date,ItemID,[Item Name],Category,Units,Quantity)VALUES (@Date,@ItemID,@ItemName,@Category,@Units, @Quantity)ENDEND
The insert trigger is called only once even if the insert statement results in multiple rows being inserted. So the way you have written it - using variables to store the intermediate quantities would not work correctly if more than one row is inserted in a single insert statement. So I would recommend changing the whole code to something like this.-- update any rows that need to be updated;WITH cte AS( SELECT a.ItemId, SUM(a.Quantity) AS NewQuantity FROM INSERTED a GROUP BY a.ItemId)UPDATE b SET Quantity = b.Quantity + a.NewQuantityFROM cte a INNER JOIN dbo.Inventory b ON a.ItemId = b.ItemId;-- insert any new itemidsINSERT INTO dbo.Inventory([Date],ItemID,[Item Name],Category,Units,Quantity)SELECT MAX([Date]),ItemId,MAX([Item NAME]),MAX(Category),MAX(Units),SUM(Quantity)FROM INSERTEDWHERE ItemId NOT IN (SELECT ItemId FROM dbo.Inventory)GROUP BY ItemId