17 February 2017

Creating a Table With a Column Value to be Generated Automatically as GUID

Let's say you want to create a table tbl_Users with columns Id, UserId, and Name.

To generate a GUID (uniqueidentifier) automatically for column UserId, you simply need to add DEFAULT NEWSEQUENTIALID() to the UserId column when you create a table like the sample below:

CREATE TABLE [dbo].[tbl_Users]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY,
    [UserId] UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
    [Name] VARCHAR(50) NULL
)

No comments:

Post a Comment