简体   繁体   中英

SQL Server TRIGGER UPDATE on change

I'm trying to do a TRIGGER UPDATE for a web store and I want the total amount ( col2 ) to update every time something is added into the order, all orders are done in one table ( table1 ) and then all the orders are stored in another table ( table2 ). I keep getting errors with table1.col1 = table2.col1 where col1 is an ID.

CREATE TRIGGER table2.col2
ON table1
FOR UPDATE
BEGIN
    UPDATE table2
    SET newTable =
        (SELECT table2.col2 AS p
        FROM table2
        JOIN inserted AS i
        ON p.orderId = i.orderId)
    WHERE table2.orderId = table1.orderId
END

You can probably re-write it without a sub-query but the quick fix is to add inserted into your where clause as follows:

CREATE TRIGGER table2.col2
ON table1
FOR UPDATE
BEGIN
    UPDATE table2 SET
        newTable = (
            SELECT table2.col2 AS p
            FROM table2
            JOIN inserted AS i
            ON p.orderId = i.orderId
        )
    WHERE table2.orderId in (select orderId from Inserted)
END

Inserted is a pseudo table which contains a row with the new data (aside from large columns) for each row being updated.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM