开发者

SQL Server convert column to an identity column

开发者 https://www.devze.com 2023-01-13 19:22 出处:网络
I am using SQL Server 2008. One int column I used as primary key but not identity column (whose value will be increased by 1 automatically). I want to convert this column to identity column. Any solut

I am using SQL Server 2008. One int column I used as primary key but not identity column (whose value will be increased by 1 automatically). I want to convert this column to identity column. Any solutions?开发者_开发知识库

thanks in advance, George


Unfortunately, you cannot change a field to IDENTITY on an existing table.

You should:

  • Create a new table with the IDENTITY field
  • Issue SET IDENTITY_INSERT ON for the new table
  • Insert the data into the new table
  • Issue SET IDENTITY_INSERT OFF for the new table
  • Drop the old table
  • Rename the new table to the old name.

You can use SSMS to change the field type, it will do all this for you behind the scenes.

Here's a sample table:

CREATE TABLE plain (id INT NOT NULL PRIMARY KEY)

INSERT
INTO    plain
VALUES  (1000)

and the script generated by SSMS:

SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_plain
    (
    id int NOT NULL IDENTITY (1, 1)
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_plain SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_plain ON
GO
IF EXISTS(SELECT * FROM dbo.plain)
     EXEC('INSERT INTO dbo.Tmp_plain (id)
        SELECT id FROM dbo.plain WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_plain OFF
GO
DROP TABLE dbo.plain
GO
EXECUTE sp_rename N'dbo.Tmp_plain', N'plain', 'OBJECT' 
GO
ALTER TABLE dbo.plain ADD CONSTRAINT
    PK__plain__3213E83F1A609306 PRIMARY KEY CLUSTERED 
    (
    id
    ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
COMMIT


Go to your table object in object explorer in sql server right click on a table say modify, than click on a field which is primary key that you want to convert to identity, than below you'll see column properties , there you need to change as (Is Identity) Yes and Idendity Increment 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消