简体   繁体   中英

SQL Server won't let me make column identity

So I have a table in SQL Server w/ a primary key column, and 4 other columns. When I modify the table, and select the primary key column to be identity, it won't let me save the table.

How can I make it an identity column through T-SQL or something without going to the UI?

Thanks.

Here's the create

USE [db]
GO

/****** Object:  Table [dbo].[tblMessages]    Script Date: 04/05/2011 11:58:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tblMessages](
    [messageId] [int] NOT NULL,
    [messageText] [varchar](500) NOT NULL,
    [messageLatitude] [float] NOT NULL,
    [messageLongitude] [float] NOT NULL,
    [messageTimestamp] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [messageId] 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

You cannot turn an existing column into an IDENTITY column after it's been created.

ALTER TABLE dbo.YourTable
  ALTER COLUMN YourColumn INT IDENTITY

will cause an error:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'IDENTITY'.

You need to create a new column of type INT IDENTITY and then possibly drop the old one. Or if your table is still empty: drop it and re-create it with the correct settings for your ID column

ALTER TABLE MyTable
ADD NewIdentity INT IDENTITY;

ALTER TABLE MyTable
DROP COLUMN OldPK;

EDIT

If your table is empty, just drop it and add IDENTITY after INT on your PK column and be done with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM