Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the GUID value of a new row after inserting it? [duplicate]

I am trying to get the Id of newly inserted record in Sqlserver. I have checked the Scope_Identity() but this is said to return the value of the autoincrement column. The column I am using for Id is Guid. I want this Guid column value after the insert. How should this be achieved? Or I must have to write a custom tedious function to get the Id of newly inserted record.

like image 379
Spirals Whirls Avatar asked May 20 '13 16:05

Spirals Whirls


People also ask

How do I get the last inserted GUID in SQL Server?

Just between the Insert section and Values keyword. There is a query statement to output the inserted Guid into the variable table. Then to get the value itself you can see the last query where we select the ColGuid from the variable table.

How do I generate a random GUID in SQL?

-- If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function. -- This will return a new random uniqueidentifier e.g. You can directly use this with INSERT statement to insert new row in table.

How do I add a new GUID to a table in SQL?

Open a new query window and connect to the database that contains the table or view to be edited. Use the newid() function to populate the global ID or GUID column when you insert a record to the table. Note that you could use the Next_GlobalID stored procedure to get the next ID value.

Which data type is used for assigning GUID value in SQL?

The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.


1 Answers

You can try and use OUTPUT, it would be something like:

INSERT INTO ExampleTable (<Column1>, <Column2>, <Column3>) 
OUTPUT INSERTED.ID
VALUES (<Value1>, <Value2>, <Value3>)

Also, this question, has a lot more info on the different types of identity selection, you should check it out.

EDIT

You would use this as a regular scalar:

var command = new SqlCommand("...");
Guid id = (Guid) command.ExecuteScalar();
like image 152
Dimitar Dimitrov Avatar answered Nov 14 '22 23:11

Dimitar Dimitrov