如何获得最后插入的ID?

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

我有这样的code:

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(); }

当我插入这个表,我有一个auto_increment int主键名为 GamesProfileId 专栏中,我怎么能得到最后插入一个接着这个,所以我可以使用该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 +,如果没有插入触发器,然后更改插入语句(全部一行拆分为清楚起见,在这里)这个

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:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   ID

发布评论

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

>www.elefans.com

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