SCOPE_INDENTITY()不工作是否返回null?
在阅读本网站时,我想以下代码会返回添加到我的数据库的项目的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拥有最新的条目的 ID。
这表明您当前使用的数据库代码运行良好。调试时
诠释ID不当地人出现了,如果我看着它我 得到...
这是你的问题的根源。问题在于您已将范围ID设置为
if (type == typeof(Weights))
块。在该块之外,标识符ID
没有意义。
声明ID
在此过程的范围的顶部,您应该能够在本地中看到它或添加监视。
这就是它虽然所有其他答案都非常有帮助 - 移动声明并没有在当地人看到或观看,但完成我的代码并用它来更新另一个表中的列。谢谢,并表示歉意,有点毫无意义的问题! – Luthervd
我假设表有一个标识列。
试着这样做:
string InsertWeight = ("INSERT INTO WeightExercise
(ExcerciseName, Duration, Sets, DiaryId) VALUES (@name, @time, @sets, @DiaryId); SELECT SCOPE_IDENTITY()");
然后,而不是com.ExecuteNonQuery()
使用int ID = (int) com.ExecuteScalar()
;
对于您的实际问题,请尝试在插入语句之后和SET之前放入分号。原因是因为你在同一个陈述中。当SCOPE_IDENTITY()被调用时,还没有插入。您需要终止声明(;
),然后调用SCOPE_IDENTITY();
SCOPE_IDENTITY
返回插入到同一范围内的标识列的最后一个标识值。您需要使用ExecuteScalar
而不是ExecuteNonQuery
找回它:
因此改变你的SQL先:
“INSERT INTO WeightExercise(ExcerciseName,持续时间,集合,DiaryId) VALUES(@name,@time ,@sets,@DiaryId); SELECT SCOPE_IDENTITY();“
,那么你可以通过这种方式获取ID:
ID = (int)com.ExecuteScalar();
OP正在更新一个指定为输出的参数 - 它应该与原来一样好,与执行查询 –
这是一个范围界定问题吗? ID只存在于if(type == typeof(Weights))块 – akatakritos
我已经用select scope_identity()做了这个,但是我看不出你的代码有什么问题。 – Paparazzi
这里有一个'IDENTITY'专栏吗? –