118

我有一个现有的表,因为我没有创建它并将ID列设置为表的标识列,所以我将要删除它。

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

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

4

4 回答 4

163
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]
于 2012-05-23T18:28:23.180 回答
36

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

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

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

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

于 2012-05-23T19:19:21.680 回答
12
[id] [int] IDENTITY(1,1) NOT NULL,

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

在此处输入图像描述

于 2012-05-23T18:27:48.150 回答
-3

唯一键最多允许 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”中插入重复键。
该语句已终止。

于 2016-03-29T10:34:51.340 回答