Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoincrement uniqueidentifier

Tags:

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).

like image 697
Rasto Avatar asked May 14 '10 20:05

Rasto


People also ask

What does Autoincrement do in SQL?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

What is datatype Uniqueidentifier?

Uniqueidentifier is a Microsoft SQL Server data type that is used to store Globally Unique Identifiers (GUIDs). It can store 16 bytes of data. The Developer tool treats the Uniqueidentifier data type as String.

What does Autoincrement mean?

Auto Increment is a field used to generate a unique number for every new record added into a table. This is generally used for the primary key column as it becomes easy for the developers to automatically generate a unique number for every new record.

Can Uniqueidentifier be duplicated?

Well, no: the nature of a uniqueidentifier is to not allow duplicate entries.


1 Answers

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!

like image 69
marc_s Avatar answered Sep 20 '22 15:09

marc_s