Archive

Posts Tagged ‘GUID’

Using Built-in System Functions – NEWID() and NEWSEQUENTIALID()

25.05.2011 No comments

You can use NEWID() and NEWSEQUENTIALID() to create a unique value of type UNIQUEIDENTIFIER.

You can use the NEWID() as any other TSQL function as below:

— © 2011 – Vishal (http://SqlAndMe.com)

 

SELECT NEWID() AS 'Unique ID'

Result Set:

Unique ID

————————————

86E49A76-B4CE-4798-9091-B7E494C05705

 

(1 row(s) affected)

 

NEWSEQUENTIALID() generates a new GUID which is greater than previously generated GUID using NEWSEQUENTIALID(). NEWSEQUENTIALID() can only be used in a DEFAULT constraint for a table.

— © 2011 – Vishal (http://SqlAndMe.com)

 

CREATE TABLE TestTable

(

      INT_ID INT,

      Sequential_ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),

      Unique_ID     UNIQUEIDENTIFIER DEFAULT NEWID()

)

We can test this by adding a few rows:

INSERT INTO TestTable (INT_ID) VALUES (1), (2), (3), (4), (5)

SELECT * FROM TestTable

Result Set:

INT_ID     Sequential_ID                        Unique_ID

——— ———————————— ————————————

1         E326E023-B286-E011-8FC2-F4CE4697A63A EA44BE6E-A0EE-4A52-85BC-C24F6ADC4DD8

2         E426E023-B286-E011-8FC2-F4CE4697A63A D534CB28-922D-49C9-A51A-1CB8185CD662

3         E526E023-B286-E011-8FC2-F4CE4697A63A FFF87554-CFD2-46C9-B351-0A63F7552CCE

4         E626E023-B286-E011-8FC2-F4CE4697A63A 55219CF9-5D41-407D-95E5-BE9C4A013806

5         E726E023-B286-E011-8FC2-F4CE4697A63A B3C74453-05E7-42A3-8DD0-8FAA70F780A6

 

(5 row(s) affected)

 

Hope This Helps!

Vishal