Tuesday, February 21, 2012

MSSQL Triggers and @@IDENTITY and SCOPE_IDENTITY()

I took the SQL here and added this to it:

CREATE TRIGGER dbo.AddressTrigger

   ON dbo.Address

AFTER INSERT

AS

INSERT INTO Person (PersonId, Name, AddressId)

VALUES (NEWID(),'I need a name','1ba51989-84fb-4a61-8c35-9e6a007bc0fb')

 
 

In doing so I created a trigger that will fire whenever a row is inserted into the Address table. The trigger will make a new row in the Person table. I wanted the process to assign the Person the Address of the Address just created, but I find in hard to know what the uniqueidentifier most recently used is. :(

I found this stuff in Googling to figure out the above:

  1. http://www.youtube.com/watch?v=5zyQIt-8NRQ
  2. http://www.kodyaz.com/articles/sql-trigger-example-in-sql-server-2008.aspx
  3. http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row
  4. http://www.kodyaz.com/articles/sql-trigger-example-in-sql-server-2008.aspx
  5. http://vyaskn.tripod.com/retrieve_guid_value_like_identity.htm

Some of the above touches on @@IDENTITY and SCOPE_IDENTITY() would have been handy for solving the problem above if I were using ints for ids instead of guids.

No comments:

Post a Comment