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

☆樱花仙子☆ 提交于 2021-02-08 12:19:35

问题


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>

回答1:


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)




回答2:


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>)



回答3:


SQLServer 2008 did not allow me to change a primary key with data so I deactivated all the constraints, performed the command and activated all the constraints again. The commands are:

EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"

-- commands here

EXEC sp_MSforeachtable @command1="ALTER TABLE ? CHECK CONSTRAINT ALL"


来源:https://stackoverflow.com/questions/30350822/how-to-change-the-column-length-of-a-primary-key-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!