如何更改 SQL Server 中主键的列长度? [英] How to change the column length of a primary key in SQL Server?

查看:96
本文介绍了如何更改 SQL Server 中主键的列长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何更改列的长度,但是我的 SQL 语句失败了,因为我要更改的列是 PK,因此出现以下错误:

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:

消息 5074,级别 16,状态 1,第 1 行
对象PK_TableName"依赖于PersonID"列.

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

人员 ID = PK.

PersonID = PK.

我已阅读 sql server 中改变表列字段长度的sql是什么 只适用于非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.

我试过这个:

ALTER TABLE table_name
ALTER COLUMN column_name <new datatype>

推荐答案

查看下面的示例示例如何增加主列的大小

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

  1. 创建示例表

  1. Create a sample table

创建表 abc (id varchar(10) 主键)

在关键约束表中查找主要约束

Find primary constraint in key constraints tables

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

放置约束

ALTER TABLE abc删除约束 PK__abc__3213E83F74EAC69B

(将 PK__abc__3213E83F74EAC69B 替换为您收到的约束名称.)

添加非空

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

再次添加主键

ALTER TABLE abc添加约束 MyPrimaryKey PRIMARY KEY (id)

这篇关于如何更改 SQL Server 中主键的列长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