Scope_identity () in sqlclient batch commands

I usually use a stored procedure when inserting records to make sure that I get the correct scope_identity () value. I have a requirement to get the id field of an inserted record when using SqlClient.

My understanding is that if I execute the scope_identity () command with insert, will it still be in the same scope as the insert command? Something like below. It's hard to check though ... Will I 100% get the correct id value with this ..?

(id field is an automatic increment of bigint - Sql Server)

long newid = 0; using (SqlConnection conn = new SqlConnection(....)) { conn.Open(); using (SqlCommand comm = new SqlCommand ("insert into .... ; select SCOPE_IDENTITY();", conn)) { SqlDataReader reader = comm.ExecuteReader(); if (reader.HasRows) { reader.Read(); newid = Convert.ToInt64(reader[0]); } } } 
+1
source share
1 answer

From the documentation for SCOPE_IDENTITY (emphasis mine):

Returns the last identity value inserted into the identifier column to the same extent. Volume is a module: stored procedure, trigger, function, or package . Therefore, two statements are in the same if they are in the same stored procedure, function, or batch .

In this case, your command:

 "insert into .... ; select SCOPE_IDENTITY();" 

It is a package, and therefore, you will get the last inserted identifier value in this batch, which in this case is the identifier value in the insert, since this is the only other statement in the package.

+3
source

All Articles