Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the column length of a primary key in SQL Server?

I know how to change the length of a column, but my SQL statement fails because the column I'm trying to change is a PK, so I get the following error:

Msg 5074, Level 16, State 1, Line 1
The object 'PK_TableName' is dependent on column 'PersonID'.

PersonID = PK.

I've read What is the sql to change the field length of a table column in sql server which only applies to non-PK columns.

I tried this:

ALTER TABLE table_name
ALTER COLUMN column_name <new datatype>
like image 802
LearnByReading Avatar asked May 20 '15 13:05

LearnByReading


People also ask

Can you modify primary key in SQL?

You can modify a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. You can modify the primary key of a table by changing the column order, index name, clustered option, or fill factor.

Can you alter a primary key?

To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.


2 Answers

See below sample example how to increase size of the primary column

  1. Create a sample table

    create table abc (id varchar(10) primary key)

  2. Find primary constraint in key constraints tables

    select object_name(object_id),* from sys.key_constraints where object_name(parent_object_id) = 'abc

  3. Drop constraint

    ALTER TABLE abc DROP CONSTRAINT PK__abc__3213E83F74EAC69B

    (Replace PK__abc__3213E83F74EAC69B with constraint name you receive.)

  4. Add not null

    ALTER TABLE abc alter column id varchar(20) NOT NULL;

  5. Add primary key again

    ALTER TABLE abc ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (id)

like image 197
Indra Prakash Tiwari Avatar answered Sep 28 '22 18:09

Indra Prakash Tiwari


ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>

ALTER TABLE table_name
ALTER COLUMN column_name datatype

ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)
like image 42
The Reason Avatar answered Sep 28 '22 20:09

The Reason