1

All the years I've played with SQL, and I never thought to ask this question.

If I am adding (inserting) a row into a table, and it has an identity column, how might I retrieve the identity for this new row? I am keen on hearing a solution to this, as I fear I may be operating on a database with some very similar or duplicate rows.

user978122
  • 5,531
  • 7
  • 33
  • 41
  • possible duplicate of [Best way to get identity of inserted row?](http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row) and many others. – Martin Smith Nov 18 '12 at 09:12

2 Answers2

1

Use SCOPE_IDENTITY function to obtain the last inserted identity in the current scope.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

There are three main functions/ways how to retrieve the value of IDENTITY column. Please follow the first link to brief explanation. The second (MSDN) provides clear examples and comparison:

Three ways how to get identity: @@IDENTITY, SCOPE_IDENTITY(), IDENT_CURRENT('TableName')

While @@IDENTITY is most likely "the-most-often-used", because of its implementation it does not have to always return expected identity value. read more here

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335