Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server convert column to an identity column

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

like image 779
George2 Avatar asked Dec 22 '22 23:12

George2


1 Answers

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
like image 137
Quassnoi Avatar answered Mar 07 '23 10:03

Quassnoi