views:

209

answers:

1

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 !

+4  A: 

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
Eric
Thanks Eric for that nice and quick answer
iDevlop
Hey, I'm here for you :)
Eric
Just a note for others: Sql Server does not seem to like "FOR AFTER INSERT". But "FOR INSERT" does the job.
iDevlop
@iDevlop: Good call. I've been answering too many MySQL trigger questions :)
Eric
And if I want to add a condition to only do the update when the inserted record has NULL in unitcost, where do I put that condition ? I tried several things, including a WHERE i.productId IS NULL before the last END, but that does not seem to work.
iDevlop