5 cents hint – c# + MSSQL getting last inserted id and what about bigint

By | 4. May 2017

Getting last inserted Id value is quite common needed task. When using SqlCommand it is not part of the class.

Things are getting even trickier if the value must be Int64. But have no fear, it is not tricky. Just define in SqlCommand two sql statements:-

first of  insert and second for selecting back inserted identity

 

using (SqlCommand dbCommand = new SqlCommand("INSERT INTO MainTable ( [Message] ) VALUES ( @message ); SELECT CAST(scope_identity() AS bigint);", connection))
{
    dbCommand.Parameters.Add("message", SqlDbType.VarChar).Value = "My important message";
    Int64 lastId = (Int64)dbCommand.ExecuteScalar();

    object MyComplexTechInfo = null;
    CreateMessageDetails(lastId, MyComplexTechInfo);
}

PS. SCOPE_IDENTITY returns the value only within the current scope;

Leave a Reply