Either just grab the latest ID when the insert happens (using SCOPE_IDENTITY()
), or if you need to check the current value of an IDENTITY
column later on, use SELECT IDENT_CURRENT('table_name')
to get that value.
So the easiest way is to just get the ID as you insert your values - something like this:
string sql = "INSERT INTO dbo.YourTable(Col1, ..., ColN) VALUES(@Val1, ..., @ValN); SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
Or if you cannot grab the ID as it's being inserted, you can always check later on what the current last used value of the IDENTITY
column on a given table was, using something like this:
string sql = string.Format("SELECT IDENT_CURRENT('{0}');", yourTableName);
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}