SQL Server Change Primary Key Data Type Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceHow to check if a column exists in a SQL Server table?sql primary key and indexSqlite primary key on multiple columnsRemove Primary Key in MySQLUpdating MySQL primary keySQL Server add auto increment primary key to existing tableALTER TABLE to add a composite primary keyInsert auto increment primary key to existing tableAdd primary key to existing tableWhat are the best practices for using a GUID as a primary key, specifically regarding performance?

How should I respond to a player wanting to catch a sword between their hands?

Problem when applying foreach loop

Autumning in love

Limit for e and 1/e

I'm having difficulty getting my players to do stuff in a sandbox campaign

Who can trigger ship-wide alerts in Star Trek?

Do working physicists consider Newtonian mechanics to be "falsified"?

Fishing simulator

What LEGO pieces have "real-world" functionality?

Should you tell Jews they are breaking a commandment?

New Order #5: where Fibonacci and Beatty meet at Wythoff

How to say that you spent the night with someone, you were only sleeping and nothing else?

How to politely respond to generic emails requesting a PhD/job in my lab? Without wasting too much time

Unable to start mainnet node docker container

What did Darwin mean by 'squib' here?

Area of a 2D convex hull

Did the new image of black hole confirm the general theory of relativity?

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

Notation for two qubit composite product state

Single author papers against my advisor's will?

What to do with post with dry rot?

Antler Helmet: Can it work?

What is the electric potential inside a point charge?

What computer would be fastest for Mathematica Home Edition?



SQL Server Change Primary Key Data Type



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceHow to check if a column exists in a SQL Server table?sql primary key and indexSqlite primary key on multiple columnsRemove Primary Key in MySQLUpdating MySQL primary keySQL Server add auto increment primary key to existing tableALTER TABLE to add a composite primary keyInsert auto increment primary key to existing tableAdd primary key to existing tableWhat are the best practices for using a GUID as a primary key, specifically regarding performance?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








6















I am working on SQL Server 2012:



I have a table with a primary key column as INT. I need to change this to a GUID.



Do I alter the table and remove int column as primary key?



Add the GUID column and set it as Primary and drop the old INT column?



Thank you.










