如果未提供,则在 SQL Server 中生成新的 GUID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14817235/
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
Generate new GUID in SQL Server if one is not provided
提问by Slee
I am updating my database to have a column for a GUID for each record in a table.
我正在更新我的数据库,以便为表中的每条记录创建一个 GUID 列。
This table is populated by several different sources and some of them will not provide a GUID for new records.
此表由几个不同的来源填充,其中一些不会为新记录提供 GUID。
How can I populate this column with a newid() on the DB side only if there was no value passed in for a new record?
仅当没有为新记录传入值时,如何在 DB 端使用 newid() 填充此列?
回答by Zane
DO NOT I REPEAT DO NOT PLACE A DEFAULT COLUMN OF NEWID()
. If you do the GUID you get will be completely random and if you have any sort of indexing on this column it will be useless. If you are going to do this you want to set the column default to be NEWSEQUENTIALID ( )
不要重复不要放置默认列NEWID()
。如果你做 GUID,你得到的将是完全随机的,如果你在这个列上有任何类型的索引,它将毫无用处。如果您打算这样做,您希望将列默认设置为NEWSEQUENTIALID ( )
Kimberly Tripp has a Great Articleand another Great Articleon this subject.
金伯利·特里普 (Kimberly Tripp)在这个主题上有一篇很棒的文章和另一篇很棒的文章。
To implement NEWSEQUENTIALID ( )
as a default:
要实现NEWSEQUENTIALID ( )
为默认值:
CREATE TABLE foo
(unq_id UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
cola varchar(10));
回答by Jeff Rosenberg
You can set the default value for the column to NEWID()
. Then a GUID will be created and assigned only if one hasn't already been.
您可以将列的默认值设置为NEWID()
。然后,只有在尚未创建和分配 GUID 时,才会创建和分配 GUID。