SQL Server: How do I get the value for the row I inserted?

767 Views Asked by At

My SQL Server table has, between other, these columns.

AutoID which has IdentitySpecification set to True and GuidKey which has the default value of (newid())

AutoID   GuidKey
1        f4rc-erdd
2        gedd-rrds

Is there any way of getting the GuidKey from the row inserted?

I need something like the Scope_Identity(), with the difference that i don't want to get the content of AutoID, but the GuidKey column.

4

There are 4 best solutions below

1
On BEST ANSWER

Sql Server 2005/2008

INSERT INTO myTable (SomeColumn)
    OUTPUT INSERTED.GuidKEY
VALUES ('SomeData')
0
On

Sure:

 SELECT GuidKEy FROM [Table] WHERE AutoID= scope_identity()
0
On

You can do the following:

DECLARE @TempTable TABLE (GuidKey UNIQUEIDENTIFIER)

INSERT INTO YourTable(Columns) 
  OUTPUT INSERTED.GuidKey INTO @TempTable(GuidKey) 
  VALUES(YourVALUES)

This will insert the inserted GuidKey into @TempTable. You can then pull the value from that table.

0
On

For the uniqueidentifier i do as follows:

DECLARE @ID uniqueidentifier
SET @ID = newId()

...

Then i use the @ID in my insert statement. Finally i return the value using SELECT @ID or RETURN @ID