数据库创建过程中的身份问

时间:2012-11-27 21:23:05

标签: sql-server identity database-create

使用SQL Server Management Studio,我的问题源于数据库创建脚本。编写脚本是为了创建一个数据库,其中许多表都有一个标识列:

CREATE TABLE Workshop
(
    WorkshopID int IDENTITY,
    WorkshopName varchar(40) NOT NULL,
    Description varchar(800),
    CONSTRAINT PK_Workshop PRIMARY KEY (WorkshopID)
);

我的问题是,即使脚本明确地将列创建为标识列,在脚本运行之后,任何应该是标识列的列实际上都不会将该列设置为标识。

澄清一下:运行上面的代码将创建指定的表,但WorkshopID将不是标识列。

需要更改哪些内容才能使脚本以书面形式运行?

1 个答案:

答案 0 :(得分:0)

仅供参考,如果您使用SQL Management Studio的设计器为此生成脚本,则这是生成的脚本:

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Table_1
    (
    WorkshopID int NOT NULL IDENTITY (1, 1),
    WorkshopName varchar(40) NOT NULL,
    Description varchar(800) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Table_1 ADD CONSTRAINT
    PK_Table_1 PRIMARY KEY CLUSTERED 
    (
    WorkshopID
    ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,   ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
ALTER TABLE dbo.Table_1 SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

如果您创建表格,然后使用“创建到...”菜单选项对其进行编写,则会得到一个完全不同的脚本:

USE [MyDatabase]
GO

/****** Object:  Table [dbo].[Workshop]    Script Date: 11/27/2012 14:05:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Workshop](
    [WorkshopID] [int] IDENTITY(1,1) NOT NULL,
    [WorkshopName] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Description] [varchar](800) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 CONSTRAINT [PK_Workshop] PRIMARY KEY CLUSTERED 
(
    [WorkshopID] 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

SET ANSI_PADDING OFF
GO