share|improve this question






























    6















    I am working on SQL Server 2012:



    I have a table with a primary key column as INT. I need to change this to a GUID.



    Do I alter the table and remove int column as primary key?



    Add the GUID column and set it as Primary and drop the old INT column?



    Thank you.










    share|improve this question


























      6












      6








      6


      1






      I am working on SQL Server 2012:



      I have a table with a primary key column as INT. I need to change this to a GUID.



      Do I alter the table and remove int column as primary key?



      Add the GUID column and set it as Primary and drop the old INT column?



      Thank you.










      share|improve this question
















      I am working on SQL Server 2012:



      I have a table with a primary key column as INT. I need to change this to a GUID.



      Do I alter the table and remove int column as primary key?



      Add the GUID column and set it as Primary and drop the old INT column?



      Thank you.







      sql-server-2012 primary-key






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 3 '18 at 13:13









      DineshDB

      3,97942339




      3,97942339










      asked Jan 9 '17 at 13:50









      GuygarGuygar

      64117




      64117






















          4 Answers
          4






          active

          oldest

          votes


















          11














          You can't change primary key column,unless you drop it..Any operations to change its data type will lead to below error..




          The object 'XXXX' is dependent on column 'XXXX'.




          Only option is to



          1.Drop primary key

          2.change data type

          3.recreate primary key



          ALTER TABLE t1 
          DROP CONSTRAINT PK__t1__3213E83F88CF144D;
          GO

          alter table t1
          alter column id varchar(10) not null

          alter table t1 add primary key (id)


          From 2012,there is a clause called (DROP_EXISTING = ON) which makes things simple ,by dropping the clustered index at final stage and also keeping old index available for all operations..But in your case,this clause won't work..



          So i recommend



          1.create new table with desired schema and indexes,with different name

          2.insert data from old table to new table

          3.finally at the time of switch ,insert data that got accumulated

          4.Rename the table to old table name



          This way you might have less downtime






          share|improve this answer
































            2














            You can change the date type of the primary key in three steps



            Step 1 :- Drop the constraint associated with the Primary key



            ALTER TABLE table_name
            DROP CONSTRAINT constraint_name;


            Step 2 :- Alter the Primay key column to a valid primary key data type



            ALTER TABLE table_name
            ALTER COLUMN pk_column_name target_data_type(size) not null;


            Step 3 :- Make the altered column primary key again



            ALTER TABLE table_name
            ADD PRIMARY KEY (pk_column_name);



            PS :-



            • You can get the Constraint name from the error message when you try to alter the
              pk_column


            • If you already have data in the pk_column make sure the source and target data type of the column both can be used for the existing data. else another two steps would be needed to move the existing data to a temporary column and then perform the steps and bring back that data after vetting and dropping that temporary column.







            share|improve this answer























            • THE BEST ANSWER

              – David
              Mar 28 at 19:19


















            1














            Below is a script I wrote to help us deploy a change to primary key column data type.



            This script assumes there aren't any non-primary key constraints (e.g. foreign keys) depending on this column.



            It has a few safety checks as this was designed to be deployed to different servers (dev, uat, live) without creating side effects if the table was somehow different on a server.



            I hope this helps someone. Please let me know if you find anything wrong before down-voting. I'm more than happy to update the script.



            IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C WITH (NOLOCK) WHERE C.TABLE_CATALOG = '<<DB>>' AND C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = '<<Table>>' 
            AND C.COLUMN_NAME = '<<COLUMN>>' AND C.DATA_TYPE = 'int') -- <- Additional test to check the current datatype so this won't make unnecessary or wrong updates
            BEGIN
            DECLARE @pkName VARCHAR(200);
            SELECT @pkName = pkRef.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pkRef WITH (NOLOCK)
            WHERE pkRef.TABLE_CATALOG = '<<DB>>' AND pkRef.TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '<<Table>>'

            IF(@pkName IS NOT NULL)
            BEGIN
            -- Make sure the primary key name is the one you are going to use in script beyond this point.
            IF(@pkName != '<<PRIMARY KEY NAME>>')
            BEGIN
            RAISERROR ('Unexpected primary key name - The primary key found has a different name than expected. Please update the script.', 16, 1);
            RETURN;
            END

            ALTER TABLE dbo.<<Table>>
            DROP CONSTRAINT <<PRIMARY KEY NAME>>; -- Note: this is not a string or a variable (just type the PK name)
            SELECT 'Dropped existing primary key';
            END

            ALTER TABLE dbo.<<Table>> ALTER COLUMN ID BIGINT
            SELECT 'Updated column type to big int';

            ALTER TABLE dbo.<<Table>>
            ADD CONSTRAINT <<PRIMARY KEY NAME>> PRIMARY KEY CLUSTERED (<<COLUMN>>);
            SELECT 'Created the primary key';
            END
            ELSE
            BEGIN
            SELECT 'No change required.';
            END





            share|improve this answer
































              0














              Right in the table you want to change the PK type >> Modify. Go in the column, change the type and save. If you want to see the code for such a change, before saving, you can right-click >> "Generate Change Script ..".






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41549549%2fsql-server-change-primary-key-data-type%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                11














                You can't change primary key column,unless you drop it..Any operations to change its data type will lead to below error..




                The object 'XXXX' is dependent on column 'XXXX'.




                Only option is to



                1.Drop primary key

                2.change data type

                3.recreate primary key



                ALTER TABLE t1 
                DROP CONSTRAINT PK__t1__3213E83F88CF144D;
                GO

                alter table t1
                alter column id varchar(10) not null

                alter table t1 add primary key (id)


                From 2012,there is a clause called (DROP_EXISTING = ON) which makes things simple ,by dropping the clustered index at final stage and also keeping old index available for all operations..But in your case,this clause won't work..



                So i recommend



                1.create new table with desired schema and indexes,with different name

                2.insert data from old table to new table

                3.finally at the time of switch ,insert data that got accumulated

                4.Rename the table to old table name



                This way you might have less downtime






                share|improve this answer





























                  11














                  You can't change primary key column,unless you drop it..Any operations to change its data type will lead to below error..




                  The object 'XXXX' is dependent on column 'XXXX'.




                  Only option is to



                  1.Drop primary key

                  2.change data type

                  3.recreate primary key



                  ALTER TABLE t1 
                  DROP CONSTRAINT PK__t1__3213E83F88CF144D;
                  GO

                  alter table t1
                  alter column id varchar(10) not null

                  alter table t1 add primary key (id)


                  From 2012,there is a clause called (DROP_EXISTING = ON) which makes things simple ,by dropping the clustered index at final stage and also keeping old index available for all operations..But in your case,this clause won't work..



                  So i recommend



                  1.create new table with desired schema and indexes,with different name

                  2.insert data from old table to new table

                  3.finally at the time of switch ,insert data that got accumulated

                  4.Rename the table to old table name



                  This way you might have less downtime






                  share|improve this answer



























                    11












                    11








                    11







                    You can't change primary key column,unless you drop it..Any operations to change its data type will lead to below error..




                    The object 'XXXX' is dependent on column 'XXXX'.




                    Only option is to



                    1.Drop primary key

                    2.change data type

                    3.recreate primary key



                    ALTER TABLE t1 
                    DROP CONSTRAINT PK__t1__3213E83F88CF144D;
                    GO

                    alter table t1
                    alter column id varchar(10) not null

                    alter table t1 add primary key (id)


                    From 2012,there is a clause called (DROP_EXISTING = ON) which makes things simple ,by dropping the clustered index at final stage and also keeping old index available for all operations..But in your case,this clause won't work..



                    So i recommend



                    1.create new table with desired schema and indexes,with different name

                    2.insert data from old table to new table

                    3.finally at the time of switch ,insert data that got accumulated

                    4.Rename the table to old table name



                    This way you might have less downtime






                    share|improve this answer















                    You can't change primary key column,unless you drop it..Any operations to change its data type will lead to below error..




                    The object 'XXXX' is dependent on column 'XXXX'.




                    Only option is to



                    1.Drop primary key

                    2.change data type

                    3.recreate primary key



                    ALTER TABLE t1 
                    DROP CONSTRAINT PK__t1__3213E83F88CF144D;
                    GO

                    alter table t1
                    alter column id varchar(10) not null

                    alter table t1 add primary key (id)


                    From 2012,there is a clause called (DROP_EXISTING = ON) which makes things simple ,by dropping the clustered index at final stage and also keeping old index available for all operations..But in your case,this clause won't work..



                    So i recommend



                    1.create new table with desired schema and indexes,with different name

                    2.insert data from old table to new table

                    3.finally at the time of switch ,insert data that got accumulated

                    4.Rename the table to old table name



                    This way you might have less downtime







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 8 at 14:56

























                    answered Jan 9 '17 at 14:32









                    TheGameiswarTheGameiswar

                    21.6k53165




                    21.6k53165























                        2














                        You can change the date type of the primary key in three steps



                        Step 1 :- Drop the constraint associated with the Primary key



                        ALTER TABLE table_name
                        DROP CONSTRAINT constraint_name;


                        Step 2 :- Alter the Primay key column to a valid primary key data type



                        ALTER TABLE table_name
                        ALTER COLUMN pk_column_name target_data_type(size) not null;


                        Step 3 :- Make the altered column primary key again



                        ALTER TABLE table_name
                        ADD PRIMARY KEY (pk_column_name);



                        PS :-



                        • You can get the Constraint name from the error message when you try to alter the
                          pk_column


                        • If you already have data in the pk_column make sure the source and target data type of the column both can be used for the existing data. else another two steps would be needed to move the existing data to a temporary column and then perform the steps and bring back that data after vetting and dropping that temporary column.







                        share|improve this answer























                        • THE BEST ANSWER

                          – David
                          Mar 28 at 19:19















                        2














                        You can change the date type of the primary key in three steps



                        Step 1 :- Drop the constraint associated with the Primary key



                        ALTER TABLE table_name
                        DROP CONSTRAINT constraint_name;


                        Step 2 :- Alter the Primay key column to a valid primary key data type



                        ALTER TABLE table_name
                        ALTER COLUMN pk_column_name target_data_type(size) not null;


                        Step 3 :- Make the altered column primary key again



                        ALTER TABLE table_name
                        ADD PRIMARY KEY (pk_column_name);



                        PS :-



                        • You can get the Constraint name from the error message when you try to alter the
                          pk_column


                        • If you already have data in the pk_column make sure the source and target data type of the column both can be used for the existing data. else another two steps would be needed to move the existing data to a temporary column and then perform the steps and bring back that data after vetting and dropping that temporary column.







                        share|improve this answer























                        • THE BEST ANSWER

                          – David
                          Mar 28 at 19:19













                        2












                        2








                        2







                        You can change the date type of the primary key in three steps



                        Step 1 :- Drop the constraint associated with the Primary key



                        ALTER TABLE table_name
                        DROP CONSTRAINT constraint_name;


                        Step 2 :- Alter the Primay key column to a valid primary key data type



                        ALTER TABLE table_name
                        ALTER COLUMN pk_column_name target_data_type(size) not null;


                        Step 3 :- Make the altered column primary key again



                        ALTER TABLE table_name
                        ADD PRIMARY KEY (pk_column_name);



                        PS :-



                        • You can get the Constraint name from the error message when you try to alter the
                          pk_column


                        • If you already have data in the pk_column make sure the source and target data type of the column both can be used for the existing data. else another two steps would be needed to move the existing data to a temporary column and then perform the steps and bring back that data after vetting and dropping that temporary column.







                        share|improve this answer













                        You can change the date type of the primary key in three steps



                        Step 1 :- Drop the constraint associated with the Primary key



                        ALTER TABLE table_name
                        DROP CONSTRAINT constraint_name;


                        Step 2 :- Alter the Primay key column to a valid primary key data type



                        ALTER TABLE table_name
                        ALTER COLUMN pk_column_name target_data_type(size) not null;


                        Step 3 :- Make the altered column primary key again



                        ALTER TABLE table_name
                        ADD PRIMARY KEY (pk_column_name);



                        PS :-



                        • You can get the Constraint name from the error message when you try to alter the
                          pk_column


                        • If you already have data in the pk_column make sure the source and target data type of the column both can be used for the existing data. else another two steps would be needed to move the existing data to a temporary column and then perform the steps and bring back that data after vetting and dropping that temporary column.








                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Dec 3 '18 at 7:23









                        Sumit KumarSumit Kumar

                        211




                        211












                        • THE BEST ANSWER

                          – David
                          Mar 28 at 19:19

















                        • THE BEST ANSWER

                          – David
                          Mar 28 at 19:19
















                        THE BEST ANSWER

                        – David
                        Mar 28 at 19:19





                        THE BEST ANSWER

                        – David
                        Mar 28 at 19:19











                        1














                        Below is a script I wrote to help us deploy a change to primary key column data type.



                        This script assumes there aren't any non-primary key constraints (e.g. foreign keys) depending on this column.



                        It has a few safety checks as this was designed to be deployed to different servers (dev, uat, live) without creating side effects if the table was somehow different on a server.



                        I hope this helps someone. Please let me know if you find anything wrong before down-voting. I'm more than happy to update the script.



                        IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C WITH (NOLOCK) WHERE C.TABLE_CATALOG = '<<DB>>' AND C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = '<<Table>>' 
                        AND C.COLUMN_NAME = '<<COLUMN>>' AND C.DATA_TYPE = 'int') -- <- Additional test to check the current datatype so this won't make unnecessary or wrong updates
                        BEGIN
                        DECLARE @pkName VARCHAR(200);
                        SELECT @pkName = pkRef.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pkRef WITH (NOLOCK)
                        WHERE pkRef.TABLE_CATALOG = '<<DB>>' AND pkRef.TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '<<Table>>'

                        IF(@pkName IS NOT NULL)
                        BEGIN
                        -- Make sure the primary key name is the one you are going to use in script beyond this point.
                        IF(@pkName != '<<PRIMARY KEY NAME>>')
                        BEGIN
                        RAISERROR ('Unexpected primary key name - The primary key found has a different name than expected. Please update the script.', 16, 1);
                        RETURN;
                        END

                        ALTER TABLE dbo.<<Table>>
                        DROP CONSTRAINT <<PRIMARY KEY NAME>>; -- Note: this is not a string or a variable (just type the PK name)
                        SELECT 'Dropped existing primary key';
                        END

                        ALTER TABLE dbo.<<Table>> ALTER COLUMN ID BIGINT
                        SELECT 'Updated column type to big int';

                        ALTER TABLE dbo.<<Table>>
                        ADD CONSTRAINT <<PRIMARY KEY NAME>> PRIMARY KEY CLUSTERED (<<COLUMN>>);
                        SELECT 'Created the primary key';
                        END
                        ELSE
                        BEGIN
                        SELECT 'No change required.';
                        END





                        share|improve this answer





























                          1














                          Below is a script I wrote to help us deploy a change to primary key column data type.



                          This script assumes there aren't any non-primary key constraints (e.g. foreign keys) depending on this column.



                          It has a few safety checks as this was designed to be deployed to different servers (dev, uat, live) without creating side effects if the table was somehow different on a server.



                          I hope this helps someone. Please let me know if you find anything wrong before down-voting. I'm more than happy to update the script.



                          IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C WITH (NOLOCK) WHERE C.TABLE_CATALOG = '<<DB>>' AND C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = '<<Table>>' 
                          AND C.COLUMN_NAME = '<<COLUMN>>' AND C.DATA_TYPE = 'int') -- <- Additional test to check the current datatype so this won't make unnecessary or wrong updates
                          BEGIN
                          DECLARE @pkName VARCHAR(200);
                          SELECT @pkName = pkRef.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pkRef WITH (NOLOCK)
                          WHERE pkRef.TABLE_CATALOG = '<<DB>>' AND pkRef.TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '<<Table>>'

                          IF(@pkName IS NOT NULL)
                          BEGIN
                          -- Make sure the primary key name is the one you are going to use in script beyond this point.
                          IF(@pkName != '<<PRIMARY KEY NAME>>')
                          BEGIN
                          RAISERROR ('Unexpected primary key name - The primary key found has a different name than expected. Please update the script.', 16, 1);
                          RETURN;
                          END

                          ALTER TABLE dbo.<<Table>>
                          DROP CONSTRAINT <<PRIMARY KEY NAME>>; -- Note: this is not a string or a variable (just type the PK name)
                          SELECT 'Dropped existing primary key';
                          END

                          ALTER TABLE dbo.<<Table>> ALTER COLUMN ID BIGINT
                          SELECT 'Updated column type to big int';

                          ALTER TABLE dbo.<<Table>>
                          ADD CONSTRAINT <<PRIMARY KEY NAME>> PRIMARY KEY CLUSTERED (<<COLUMN>>);
                          SELECT 'Created the primary key';
                          END
                          ELSE
                          BEGIN
                          SELECT 'No change required.';
                          END





                          share|improve this answer



























                            1












                            1








                            1







                            Below is a script I wrote to help us deploy a change to primary key column data type.



                            This script assumes there aren't any non-primary key constraints (e.g. foreign keys) depending on this column.



                            It has a few safety checks as this was designed to be deployed to different servers (dev, uat, live) without creating side effects if the table was somehow different on a server.



                            I hope this helps someone. Please let me know if you find anything wrong before down-voting. I'm more than happy to update the script.



                            IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C WITH (NOLOCK) WHERE C.TABLE_CATALOG = '<<DB>>' AND C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = '<<Table>>' 
                            AND C.COLUMN_NAME = '<<COLUMN>>' AND C.DATA_TYPE = 'int') -- <- Additional test to check the current datatype so this won't make unnecessary or wrong updates
                            BEGIN
                            DECLARE @pkName VARCHAR(200);
                            SELECT @pkName = pkRef.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pkRef WITH (NOLOCK)
                            WHERE pkRef.TABLE_CATALOG = '<<DB>>' AND pkRef.TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '<<Table>>'

                            IF(@pkName IS NOT NULL)
                            BEGIN
                            -- Make sure the primary key name is the one you are going to use in script beyond this point.
                            IF(@pkName != '<<PRIMARY KEY NAME>>')
                            BEGIN
                            RAISERROR ('Unexpected primary key name - The primary key found has a different name than expected. Please update the script.', 16, 1);
                            RETURN;
                            END

                            ALTER TABLE dbo.<<Table>>
                            DROP CONSTRAINT <<PRIMARY KEY NAME>>; -- Note: this is not a string or a variable (just type the PK name)
                            SELECT 'Dropped existing primary key';
                            END

                            ALTER TABLE dbo.<<Table>> ALTER COLUMN ID BIGINT
                            SELECT 'Updated column type to big int';

                            ALTER TABLE dbo.<<Table>>
                            ADD CONSTRAINT <<PRIMARY KEY NAME>> PRIMARY KEY CLUSTERED (<<COLUMN>>);
                            SELECT 'Created the primary key';
                            END
                            ELSE
                            BEGIN
                            SELECT 'No change required.';
                            END





                            share|improve this answer















                            Below is a script I wrote to help us deploy a change to primary key column data type.



                            This script assumes there aren't any non-primary key constraints (e.g. foreign keys) depending on this column.



                            It has a few safety checks as this was designed to be deployed to different servers (dev, uat, live) without creating side effects if the table was somehow different on a server.



                            I hope this helps someone. Please let me know if you find anything wrong before down-voting. I'm more than happy to update the script.



                            IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C WITH (NOLOCK) WHERE C.TABLE_CATALOG = '<<DB>>' AND C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = '<<Table>>' 
                            AND C.COLUMN_NAME = '<<COLUMN>>' AND C.DATA_TYPE = 'int') -- <- Additional test to check the current datatype so this won't make unnecessary or wrong updates
                            BEGIN
                            DECLARE @pkName VARCHAR(200);
                            SELECT @pkName = pkRef.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pkRef WITH (NOLOCK)
                            WHERE pkRef.TABLE_CATALOG = '<<DB>>' AND pkRef.TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '<<Table>>'

                            IF(@pkName IS NOT NULL)
                            BEGIN
                            -- Make sure the primary key name is the one you are going to use in script beyond this point.
                            IF(@pkName != '<<PRIMARY KEY NAME>>')
                            BEGIN
                            RAISERROR ('Unexpected primary key name - The primary key found has a different name than expected. Please update the script.', 16, 1);
                            RETURN;
                            END

                            ALTER TABLE dbo.<<Table>>
                            DROP CONSTRAINT <<PRIMARY KEY NAME>>; -- Note: this is not a string or a variable (just type the PK name)
                            SELECT 'Dropped existing primary key';
                            END

                            ALTER TABLE dbo.<<Table>> ALTER COLUMN ID BIGINT
                            SELECT 'Updated column type to big int';

                            ALTER TABLE dbo.<<Table>>
                            ADD CONSTRAINT <<PRIMARY KEY NAME>> PRIMARY KEY CLUSTERED (<<COLUMN>>);
                            SELECT 'Created the primary key';
                            END
                            ELSE
                            BEGIN
                            SELECT 'No change required.';
                            END






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited May 11 '18 at 7:42

























                            answered Feb 8 '18 at 13:26









                            MenolMenol

                            590928




                            590928





















                                0














                                Right in the table you want to change the PK type >> Modify. Go in the column, change the type and save. If you want to see the code for such a change, before saving, you can right-click >> "Generate Change Script ..".






                                share|improve this answer



























                                  0














                                  Right in the table you want to change the PK type >> Modify. Go in the column, change the type and save. If you want to see the code for such a change, before saving, you can right-click >> "Generate Change Script ..".






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    Right in the table you want to change the PK type >> Modify. Go in the column, change the type and save. If you want to see the code for such a change, before saving, you can right-click >> "Generate Change Script ..".






                                    share|improve this answer













                                    Right in the table you want to change the PK type >> Modify. Go in the column, change the type and save. If you want to see the code for such a change, before saving, you can right-click >> "Generate Change Script ..".







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Dec 19 '18 at 21:24









                                    Werneck OliveiraWerneck Oliveira

                                    1




                                    1



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41549549%2fsql-server-change-primary-key-data-type%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                        Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                        Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved