每当更改SaleOrderDetail中的订单项时,触发将更改日期和时间放入Order表的LastModified列中

时间:2018-07-14 19:49:32

标签: sql-server adventureworks

我创建了如下表:

CREATE TABLE Customer
(
    CustomerID INT PRIMARY KEY,
    CustomerLName VARCHAR(30),
    CustomerFName VARCHAR(30)
);

CREATE TABLE SaleOrder
(
    OrderID INT IDENTITY PRIMARY KEY,
    CustomerID INT REFERENCES Customer(CustomerID),
    OrderDate DATE,
    LastModified datetime
);

CREATE TABLE SaleOrderDetail
( 
    OrderID INT REFERENCES SaleOrder(OrderID),
    ProductID INT,
    Quantity INT,
    UnitPrice INT,
    PRIMARY KEY (OrderID, ProductID)
);

我需要验证此查询是否正确或需要进行哪些更改。

CREATE TRIGGER [dbo].[tr_Modify]
ON dbo.SaleOrder
AFTER Update
AS
BEGIN
    SET NOCOUNT on;

    IF UPDATE (OrderID)
    BEGIN
        UPDATE SaleOrder
        SET LastModified = GETDATE()
        FROM SaleOrder o
        INNER JOIN SaleOrderDetail od ON o.OrderID = od.OrderID
        WHERE o.OrderID <> od.OrderID
    END
END

1 个答案:

答案 0 :(得分:1)

我认为语法是正确的,但是由于OrderID是一个身份PK,因此无法更新,因此触发器将永远不会触发。

如果您尝试从salesOrderDetail的更新中更新salesOrder中的最后修改,则应执行以下操作:

CREATE TRIGGER [dbo].[tr_Modify2]
ON dbo.SaleOrderDetail
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT on;

    BEGIN
        UPDATE SaleOrder
        SET LastModified = GETDATE()
        FROM
            SaleOrder o
            INNER JOIN INSERTED INS ON INS.orderid = o.orderid

    END
END