在INSERT触发器SQL中使用WHERE子句

时间:2016-06-06 17:47:36

标签: sql-server triggers insert sum where-clause

我试图从另一张表中插入一笔价格。

INSERT INTO Invoice_Of_Supplier (OrderSupplierID, PaymentStatus, Cost)
VALUES (
( SELECT OrderSupplierID FROM inserted),
0,
(SELECT SUM([Price(RUB)]) FROM Car
  JOIN OrderOfSupplier_Car AS osc ON osc.CarID=Car.CarID 
where osc.OrderSupplierID = (select OrderSupplierID from inserted)))

我有Car表格,其中包含字段priceCarID等;

带有字段Order_Of_SupplierOrderSupplierID

SupplierID表格;

Order_Of_Supplier_Car表,其中每个订单都有多个汽车(字段为CarIDOrderSupplierID

我需要在表'InvoiceOfSupplier'中插入一行,其中包含'OrderSupplierID',PaymentStatusCost字段。

OrderSupplierIDPaymentStatus没问题,但CostNULL,我无法理解原因。 当我更改osc.OrderSupplierID = 2(直接获得OrderSupplierID)时,它不起作用。 它只有在我删除所有条件(如'WHERE')时才有效,但在这种情况下,它会获得所有订单的“价格(RUB)”,而不是我需要的那个。

编辑: 问题是,在Order_Of_Supplier中插入数据时,Order_Of_Supplier_Car中没有数据。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

INSERT INTO Invoice_Of_Supplier (OrderSupplierID, PaymentStatus, Cost)
VALUES (
( SELECT OrderSupplierID FROM inserted),
0,
(SELECT SUM(column_name) FROM Car
where Car.CarID = OrderOfSupplier_Car.CarID
and OrderOfSupplier_Car.OrderSupplierID in (select OrderSupplierID from inserted))

答案 1 :(得分:0)

为什么不从插入中选择?

INSERT INTO dbo.Invoice_Of_Supplier (OrderSupplierID, PaymentStatus, Cost)
SELECT
  i.OrderSupplierID,
  0,
  SUM(osc.[Price(RUB)])
FROM inserted i
inner join dbo.OrderOfSupplier_Car osc 
on osc.OrderSupplierID = i.OrderSupplierID
inner join dbo.Car c
ON c.CarID = osc.CarID 
group by i.OrderSupplierID

我认为你根本不需要加入Car

有些问题:这是after还是instead of触发?它在哪张桌子上?