Store the previous record in its history table before updating it in the SQL table using a trigger.
Store the previous record in its history table before updating it in the SQL table using a trigger.
343
22-Mar-2023
Updated on 14-Apr-2023
Krishnapriya Rajeev
14-Apr-2023To store the previous record in its history table before updating it in an SQL table using a trigger, you can create a trigger that executes before the update statement. The trigger will need to insert a copy of the current record into the history table before the update is executed.
Here is an example of how you can create a trigger in SQL to achieve this:
In this example, my_table is the name of the table you want to track changes for, and my_table_history is the name of the table you want to store previous versions of the record in. The OLD keyword refers to the current version of the record being updated and allows you to reference the values of its columns.
With this trigger in place, whenever an update is executed on my_table, the trigger will automatically insert a copy of the current record into the my_table_history table before the update is executed. This allows you to maintain a history of changes to the table over time.