Sql server:在插入时更新新记录

时间:2009-09-04 12:06:12

标签: sql sql-server database triggers

使用“Northwind”示例:

我想在OrderDetails表上创建一个insert触发器,这样每次插入OrderDetail时,它都会获得Products表中定义的UnitCost的当前值。

它应该是这样的,但我很难把它弄好。你能帮忙吗?

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 )

我正在使用SQL Server 2008。 谢谢!

1 个答案:

答案 0 :(得分:4)

您必须将inserted表加入orderdetails表,以找出插入的内容。像这样:

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