使用 @@IDENTITY /scope_identity() 时插入 2 行而不是 1 行
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
没有
SELECT CAST(scope_identity() AS int)
插入一行。但由于我需要使用scope_identity创建的行中的ID。但是,当我使用它时,会创建 2 行而不是 1 行。
我错过了什么吗?
谢谢
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
Without the
SELECT CAST(scope_identity() AS int)
One row is inserted. But since I need the ID from the created row im using scope_identity. However, when I use this, 2 rows are created instead of one.
Did I miss something?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您发布的代码中的问题是您运行了两次相同的查询...一次使用 ExecuteNonQuery(); ,最后一次使用 (int)command.ExecuteScalar();
如果您尝试仅使用executeScalar,我认为您已经得到了您想要的结果...
尝试并希望这会有所帮助...
如果您愿意,您可以使用参数来检索身份,就像他们在<中所做的那样a href="http://www.davidhayden.com/blog/dave/archive/2006/02/16/2803.aspx" rel="nofollow">文章
The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();
If you try to use only the executeScalar i think you have the result's you want....
Try and hope this helps...
If you want you can use Parameter to retrieve the Identity, like they do in this Article
如果您使用 gbn 或 我的回答你的第一个问题,问题不应该发生。
If you would use gbn or my answer from your first question, the problem shouldn't occur.
尝试做
Try doing