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

时间:2022-02-12 14:17:25

Using the "Northwind" sample:

使用“Northwind”示例:

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.

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

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 !

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

1 个解决方案

#1


4  

You'd have to join the inserted table to the orderdetails table to find out what's been inserted. Like so:

您必须将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

#1


4  

You'd have to join the inserted table to the orderdetails table to find out what's been inserted. Like so:

您必须将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