如何在存储过程中生成新的 Guid?

我当前有一个存储过程,我想在其中向表中插入新行。

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

所以主键“ id”是一个 Guid。我知道如何在 C # 代码中创建一个新的 Guid,但是在存储过程中,我不确定如何为主键值生成新的 Guid。

104775 次浏览

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

Try this:

SELECT NewId()

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.

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;

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

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