How to Alter a table for Identity Specification is identity SQL Server

后端 未结 3 1865
南方客
南方客 2020-12-06 06:25

not working

ALTER TABLE ProductInProduct ALTER COLUMN Id KEY IDENTITY (1, 1);

Check Image

I have a table ProductInProduct is

相关标签:
3条回答
  • 2020-12-06 06:37

    You don't set value to default in a table. You should clear the option "Default value or Binding" first.

    0 讨论(0)
  • 2020-12-06 06:57

    You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

    ALTER TABLE ProductInProduct 
    ADD NewId INT IDENTITY (1, 1);
    

    Update:

    OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

    0 讨论(0)
  • 2020-12-06 06:59

    You can't alter the existing columns for identity.

    You have 2 options,

    Create a new table with identity & drop the existing table

    Create a new column with identity & drop the existing column

    Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.

    CREATE TABLE dbo.Tmp_Names
        (
          Id int NOT NULL
                 IDENTITY(1, 1),
          Name varchar(50) NULL
        )
    ON  [PRIMARY]
    go
    
    SET IDENTITY_INSERT dbo.Tmp_Names ON
    go
    
    IF EXISTS ( SELECT  *
                FROM    dbo.Names ) 
        INSERT  INTO dbo.Tmp_Names ( Id, Name )
                SELECT  Id,
                        Name
                FROM    dbo.Names TABLOCKX
    go
    
    SET IDENTITY_INSERT dbo.Tmp_Names OFF
    go
    
    DROP TABLE dbo.Names
    go
    
    Exec sp_rename 'Tmp_Names', 'Names'
    

    Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.

    Alter Table Names
    Add Id_new Int Identity(1, 1)
    Go
    
    Alter Table Names Drop Column ID
    Go
    
    Exec sp_rename 'Names.Id_new', 'ID', 'Column'
    

    See the following Microsoft SQL Server Forum post for more details:

    http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032

    0 讨论(0)
提交回复
热议问题