Autoincrement uniqueidentifier

我是研究僧i 提交于 2019-11-27 20:18:32

问题


Basically I want to use uniqueidentifier in similar way as identity. I don't want to insert values into it, It should just insert values automatically, different value for each row. I'm not able to set autoincrement on columns of type uniqueidentifier(the property 'autoincrement' is set to false and is not editable).


回答1:


Or even better: use the newsequentialid() as the default for your UNIQUEIDENITIFER column. That'll give you a somewhat sequential series of GUIDs.

CREATE TABLE dbo.YourTable   
   (SerialID UNIQUEIDENTIFIER 
        CONSTRAINT DF_SerialID DEFAULT newsequentialid(),
     .... (other columns)......
   )

Trouble is: newsequentialid is only available as a column default - you cannot call it as a function or anything. But that seems to fit your requirements.

UPDATE: there appears to be an acknowledged bug in SQL Server Management Studio that prevents specifying newsequentialid() as the default for a column in the interactive table designer.

See: http://social.msdn.microsoft.com/Forums/en-US/sqltools/thread/cad8a4d7-714f-44a2-adb0-569655ac66e6

Workaround: create your table without specifying any default, and then type in this T-SQL statement in a normal query window and run it:

ALTER TABLE dbo.YourTable
    ADD CONSTRAINT DF_SerialID DEFAULT newsequentialid() FOR SerialID

That should do the trick!




回答2:


I guess you mean in SQLServer and not C#...

Set the column as PRIMARY KEY and ROWGUID

RowGuid http://img341.imageshack.us/img341/8867/sqlserverrowguid.png




回答3:


Use NewID() as the default value. At least this is what you would do for SQL Server.




回答4:


I think

CREATE TABLE dbo.YourTable
(
    SerialID UNIQUEIDENTIFIER PRIMARY KEY DEFAULT newsequentialid()
)

is simplier



来源:https://stackoverflow.com/questions/2837559/autoincrement-uniqueidentifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!