本文介绍了如何获取最后插入的 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?
发布评论