Changing Primary Keys for Existing Tables Containing Data

VDT-7677 161 Reputation points
2025-03-22T04:05:32.15+00:00

Hi,

Running SQL Server 2008 R2 SP3.

We are working on implementing some DDL changes with the goal of improving overall performance.

Aside from indexing strategies we would like to change the data type of primary key columns from varchar to bigint.  Current PK values are generated outside the database (prefix code + sequential number).

We would like the database to take care of the PK generation using IDENTITY(1,1), and back-fill the existing rows with identity values.  It should also be noted that at the end of the transformation the new PK column needs to have the same name as the old PK column.

What would be the proper steps to accomplish what I’m looking to do?

Thanks!

SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
177 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 120.3K Reputation points MVP
    2025-03-22T11:41:49.19+00:00

    Create a new version of the table and copy data over. You need to use SET IDENTITY_INSERT ON to insert the existing values. Note that you cannot keep your prefix code.

    If there are other tables which refers to this table with a foreign-key constraint, you need to alter the column in this table.

    Make sure that don't lose any indexes, triggers, constraints etc when you create the new table, but you need to bring them over to the new table.


1 additional answer

Sort by: Most helpful
  1. ZoeHui-MSFT 41,456 Reputation points
    2025-03-24T05:47:03.3733333+00:00

    Hi @VDT-7677,

    You may also check this blog.

    Disable, enable, drop and recreate SQL Server Foreign Keys

    Regards,

    Zoe Hui


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.