How to get last inserted id?(如何获取最后插入的 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取最后插入的 id?


基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01