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

How to Retrieve the Last Inserted Row ID in SQL Server?

Patricia Arquette
Release: 2025-01-13 13:17:43
Original
621 people have browsed it

How to Retrieve the Last Inserted Row ID in SQL Server?

Getting the ID of the Last Inserted Row in SQL Server

The Challenge:

After adding a new row to a SQL Server table, you need to get the ID of that new row efficiently, without using extra temporary tables. The goal is to get this ID immediately after a single INSERT statement.

The Solution:

If your table has an INT IDENTITY or BIGINT IDENTITY column (auto-incrementing), use this SQL statement:

<code class="language-sql">INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()</code>
Copy after login

SCOPE_IDENTITY() returns the last IDENTITY value generated within the current session.

Other options include @@IDENTITY and IDENT_CURRENT(). For a detailed comparison of these functions and their uses, see this helpful guide: //m.sbmmt.com/link/1e5e1435c95e420a1cd34d3202769c18.

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

source:php.cn
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