Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace identity column from int to bigint

I am using SQL Server 2008, and I have a table that contains about 50 mill rows.

That table contains a primary identity column of type int.

I want to upgrade that column to be bigint.

I need to know how to do that in a quick way that will not make my DB server unavailable, and will not delete or ruin any of my data

How should I best do it ? what are the consequences of doing that?

like image 272
Matan L Avatar asked Mar 07 '13 17:03

Matan L


People also ask

Can identity column be Bigint?

An identity column is an integer or bigint column whose values are automatically generated from a system-defined sequence. An identity column provides a way to automatically generate a unique numeric value for each row in a table.

How do you change an int column to an identity column?

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.


1 Answers

Well, it won't be a quick'n'easy way to do this, really....

My approach would be this:

  1. create a new table with identical structure - except for the ID column being BIGINT IDENTITY instead of INT IDENTITY

    ----[ put your server into exclusive single-user mode here; user cannot use your server from this point on ]----

  2. find and disable all foreign key constraints referencing your table

  3. turn SET IDENTITY_INSERT (your new table) ON

  4. insert the rows from your old table into the new table

  5. turn SET IDENTITY_INSERT (your new table) OFF

  6. delete your old table

  7. rename your new table to the old table name

  8. update all table that have a FK reference to your table to use BIGINT instead of INT (that should be doable with a simple ALTER TABLE ..... ALTER COLUMN FKID BIGINT)

  9. re-create all foreign key relationships again

  10. now you can return your server to normal multi-user usage again

like image 64
marc_s Avatar answered Sep 22 '22 14:09

marc_s