你會設置一個Output
參數。代碼可能是這樣的:
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;
}
亞倫認爲,這是鎖定一個很好的候選人,交易程序始終是這裏的最佳實踐,以及。因此,修改後的代碼可能是這樣的:
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;
}
}
其中_lockObj
被定義爲private object _lockObj = new Object();
作爲一個字段。
注:你不需要在這裏擔心Rollback
,因爲如果將引發異常的Rollback
將SqlTransaction
對象的Dispose
期間印發。
您需要解決此交易,以防止競爭條件... –