x

@@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?

more ▼

asked Oct 12 '09 at 07:48 AM in Default

Matt Whitfield gravatar image

Matt Whitfield ♦♦
29.4k 61 65 87

(comments are locked)
10|1200 characters needed characters left

6 answers: sort voted first

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

more ▼

answered Oct 12 '09 at 10:51 AM

Jack Corbett gravatar image

Jack Corbett
1.1k 2 2 3

I agree with Jack, if you are on a newer version, kick this back with the OUTPUT clause.
Oct 12 '09 at 11:10 AM Steve Jones - Editor ♦♦
(comments are locked)
10|1200 characters needed characters left

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

more ▼

answered Oct 12 '09 at 09:23 AM

Capetonian gravatar image

Capetonian
26

(comments are locked)
10|1200 characters needed characters left

@@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.

more ▼

answered Oct 12 '09 at 06:18 PM

David 1 gravatar image

David 1
1.8k 1 3

(comments are locked)
10|1200 characters needed characters left

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

more ▼

answered Oct 12 '09 at 11:50 AM

J Kidd gravatar image

J Kidd
11

(comments are locked)
10|1200 characters needed characters left

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.

more ▼

answered Oct 12 '09 at 02:09 PM

rjv_rnjn gravatar image

rjv_rnjn
21

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x977
x114
x33

asked: Oct 12 '09 at 07:48 AM

Seen: 3393 times

Last Updated: Oct 12 '09 at 08:35 AM