Home > Database > Mysql Tutorial > How to Retrieve the Last Inserted GUID Primary Key in SQL Server?

How to Retrieve the Last Inserted GUID Primary Key in SQL Server?

Barbara Streisand
Release: 2025-01-24 12:16:09
Original
559 people have browsed it

How to Retrieve the Last Inserted GUID Primary Key in SQL Server?

Accessing the Newly Inserted GUID Primary Key in SQL Server

Using GUIDs as primary keys in SQL Server often presents a challenge: how to efficiently retrieve the GUID of the most recently added row, especially when avoiding pre-generation and variable storage. This article demonstrates a solution using the OUTPUT clause.

The OUTPUT clause offers a powerful method to capture the data of inserted rows, even during bulk inserts. This eliminates the need for separate queries to retrieve the newly generated GUID.

Implementation:

<code class="language-sql">CREATE TABLE dbo.GuidPk (
    ColGuid uniqueidentifier NOT NULL DEFAULT NEWSEQUENTIALID(),
    Col2    int              NOT NULL
)
GO

DECLARE @op TABLE (
    ColGuid uniqueidentifier
)

INSERT INTO dbo.GuidPk (Col2)
OUTPUT inserted.ColGuid INTO @op
VALUES (1);

SELECT * FROM @op;

SELECT * FROM dbo.GuidPk;</code>
Copy after login

This approach provides a clean and efficient way to obtain the last inserted GUID primary key within SQL Server, even when multiple rows are inserted concurrently. The OUTPUT clause redirects the inserted ColGuid values into the temporary table @op, making retrieval straightforward.

The above is the detailed content of How to Retrieve the Last Inserted GUID Primary Key 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