如何使用标识列创build表

我有一个现有的表,我将要吹走,因为我没有创build它的ID列设置为表的标识列。

使用SQL Server Management Studio,我编写了一个创build到…的现有表,并得到了这个:

 CREATE TABLE [dbo].[History]( [ID] [int] NOT NULL, [RequestID] [int] NOT NULL, [EmployeeID] [varchar](50) NOT NULL, [DateStamp] [datetime] NOT NULL, CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] 

我的问题是,我将如何修改这个SQL,以便我的结果表的ID列设置为身份

 CREATE TABLE [dbo].[History]( [ID] [int] IDENTITY(1,1) NOT NULL, [RequestID] [int] NOT NULL, [EmployeeID] [varchar](50) NOT NULL, [DateStamp] [datetime] NOT NULL, CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ) ON [PRIMARY] 

这已经被回答了,但我认为最简单的语法是:

 CREATE TABLE History ( ID int primary key IDENTITY(1,1) NOT NULL, . . . 

当你真正想改变选项时,更复杂的约束索引是有用的。

顺便说一句,我更喜欢命名这样一个列HistoryId,所以它匹配外键关系中的列的名称。

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

当然,因为您正在SQL Server Management Studio中创build表,您可以使用表devise器来设置Identity Specification。

在这里输入图像说明

唯一键允许最多2个NULL值。 阐释:

 create table teppp ( id int identity(1,1) primary key, name varchar(10 )unique, addresss varchar(10) ) insert into teppp ( name,addresss) values ('','address1') insert into teppp ( name,addresss) values ('NULL','address2') insert into teppp ( addresss) values ('address3') select * from teppp null string , address1 NULL,address2 NULL,address3 

如果您尝试插入相同的值,如下所示:

 insert into teppp ( name,addresss) values ('','address4') insert into teppp ( name,addresss) values ('NULL','address5') insert into teppp ( addresss) values ('address6') 

每次你会得到如下错误:

违反UNIQUE KEY约束“UQ__teppp__72E12F1B2E1BDC42”。 不能在对象'dbo.teppp'中插入重复的键。
该语句已终止。