在 SQL Server 中访问新创建的记录的 ID
本指南演示如何获取 SQL Server 中 aspnet_GameProfiles
表中最近插入的记录的 ID。 最佳方法取决于您的 SQL Server 版本:
SQL Server 2005 及更高版本(没有 INSERT 触发器):
对于较新的 SQL Server 版本,最有效的方法是直接在 OUTPUT
语句中利用 INSERT
子句:
<code class="language-sql">INSERT INTO aspnet_GameProfiles (UserId, GameId) OUTPUT INSERTED.ID VALUES (@UserId, @GameId);</code>
随后,使用 ExecuteScalar()
:
<code class="language-csharp">Int32 newId = (Int32)myCommand.ExecuteScalar();</code>
此方法避免了额外的查询,提高了性能。
SQL Server 2000 或使用 INSERT 触发器时:
对于较旧的 SQL Server 版本或涉及 INSERT
触发器的场景,请使用 SCOPE_IDENTITY()
函数:
<code class="language-sql">INSERT INTO aspnet_GameProfiles (UserId, GameId) VALUES (@UserId, @GameId); SELECT SCOPE_IDENTITY();</code>
然后可以使用 ExecuteScalar()
访问检索到的 ID:
<code class="language-csharp">Int32 newId = (Int32)myCommand.ExecuteScalar();</code>
通过使用这两种方法中的任何一种,您都可以从 aspnet_GameProfiles
无缝检索新生成的 ID,从而启用需要此信息的后续操作。
以上是如何在 INSERT 语句后检索 SQL Server 中最后插入的 ID?的详细内容。更多信息请关注PHP中文网其他相关文章!