IDENT_CURRENT returns the last identity value but SCOPE_IDENTITY does not

Pascal picture Pascal · Feb 21, 2012 · Viewed 31.9k times · Source

I have a SQL Server as backend for an asp.net application. Multiple people might insert data in the same table 'the same time...'.

When I read the solution/answer from this post: scope_identity vs ident_current

THEN I should not use the Ident_current because I could get the id of the insert of another user.

But using Select Scope_Identity(); returns me NULL while the Select IDENT_CURRENT('tableName') returns me the correct id which I checked with SQL Server Management Studio.

The insert statement I do within a SqlTransaction. The Select IDENT_CURRENT('tableName') is done after the transaction.

What do I wrong?

UPDATE:

My insert statement which is dynamically build together by a base class:

INSERT INTO TEST (NAME) VALUES (@Name)

The command's Parameter collection has the value "xxx" and everything is fine inserted into the table.

I do NOT use stored procedures just pure SqlDataReader with C#.

commandText = "INSERT INTO TEST (NAME) VALUES ('Test1');Select Scopy_Identity();"

How can I get the last auto inc id running the above statement and should I call ExecuteNonQuery or ExecuteReader for the above because it has a INSERT and SELECT that's confusing...

Answer

Fernando Manuel picture Fernando Manuel · Sep 30, 2012

IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.

@@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.

SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.