如何获得最后插入的ID? [英] How to get last inserted id?
本文介绍了如何获得最后插入的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文