views:

24

answers:

2

Is there a way in SQL Server to create a table with a primary key that auto-increments itself? I've been looking at the "UniqueIdentifier" type, but this doesn't seem to do what I expect.

Currently, I have something like this:

CREATE TABLE [dbo].[MyTable](
        [Date] [datetime] NOT NULL,
    [MyField1] [nchar](50) NOT NULL,
    [MyField2] [nvarchar](max) NULL,
    [Key] [uniqueidentifier] NOT NULL
) ON [PRIMARY]

Basically, I want KEY to start at 1 and just increment itself for each record.

+1  A: 

Define your primary key in the table create statement like this:

[Key] [int] IDENTITY(1,1) NOT NULL

Per Hornshøj-Schierbeck
But he wants to use a Guid as the primary key.
starskythehutch
@starskythehutch: He does say he wants it to start with 1 and increment, so i figured he wants an int?
Per Hornshøj-Schierbeck
fair enough. Deleted my answer.
starskythehutch
+2  A: 

You're looking for the IDENTITY property.

From the documentation:

Creates an identity column in a table. This property is used with the CREATE TABLE and ALTER TABLE Transact-SQL statements.

IDENTITY [ (seed , increment) ]

seed

Is the value that is used for the very first row loaded into the table.

increment

Is the incremental value that is added to the identity value of the previous row that was loaded.

You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).

Btw, all of this is also easily achieved from Sql Server's mgmt UI. Just right click on your table and select design. Then select the proper column and set the IDENTITY property.

Paul Sasik

related questions