question

Matt Whitfield avatar image
Matt Whitfield asked

@@IDENTITY and Triggers

Site Seeder Question: If I use @@IDENTITY to return the last inserted IDENTITY value, then this works up to the point that I create a trigger on the table that is being affected that also inserts a row into a table with an IDENTITY column.

How can I get around this?

t-sqltriggeridentity
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Capetonian avatar image
Capetonian answered

You can use scope_identity() I believe. In my experience its much better better to use scope_identity

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Jack Corbett avatar image
Jack Corbett answered

If you are on 2005 or 2008 I recommend using the OUTPUT clause. There are a couple of known issues with SCOPE_IDENTITY() as well. See Connect Items #328811 and #476577

1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

I agree with Jack, if you are on a newer version, kick this back with the OUTPUT clause.
1 Like 1 ·
J Kidd avatar image
J Kidd answered

If you are wanting to return the created identity of a specific table you can use IDENT_CURRENT( 'table_name' )

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

rjv_rnjn avatar image
rjv_rnjn answered

IDENT_CURRENT() has its own sets of issues (specifically related to transactions) and I haven't come across any situation where I would need it.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

David 1 avatar image
David 1 answered

@@IDENTITY returns the last identity value in the current connection. IDENT_CURRENT returns the last in the table. It's not the same thing as @@IDENTITY at all.

Use SCOPE_IDENTITY() instead of @@IDENTITY if you want to ignore values generated by triggers.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.