[英]How is it possible to drop primary key in one step?
I would like to drop the primary key for a table, but keep the column (I know the name of the column, if it helps).我想删除表的主键,但保留列(如果有帮助,我知道列的名称)。
I use this script to get the name of the primary key:我使用这个脚本来获取主键的名称:
-- Return the name of primary key.
SELECT key_name
FROM sys.key_constraints
WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = 'my_table';
Then I remove the key like this:然后我像这样删除密钥:
ALTER TABLE Production.TransactionHistoryArchive
DROP CONSTRAINT key_name ;
It works, but I have to run this script in one go.它可以工作,但我必须在一个 go 中运行这个脚本。 How it is possible to combine drop constraint with a select query?如何将删除约束与 select 查询结合起来?
Will throw this out there in case it's useful to you.如果它对您有用,将把它扔在那里。 Using Dynamic SQL you can build something that you could easily create a procedure for.使用动态 SQL,您可以构建可以轻松创建过程的东西。
declare @Schema nvarchar(20)=N'Production',
@Table nvarchar(50)=N'TransactionHistoryArchive',
@sql nvarchar(100)=''
select @sql='ALTER TABLE '
+ QuoteName(@Schema) + '.'
+ QuoteName(@Table)
+ ' DROP CONSTRAINT '
+ QuoteName(name)
from sys.key_constraints
where type = 'PK' and Object_Name(parent_object_id) = @Table and [schema_id]=Schema_Id(@Schema)
print @sql
exec sp_executesql @sql
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.