簡體   English   中英

如何一步刪除主鍵?

[英]How is it possible to drop primary key in one step?

我想刪除表的主鍵,但保留列(如果有幫助,我知道列的名稱)。

我使用這個腳本來獲取主鍵的名稱:

-- Return the name of primary key.  
SELECT key_name  
FROM sys.key_constraints  
WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = 'my_table'; 

然后我像這樣刪除密鑰:

ALTER TABLE Production.TransactionHistoryArchive  
DROP CONSTRAINT key_name ;   

它可以工作,但我必須在一個 go 中運行這個腳本。 如何將刪除約束與 select 查詢結合起來?

如果它對您有用,將把它扔在那里。 使用動態 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM