You would setup an Output parameter. The code might look like this:
using (SqlConnection c = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand("SP_RegisterComp", c))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CompName", compName);
cmd.Parameters.AddWithValue("@Check_In", checkIn);
var outParm = new SqlParameter("@ID", SqlDbType.Int);
outParm.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
var val = outParm.Value;
}
As Aaron suggested, this is a very good candidate for locking, and transactional programming is always a best practice here as well. So, the modified code might look like this:
lock (_lockObj)
{
using (SqlConnection c = new SqlConnection(cString))
using (SqlTransaction tran = c.BeginTransaction())
using (SqlCommand cmd = new SqlCommand("SP_RegisterComp", c, tran))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CompName", compName);
cmd.Parameters.AddWithValue("@Check_In", checkIn);
var outParm = new SqlParameter("@ID", SqlDbType.Int);
outParm.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
// commit the transaction
tran.Commit();
var val = outParm.Value;
}
}
where _lockObj is defined as private object _lockObj = new Object(); as a field.
NOTE: you don't need to worry about the Rollback here because if an exception is raised the Rollback will be issued during the Dispose of the SqlTransaction object.