主键不会递增

时间:2011-01-01 20:48:08

标签: sql sql-server tsql identity

我的表中的主键列有问题。我将id列设置为主键(我在Management studio中创建表并在那里设置),标识为yes,增量为1,seed为1,但是当我尝试插入它时不想插入(只插入一次)并且不会增加id的值。 该怎么办 ?这来自Managememt studio。

/****** Object:  Table [dbo].[club]    Script Date: 01/01/2011 22:00:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[club](
    [id] [int] NOT NULL,
    [name] [varchar](50) NOT NULL,
    [id_city] [int] NOT NULL,
    [street] [varchar](50) NULL,
    [street_number] [nchar](10) NULL,
    [descritpion] [varchar](500) NULL,
    [logo_path] [varchar](50) NULL,
 CONSTRAINT [PK_club] 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]

GO

SET ANSI_PADDING OFF
GO

3 个答案:

答案 0 :(得分:4)

根据提供的CREATE TABLE语句,很明显IDENTITY属性未启用。它应该类似于:

CREATE TABLE [dbo].[club](
  [id] [int] IDENTITY(1,1) NOT NULL,
  [name] [varchar](50) NOT NULL,
  [id_city] [int] NOT NULL,
  [street] [varchar](50) NULL,
  [street_number] [nchar](10) NULL,
  [descritpion] [varchar](500) NULL,
  [logo_path] [varchar](50) NULL,
  CONSTRAINT [PK_club] 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]
  )
创建表后无法应用

IDENTITY - 表格需要删除&创建。你有几个选择:

  • 删除表,使用我提供的CREATE TABLE语句,重新向表中添加数据
  • 创建临时表以存储数据,删除现有的club表,使用IDENTITY属性重新创建club表,从临时表导入行,继续插入其他数据

答案 1 :(得分:1)

由于自动增量不起作用,您可能没有宝贵的数据。

我建议使用以下脚本重新创建表:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

DROP TABLE [dbo].[club]
GO

CREATE TABLE [dbo].[club](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](50) NOT NULL,
    [id_city] [int] NOT NULL,
    [street] [varchar](50) NULL,
    [street_number] [nchar](10) NULL,
    [descritpion] [varchar](500) NULL,
    [logo_path] [varchar](50) NULL,
 CONSTRAINT [PK_club] 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]

GO

SET ANSI_PADDING OFF
GO

答案 2 :(得分:0)

主键不会自行递增,因为它是主键。

如果您想在SQL Server中使用“自动增量”字段,则必须将该列设置为identity列。