Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity of inserted/updated row in trigger

I have the following trigger but need ti find the identity of the row so I don't update all records in the table. How can I get the identity of the affected row?

BEGIN
  UPDATE tb_Division SET  LastModified = GetDate() WHERE "id of inserted/updated row"
END
like image 884
Chin Avatar asked Jul 06 '10 05:07

Chin


2 Answers

Since a trigger in MS SQL Server does not distinguish between single-record and multi-record operations, you should JOIN the table with the INSERTED pseudo table or use a subselect:

UPDATE tb_Division
SET LastModified = GETDATE()
WHERE id IN (SELECT id FROM INSERTED)

id being the primary key column of your table.

like image 198
devio Avatar answered Oct 31 '22 04:10

devio


Have you looked at the id of the inserted logical table? You have to be careful when using triggers, as a trigger may be operating on more than one row:

UPDATE tb_Division AS td
   SET LastModified = GetDate() 
FROM INSERTED AS i
WHERE td.id = = i.id

See here for more details, and from MSDN:

DML triggers use the deleted and inserted logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is tried. The deleted and inserted tables hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use:

like image 44
Oded Avatar answered Oct 31 '22 05:10

Oded