i need example of SQL Server Update Trigger, Get fields before and after updated to execute sql statments in another table
Using a SQL Server trigger to check if a column is updated, there are two ways this can be done; one is to use the function update(<col name>) and the other is to use columns_updated().
SQL Server COLUMNS_UPDATED() Function for Triggers. This function is used to know the inserted or updated columns of a table or view. It returns a VARBINARY stream that by using a bitmask allows you to test for multiple columns.
The IF UPDATE(column) clause functions the same as an IF, IF...ELSE, or WHILE clause and can use the BEGIN... END block. For more information, see Control-of-Flow Language (Transact-SQL). UPDATE(column) can be used anywhere inside the body of a Transact-SQL trigger.
SQL Server triggers have access to 2 "magic" tables that contain a row for each row that was inserted, updated, or deleted in the statement that caused the trigger to execute.
To find all of the inserted rows on a INSERT statement:
select * from inserted
For all of the deleted rows on a DELETE statement:
select * from deleted
For UPDATE statements, each row updated will be present in both the inserted and deleted tables. The inserted table will hold the new value of the row after the update statement, and the deleted table will hold the old value of the row just before the update statement. Join between the two tables to get what you need:
select i.*, d.* from inserted i join deleted d on (i.id = d.id)
you'll want the special trigger deleted and inserted tables. From MSDN:
In DML triggers, the inserted and deleted tables are primarily used to perform the following: Extend referential integrity between tables. Insert or update data in base tables underlying a view. Test for errors and take action based on the error. Find the difference between the state of a table before and after a data modification and take actions based on that difference. The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows in common. The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.
check here for more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With