开发者

How to define a column to be both primary key and self-incremented in Transact-sql?

开发者 https://www.devze.com 2023-02-11 05:29 出处:网络
to define a column to be a primary key I do this ContactID int NOT NULL PRIMARY KEY It looks like I need still to provide the value of the ContactID when inserting rows. I want primary key to be u

to define a column to be a primary key I do this

ContactID int NOT NULL PRIMARY KEY 

It looks like I need still to provide the value of the ContactID when inserting rows. I want primary key to be unique and incremented (+1) as if I defined the table using the designer.

Tha开发者_开发技巧nks for helping


Simply do this:

ContactID int not null identity(1,1) primary key


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Contacts](
    [ContactID] [int] IDENTITY(1,1) NOT NULL,
   CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED 
(
[ContactID] ASC)
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]
GO

you will have to add your other columns, etc.

UPDATE: as absolute minimum statement:

CREATE TABLE Contacts(ContactID INT IDENTITY (1,1) PRIMARY KEY);
0

精彩评论

暂无评论...
验证码 换一张
取 消