SQL Server 2008 Script to Drop PK Constraint that has a System Generated Name(用于删除具有系统生成名称的 PK 约束的 SQL Server 2008 脚本)
问题描述
我正在尝试向 SQL Server 2008 中的现有表添加聚集索引,它需要是一个自动化脚本,因为该表存在于跨多个服务器的多个数据库中.
I am trying to add a clustered index to an existing table in SQL Server 2008, and it needs to be an automated script, because this table exists on several databases across several servers.
为了添加聚集索引,我需要删除表上的 PK 约束,然后将其重新添加为非聚集索引.问题是 PK 约束的名称是自动生成的,并且在末尾附加了一个 guid,因此类似于PK_[Table]_D9F9203400".
In order to add a clustered index I need to remove the PK constraint on the table, and then re-add it as unclustered. The problem is the name of the PK constraint is auto-generated, and there is a guid appended to the end, so it's like "PK_[Table]_D9F9203400."
所有数据库的名称都不同,我不知道如何编写一个自动化脚本,在我不知道约束名称的表上删除 PK 约束.任何帮助表示赞赏!
The name is different across all databases, and I'm not sure how to write an automated script that drops a PK constraint on a table in which I don't know the name of the constraint. Any help is appreciated!
更新:
下面的答案是我用过的.完整脚本:
Answer below is what I used. Full script:
Declare @Val varchar(100)
Declare @Cmd varchar(1000)
Set @Val = (
select name
from sysobjects
where xtype = 'PK'
and parent_obj = (object_id('[Schema].[Table]'))
)
Set @Cmd = 'ALTER TABLE [Table] DROP CONSTRAINT ' + @Val
Exec (@Cmd)
GO
ALTER TABLE [Table] ADD CONSTRAINT PK_Table
PRIMARY KEY NONCLUSTERED (TableId)
GO
CREATE UNIQUE CLUSTERED INDEX IX_Table_Column
ON Table (Column)
GO
推荐答案
你可以查一下约束的名字,写一点动态 SQL 来处理 drop.
You can look up the name of the constraint and write a bit of dynamic SQL to handle the drop.
SELECT name
FROM sys.key_constraints
WHERE parent_object_id = object_id('YourSchemaName.YourTableName')
AND type = 'PK';
这篇关于用于删除具有系统生成名称的 PK 约束的 SQL Server 2008 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于删除具有系统生成名称的 PK 约束的 SQL Serv


基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01