How to generate a new Guid in stored procedure?

SqlSql ServerStored Procedures

Sql Problem Overview


I currently have a stored procedure in which I want to insert new rows into a table.

insert into cars
(id, Make, Model)
values('A new Guid', "Ford", "Mustang")

So the primary key 'id' is a Guid. I know how to create a new Guid in C# code but within the stored procedure I'm unsure how to generate the new Guids for the primary key values.

Sql Solutions


Solution 1 - Sql

With SQL Server you can use the function NEWID. You're using C# so I assume that you're using SQL Server. I'm sure other database system have similar functions.

select NEWID()

If you're using Oracle then you can use the SYS_GUID() function. Check out the answer to this question: Generate a GUID in Oracle

Solution 2 - Sql

Try this:

SELECT NewId()

Solution 3 - Sql

You didn't ask about this in your question, but I think it's worth pointing out that using a GUID for a primary key is not always a good idea. While it's simple, it can affect performance when a GUID is used in an index. Have you considered using an Identity column that is an integer value instead?

Here are a couple of articles that might be helpful to read.

Solution 4 - Sql

In MySQL it is UUID(). so the query would be:

insert into cars
(id, Make, Model)
values(UUID(), "Ford", "Mustang")

if you want to reuse the uuid you can do it like this:

set @id=UUID();
insert into cars
(id, Make, Model)
values(@id, "Ford", "Mustang");
select @id;

Solution 5 - Sql

In the format of the question (spot the pedant!)

insert into cars
  (id, Make, Model)
  values(NEWID(), "Ford", "Mustang")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr CricketView Question on Stackoverflow
Solution 1 - SqlAdam PoradView Answer on Stackoverflow
Solution 2 - SqlBradBView Answer on Stackoverflow
Solution 3 - SqlAdam PoradView Answer on Stackoverflow
Solution 4 - SqlFusca SoftwareView Answer on Stackoverflow
Solution 5 - SqlRegianniView Answer on Stackoverflow