在閱讀本網站時,我想以下代碼會返回添加到我的數據庫的項目的ID,但是我想填充的int值並未顯示在範圍內。下面是我的插入語句的代碼:SCOPE_INDENTITY()不工作是否返回null?
foreach (ExOb exc in exobject)
{
Type type = exc.GetType();
//Add a weight exercise
if (type == typeof(Weights))
{
Weights thisweight = (Weights)exc;
string InsertWeight = ("INSERT INTO WeightExercise (ExcerciseName, Duration, Sets, DiaryId) VALUES (@name, @time, @sets, @DiaryId) SET @ID = SCOPE_IDENTITY();");
com = new SqlCommand(InsertWeight, con);
com.Parameters.AddWithValue("@name", thisweight.ExcerciseName);
com.Parameters.AddWithValue("@time", thisweight.WeightDuration);
com.Parameters.AddWithValue("@sets", thisweight.TotalSets);
com.Parameters.AddWithValue("@DiaryId", results[0]);
com.Parameters.Add("@ID", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
con.Open();
com.ExecuteNonQuery();
int ID = (int)com.Parameters["@ID"].Value;
con.Close();
}
else if (type == typeof(Cardio))
{
Cardio thiscardio = (Cardio)exc;
}
}
}
數據庫用Weight Weight詳細信息更新。我在調試時檢查過,命令參數@ID保存最新條目的ID。 Int ID在調試時不會顯示在當地人身上,如果我觀看它,我會得到:
ID The name 'ID' does not exist in the current context
我在做什麼錯在這裏?
這是一個範圍界定問題嗎? ID只存在於if(type == typeof(Weights))塊 – akatakritos
我已經用select scope_identity()做了這個,但是我看不出你的代碼有什麼問題。 – Paparazzi
這裏有一個'IDENTITY'專欄嗎? –