Trigger to insert data row into new table when old table is updated [closed]

Posted on

Question :

I am trying to set up a trigger in SQL server that when the price of an existing item on table item is changed, it inserts that entire item (row) into table item_price_history, putting the old price as old_price and the updated price as new_price. I’m pretty stumped as to how to get this to work. I keep getting errors that item_id cannot be bound, or is an invalid column, but it is a column in both tables. Here is what I have so far:

CREATE TRIGGER update_price_trg
ON item
AFTER UPDATE,INSERT
AS 
BEGIN
  DECLARE @DATE_OF_CHANGE datetime;
  SET @DATE_OF_CHANGE = GETDATE();
  INSERT INTO item_price_history,item_id,old_price,new_price,date_of_change)
  VALUES (item_id,old.price,new.price,@DATE_OF_CHANGE)
END;

Answer :

You need to use the correct table names in the trigger — inserted and deleted are the internal table names used for the new and old data. Also, you need to associate the two tables correctly, and handle multiple rows simultaneously. Your code will need a rewrite to do all this:

CREATE TRIGGER update_price_trg
ON item
AFTER UPDATE,INSERT
AS 
BEGIN
    INSERT INTO item_price_history(
        item_id,
        old_price,
        new_price,
        date_of_change
        )
    SELECT 
        i.item_id,
        d.price,
        i.price,
        GETDATE()
    FROM inserted i
    LEFT JOIN deleted d
        ON i.item_id = d.item_id
    WHERE i.price != ISNULL(d.price, -1)
END;

Leave a Reply

Your email address will not be published. Required fields are marked *