Adding an identity to an existing column

后端 未结 19 2049
温柔的废话
温柔的废话 2020-11-21 13:16

I need to change the primary key of a table to an identity column, and there\'s already a number of rows in table.

I\'ve got a script to clean up the IDs to ensure

相关标签:
19条回答
  • 2020-11-21 14:01

    You can't alter the existing columns for identity.

    You have 2 options,

    1. Create a new table with identity & drop the existing table

    2. 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. Note that you will lose all data if 'if not exists' is not satisfied, so make sure you put the condition on the drop as well!

    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:

    How to alter column to identity(1,1)

    0 讨论(0)
  • 2020-11-21 14:06

    By design there is no simple way to turn on or turn off the identity feature for an existing column. The only clean way to do this is to create a new column and make it an identity column or create a new table and migrate your data.

    If we use SQL Server Management Studio to get rid of the identity value on column "id", a new temporary table is created, the data is moved to the temporary table, the old table is dropped and the new table is renamed.

    Use Management Studio to make the change and then right click in the designer and select "Generate Change Script".

    You will see that this is what SQL server in doing in the background.

    0 讨论(0)
  • 2020-11-21 14:06

    As per my current condition, I follow this approach. I want to give identity to a primary table after data inserted via script.

    As I want to append identity, so it always start from 1 to End of record count that I want.

    --first drop column and add with identity
    ALTER TABLE dbo.tblProductPriceList drop column ID 
    ALTER TABLE dbo.tblProductPriceList add ID INT IDENTITY(1,1)
    
    --then add primary key to that column (exist option you can ignore)
    IF  NOT EXISTS (SELECT * FROM sys.key_constraints  WHERE object_id = OBJECT_ID(N'[dbo].[PK_tblProductPriceList]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblProductPriceList]'))
        ALTER TABLE [tblProductPriceList] ADD PRIMARY KEY (id)
    GO
    

    This will create the same primary key column with identity

    I used this links : https://blog.sqlauthority.com/2014/10/11/sql-server-add-auto-incremental-identity-column-to-table-after-creating-table/

    Add primary key to existing table

    0 讨论(0)
  • 2020-11-21 14:07

    As I understood in normal cases we are creating a table with Primary key which is having Identity property
    So Rename or Delete a column which is associated with Primary Key constraint will not be possible because constraint Rules are validating column structure.
    Tto achieve this we have to process some steps in the following way:
    Let us assume TableName = 'Employee' and ColumnName = 'EmployeeId'

    1. Add new column 'EmployeeId_new' in the 'Employee' table
    ALTER TABLE Employee ADD EmployeeId_new INT IDENTITY(1,1)

    1. Now remove column 'EmployeeId' from 'Employee' table
      ALTER TABLE Employee DROP COLUMN EmployeeId

    2. This will throw error because of Primary Key Constraint rules are applicable and validating column structure.
      *### 'Msg 5074, Level 16, State 1, Line 1 The object [PK_dbo.Employee] is dependent on colmn [EmployeeId].'###

    3. So we have to remove the Primary Key constraint first from the table 'Employee' then we can remove the column
      ALTER TABLE Employee DROP constraint [PK_dbo.Employee]

    4. Now we can remove the column 'EmployeeId' from 'Employee' table as did in the previous step where we got error
      ALTER TABLE Employee DROP COLUMN EmployeeId

    5. Now Column 'EmployeeId' removed from table So we will Rename the newly added new column 'EmployeeId_new' with 'EmployeeId'
      sp_rename 'Employee.EmployeeId', 'EmployeeId_new', 'COLUMN'

    6. To rearrange the table in the same form as It was, we have to add Primary Key Constraint for the column 'EmployeeId'
      ALTER TABLE Employee add constraint [PK_dbo.Employee] primary key (EmployeeId)

    8. Now the table 'Employee' with 'EmployeeId' is modified for Identity rules along with existing primary key constraint

    0 讨论(0)
  • 2020-11-21 14:08

    There isn't one, sadly; the IDENTITY property belongs to the table rather than the column.

    The easier way is to do it in the GUI, but if this isn't an option, you can go the long way around of copying the data, dropping the column, re-adding it with identity, and putting the data back.

    See here for a blow-by-blow account.

    0 讨论(0)
  • 2020-11-21 14:09

    There is cool solution described here: SQL SERVER – Add or Remove Identity Property on Column

    In short edit manually your table in SQL Manager, switch the identity, DO NOT SAVE changes, just show the script which will be created for the changes, copy it and use it later.

    It is huge time saver, because it (the script) contains all the foreign keys, indices, etc. related to the table you change. Writting this manually... God forbid.

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