Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted ID in SQL Server?

How to Retrieve the Last Inserted ID in SQL Server?

Barbara Streisand
Release: 2025-01-21 22:57:10
Original
583 people have browsed it

How to Retrieve the Last Inserted ID in SQL Server?

Obtaining the ID of the Last Inserted Row

When working with SQL Server databases and auto-incrementing primary keys, accessing the ID of the most recently added record is a common requirement. This guide outlines several methods to achieve this, considering different SQL Server versions and the potential presence of insert triggers.

SQL Server 2005 and Later (Without Insert Triggers)

For versions 2005 and beyond, a streamlined approach involves incorporating the OUTPUT INSERTED.ID clause directly into your INSERT statement. This clause efficiently returns the ID of the newly inserted row. Here's an example:

INSERT INTO aspnet_GameProfiles (UserId, GameId)
OUTPUT INSERTED.ID
VALUES (@UserId, @GameId);
Copy after login

The newly generated ID is then readily accessible via the ExecuteScalar() method of your SqlCommand object:

Int32 newId = (Int32)myCommand.ExecuteScalar();
Copy after login
Copy after login

SQL Server 2000 or When Insert Triggers Exist

In SQL Server 2000 or scenarios involving insert triggers, a slightly different strategy is necessary:

  1. Execute the standard INSERT statement.
  2. Employ the SCOPE_IDENTITY() function to retrieve the last inserted identity value.
INSERT INTO aspnet_GameProfiles (UserId, GameId)
VALUES (@UserId, @GameId);
SELECT SCOPE_IDENTITY();
Copy after login

Similar to the previous method, ExecuteScalar() can be used to obtain the resulting ID:

Int32 newId = (Int32)myCommand.ExecuteScalar();
Copy after login
Copy after login

These methods provide efficient and reliable ways to retrieve the ID of the last inserted row, enabling seamless integration with subsequent database operations.

The above is the detailed content of How to Retrieve the Last Inserted ID in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template