SQL 如何在存储过程中生成新的 Guid?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3938113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a new Guid in stored procedure?
提问by Mr Cricket
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.
所以主键 'id' 是一个 Guid。我知道如何在 C# 代码中创建一个新的 Guid,但在存储过程中我不确定如何为主键值生成新的 Guid。
回答by Adam Porad
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.
对于 SQL Server,您可以使用NEWID函数。您使用的是 C#,所以我假设您使用的是 SQL Server。我相信其他数据库系统也有类似的功能。
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
如果您使用的是 Oracle,那么您可以使用该SYS_GUID()
功能。查看此问题的答案:在 Oracle 中生成 GUID
回答by BradB
Try this:
尝试这个:
SELECT NewId()
回答by Adam Porad
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 columnthat is an integer value instead?
您没有在问题中询问这一点,但我认为值得指出的是,为主键使用 GUID 并不总是一个好主意。虽然它很简单,但在索引中使用 GUID 时会影响性能。您是否考虑过使用作为整数值的Identity 列?
Here are a couple of articles that might be helpful to read.
这里有几篇文章可能对阅读有所帮助。
- Performance Effects of Using GUIDs as Primary Keys(SQL Server Magazine)
- Primary Keys: IDs versus GUIDs(Jeff Atwood)
- The Cost of GUIDs as Primary Keys(Jimmy Nelson's article referenced by the two other articles)
- 使用 GUID 作为主键的性能影响(SQL Server 杂志)
- 主键:ID 与 GUID(Jeff Atwood)
- GUID 作为主键的成本(Jimmy Nelson 的文章被其他两篇文章引用)
回答by Fusca Software
In MySQL it is UUID(). so the query would be:
在 MySQL 中它是 UUID()。所以查询将是:
insert into cars
(id, Make, Model)
values(UUID(), "Ford", "Mustang")
if you want to reuse the uuid you can do it like this:
如果你想重用 uuid,你可以这样做:
set @id=UUID();
insert into cars
(id, Make, Model)
values(@id, "Ford", "Mustang");
select @id;
回答by Regianni
In the format of the question (spot the pedant!)
以问题的格式(发现书呆子!)
insert into cars
(id, Make, Model)
values(NEWID(), "Ford", "Mustang")