我已简化Entity Model以显示与我的问题相关的表格
我需要AFTER INSERT
上的Packings
触发器。
我希望它为dRoastedStocks
INSERTED
行Packings
行中所选混合中包含的每种咖啡种类更新"NewOne" = "OldOne" - "Capacity of selected package" * "Ratio of CoffeeSort in selected Mix" * "Number of packages"
表的相应行中的数量。
数量应按以下方式计算:
NewPacking
在这里,我已经使用Entity Framework在C#中实现了它,并且它运行得很好,如果有人可以将它变成SQL Server触发器,我会非常感激
(//For each CoffeeSort included into selected Mix
foreach (var mixDetail in NewPacking.Mix.Mix_Details)
{
// Find row in dRoastedStocks which refers to CoffeeSort
var roastedStock = _context.dRoastedStocks.First(x => x.CoffeeSort.Id == mixDetail.CoffeeSort.Id);
// Update it's quantity with new value by substracting packed quantity
// Packed quantity is calculated as "Capacity of selected package" * "Ratio of CoffeeSort in selected Mix" * "Number of packages"
roastedStock.Quantity -= NewPacking.PackQuantity * mixDetail.Ratio/100 * NewPacking.Package.Capacity;
}
指的是添加的行)
CREATE TRIGGER RoastedStocks_Insert_Packing
ON Packings
AFTER INSERT
AS
UPDATE dRoastedStocks
SET dbo.dRoastedStocks.Quantity =
dbo.dRoastedStocks.Quantity -
(SELECT Ratio
FROM Mix_Details
WHERE Mix_Id = (SELECT INSERTED.Mix_Id FROM INSERTED)
AND Mix_Details.CoffeeSort_Id = dRoastedStocks.CoffeeSort_Id) / 100
* (SELECT INSERTED.PackQuantity FROM INSERTED)
* (SELECT Capacity FROM Packages WHERE Id = (SELECT INSERTED.Package_Id FROM INSERTED))
解释起来非常复杂,所以我希望方案有所帮助
编辑:这是我尝试用SQL编写的内容,它与我之前编写的C#几乎相同{{1}}
答案 0 :(得分:1)
由于许多已发布的触发器在此处也未发现一次插入多行的情况。所有这些子查询都会以"标量失败...但很多行返回"错误。
看看这种方法:
UPDATE rs SET
Quantity -= md.Ratio / 100 * i.PackQuantity * pk.Capacity
FROM INSERTED i
INNER JOIN dbo.Mix_Details md
ON md.Mix_Id = i.Mix_Id
INNER JOIN dbo.Packages pk
ON pk.Id = i.Package_Id
INNER JOIN dbo.dRoastedStocks rs
ON rs.CoffeeSort_Id = md.CoffeeSort_Id