如何获取最后插入的 id?

编程入门 行业动态 更新时间:2024-10-26 20:25:13
本文介绍了如何获取最后插入的 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个代码:

string insertSql = "INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)"; using (SqlConnection myConnection = new SqlConnection(myConnectionString)) { myConnection.Open(); SqlCommand myCommand = new SqlCommand(insertSql, myConnection); myCommand.Parameters.AddWithValue("@UserId", newUserId); myCommand.Parameters.AddWithValue("@GameId", newGameId); myCommand.ExecuteNonQuery(); myConnection.Close(); }

当我插入此表时,我有一个名为 GamesProfileId 的 auto_increment int 主键列,我怎样才能获得最后插入的一个,以便我可以使用该 id 插入另一个表?

When I insert into this table, I have an auto_increment int primary key column called GamesProfileId, how can i get the last inserted one after this so I can use that id to insert into another table?

推荐答案

对于SQL Server 2005+,如果没有insert trigger,则将insert语句(全是一行,这里为了清晰起见)改成这个

For SQL Server 2005+, if there is no insert trigger, then change the insert statement (all one line, split for clarity here) to this

INSERT INTO aspnet_GameProfiles(UserId,GameId) OUTPUT INSERTED.ID VALUES(@UserId, @GameId)

对于 SQL Server 2000,或者如果有插入触发器:

For SQL Server 2000, or if there is an insert trigger:

INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId); SELECT SCOPE_IDENTITY()

然后

Int32 newId = (Int32) myCommand.ExecuteScalar();

更多推荐

如何获取最后插入的 id?

本文发布于:2023-10-13 20:44:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489027.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:id

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!