Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Trigger: On update of primary key, how to determine which "deleted" record cooresponds to which "inserted" record?

Assume that I know that updating a primary key is bad.

There are other questions which imply that the inserted and updated table records match by position (the first of one matches the first of the other.) Is this a fact or coincidence?

Is there anything that could join the two tables together when the primary key changes on an update?

like image 338
Zachary Scott Avatar asked Jul 08 '11 19:07

Zachary Scott


People also ask

Is it possible to find which column was updated in trigger?

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.

How Triggers use the inserted and deleted tables?

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.

Which of the following is the correct way to delete a trigger?

Expand Triggers, right-click the trigger to delete, and then click Delete. In the Delete Object dialog box, verify the trigger to delete, and then click OK.

How can Triggers be applied to accomplish referential integrity?

Triggers are used to maintain referential integrity, which assures that vital data in your databaseľsuch as the unique identifier for a given piece of dataľremains accurate and can be used as the database changes. Referential integrity is coordinated through the use of primary and foreign keys.


2 Answers

There is no match of inserted+deleted virtual table row positions.

And no, you can't match rows

Some options:

  • there is another unique unchanging (for that update) key to link rows
  • limit to single row actions.
  • use a stored procedure with the OUTPUT clause to capture before and after keys
  • INSTEAD OF trigger with OUTPUT clause (TBH not sure if you can do this)
  • disallow primary key updates (added after comment)
like image 162
gbn Avatar answered Sep 30 '22 14:09

gbn


Each table is allowed to have one identity column. Identity columns are not updateable; they are assigned a value when the records are inserted (or when the column is added), and they can never change. If the primary key is updateable, it must not be an identity column. So, either the table has another column which is an identity column, or you can add one to it. There is no rule that says the identity column has to be the primary key. Then in the trigger, rows in inserted and updated that have the same identity value are the same row, and you can support updating the primary key on multiple rows at a time.

like image 45
Daniel Avatar answered Sep 30 '22 13:09

Daniel