I usually use a stored procedure when inserting records to make sure I get the correct scope_identity() value. I have a requirement to get the id field of an inserted record when using SqlClient now.
My understanding is that if I batch the scope_identity() command with the insert then it will still be in the same scope as the insert command? Something like below. Hard to verify though... Will I 100% get the correct id value with this..?
(id field is an auto-incrementing 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]);
}
}
}
From the documentation for
SCOPE_IDENTITY
(emphasis mine):In this case, your command:
Is a batch, and therefore, you will get the last inserted identity value in that batch, which in this case is the identity value in the insert, since it's the only other statement in the batch.