Home >Database >Mysql Tutorial >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>
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!