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.
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.
-- 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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With