如何使用标识列创建表

时间:2012-05-23 18:24:54

标签: sql sql-server tsql

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

使用 SQL Server Management Studio ,我编写了现有表的“Create To ...”,并得到了这个:

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列设置为标识

4 个答案:

答案 0 :(得分:145)

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]

答案 1 :(得分:31)

这已经得到了解答,但我认为最简单的语法是:

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

当您真正想要更改选项时,更复杂的约束索引非常有用。

顺便说一下,我更喜欢将这样的列命名为HistoryId,因此它匹配外键关系中列的名称。

答案 2 :(得分:11)

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

当然,因为您在SQL Server Management Studio中创建表,所以可以使用表设计器来设置标识规范。

enter image description here

答案 3 :(得分:-2)

唯一键允许最多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'中插入重复键   声明已经终止。