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

How to Retrieve a Recently Inserted GUID Primary Key in SQL Server?

Barbara Streisand
Release: 2025-01-24 12:34:16
Original
946 people have browsed it

How to Retrieve a Recently Inserted GUID Primary Key in SQL Server?

Accessing the Newly Inserted GUID Primary Key in SQL Server

SQL Server's SCOPE_IDENTITY() function retrieves the last inserted identity value, but this is unsuitable for GUID primary keys. The OUTPUT clause provides a robust solution for capturing the newly generated GUID.

Here's how to obtain the recently inserted GUID:

  1. Table Creation (GUID Primary Key):

    CREATE TABLE dbo.GuidPk (
        ColGuid uniqueidentifier NOT NULL DEFAULT NEWSEQUENTIALID(),
        Col2    int              NOT NULL
    )
    Copy after login
  2. Insertion with GUID Capture using OUTPUT:

    DECLARE @op TABLE (
        ColGuid uniqueidentifier
    )
    
    INSERT INTO dbo.GuidPk (Col2)
    OUTPUT inserted.ColGuid INTO @op
    VALUES (1)
    Copy after login

    This inserts a record, letting SQL Server generate the GUID. The OUTPUT clause redirects the generated ColGuid to the @op table variable.

  3. Verification:

    SELECT * FROM @op;  -- Shows the newly inserted GUID
    
    SELECT * FROM dbo.GuidPk; -- Confirms the record in the table
    Copy after login

The OUTPUT clause efficiently retrieves the inserted GUID, even with multiple simultaneous insertions. This method ensures accurate retrieval of the newly generated primary key.

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