SQL Server convert column to an identity column

后端 未结 2 723
礼貌的吻别
礼貌的吻别 2021-01-13 13:51

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

相关标签:
2条回答
  • 2021-01-13 14:35

    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 讨论(0)
  • 2021-01-13 14:43

    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
    
    0 讨论(0)
提交回复
热议问题