HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Return the uniqueidentifier generated by a default on insert

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
uniqueidentifiergeneratedtheinsertreturndefault

Problem

Goal

Retrieve the latest guid value in real time after you have inserted the value in the table
Problem

Don't know how to do it
Info

  • The code should only specify new values for address and zipcode



  • There can be lots of data in the table



Table

CREATE TABLE [AddressBook]
(
    [testID] [uniqueidentifier] NOT NULL default newid(),
    [address] [nvarchar](50) NULL,
    [zipcode] [nvarchar](50) NULL
)

Solution

I think you are looking for output

DECLARE @MyTableVar table([testID] [uniqueidentifier]);
 INSERT [AddressBook] ([address], [zipcode])
        OUTPUT INSERTED.[testID] INTO @MyTableVar
 VALUES (N'address', N'zipcode');

--Display the result set of the table variable.
 SELECT [testID] FROM @MyTableVar;

GO


uniqueidentifier may not be the most efficient id here but this is an answer to the stated question

Code Snippets

DECLARE @MyTableVar table([testID] [uniqueidentifier]);
 INSERT [AddressBook] ([address], [zipcode])
        OUTPUT INSERTED.[testID] INTO @MyTableVar
 VALUES (N'address', N'zipcode');

--Display the result set of the table variable.
 SELECT [testID] FROM @MyTableVar;

GO

Context

StackExchange Database Administrators Q#125516, answer score: 16

Revisions (0)

No revisions yet.