Reputation: 1182
This is the database diagram of my sample database:
I want to UPDATE Ingredient Table when changes are made into OrderDetails table with the help of Table Trigger
But the problem is that the Ingredients table may have one or more entries for an Item. I want to update all entries in Ingredient table which are associated with an Item. For more description, see the algorithm below:
For each Ingredient in Ingredients for the current Item:
Update the Quantity in Ingredient table using the formula:
formula: Ingredient.Quantity = Ingredient.Quantity - (Item.Quantity * Ingredients.Quantity)
(The whole idea is whenever Item(s) for an OrderID is Added/Updated/Deleted, the Ingredient(s) Quantity should be decreased/increased by the Quantity mentioned)
Upvotes: 1
Views: 123
Reputation: 239646
We don't iterate or loop in SQL (unless we can avoid it). We describe what we want to happen, and let SQL work out how.
We also, generally, don't store data that we can compute. We can always compute the amount of each ingredient that has been ordered. (If there's another table tracking deliveries from our suppliers, that could also be computed over). If performance was an issue, we'd then consider creating an indexed view - which does include the calculated values, but SQL Server takes care of maintaining it automatically.
In that way, you avoid any discrepancies from creeping in (e.g. if your trigger is disabled).
All that being said, I think the trigger you want is:
create trigger T_OrderDetails
on OrderDetails
after insert,update,delete
as
begin
update ing
set Quantity = ing.Quantity - ((COALESCE(iod.Quantity,0) - COALESCE(dod.Quantity,0)) * i.Quantity)
from
inserted iod
full outer join
deleted dod
on
iod.ItemID = dod.ItemID
inner join
Ingredients i
on
i.ItemID = iod.ItemID or
i.ItemID = dod.ItemID --Cope with OUTER join above
inner join
Ingredient ing
on
i.IngID = ing.IngID
end
Upvotes: 1