Using the "Northwind" sample:
I would like to create an insert trigger on the OrderDetails table so that every time an OrderDetail is inserted, it gets the current value of the UnitCost as defined in the Products table.
It should be something like this, but I have trouble to get it right. Can you help ?
CREATE TRIGGER Trigger1 ON OrderDetails as od FOR INSERT AS -- save unit cost od.unitCost = (select UnitCost from Products as p WHERE p.ProductId = i.ProductId )
I am using SQL Server 2008. Thanks !
You'd have to join the inserted
table to the orderdetails
table to find out what's been inserted. Like so:
CREATE TRIGGER Trigger1
ON OrderDetails as od
FOR INSERT
AS
BEGIN
update od
set unitcost = p.unitcost
from
orderdetails od
inner join inserted i on
od.orderlineid = i.orderlineid
inner join produts p on
p.productid = od.productid
END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.