创建一个触发器,从另一个表中的行项目总数更新表格中的字段

时间:2016-08-20 01:16:52

标签: sql-server tsql triggers

我有两个表Order和Order_Details。我想创建一个触发器,通过添加属于该特定订单的Order_Details.Price字段来更新Order.Order_Total。这是我到目前为止,但它给了我以下错误 子查询返回的值超过1。当子查询跟随

时,不允许这样做
Update Order
Set Order_Total = 
    (Select SUM(Price)
    From Order_Details
    Group By Order_Id)
From Order_Details

2 个答案:

答案 0 :(得分:0)

试试这个..问题出在您的子查询中,它与订单表没有任何约束。

UPDATE o
  SET o.Order_Total = t.tprice
FROM Order o
            LEFT JOIN ( SELECT Order_Id, SUM(isnull(price,0)) tprice 
                               FROM OrderDetails
                               GROUP BY Order_Id) t
                         ON o.Order_Id=t.Order_Id

答案 1 :(得分:0)

好的,这就是我最后做的事情,以防有人有同样的问题。我创建了一个CTE来添加Order_Details价格,并更新了该CTE的Order.Total。这是我使用的完整代码。

IF EXISTS ( SELECT 1 FROM sys.triggers WHERE object_id = object_id('dbo.trOrder_Details_AIU') ) 
  DROP TRIGGER dbo.trOrder_Details_AIU
GO

CREATE TRIGGER dbo.trOrder_Details_AIU
   ON  dbo.Order_Details
   AFTER INSERT,UPDATE, Delete
AS 
BEGIN
    set nocount on;
    begin 
    ; with Total_CTE(Order_Id, Total)
    as 
    ( 
        Select Order_Id, SUM(Price)
        From Order_Details 
            Group By Order_Id
    )

Update Order
Set Order_Total = Total_CTE.Amount
From Total_CTE
Where Total_CTE.Order_Id = Total.Order_Id
    end
END