sql-server-2012primary-key

SQL Server Change Primary Key Data Type


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.


Solution

  • 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

    Code:

    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 a different name
    2. Insert data from old table to new table
    3. Finally at the time of switch, rename the table to old table name

    This way, you might have less downtime