SQL Server: drop table primary key, without knowing its name

后端 未结 2 1558
粉色の甜心
粉色の甜心 2021-01-31 17:34

HI,

Using: SQL Server Database: Northwind

I\'d like to drop a table primary key, without knowing the PK constraint name..

eg, using the Categories table

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 18:00

    Adding to Stuart Ainsworth answer, I do not know if PK name has to be unique across different schemas (if so, that answer is ok). Anyway I would choose different sub query for PK name, allowing explicitly to define schema:

    declare @PrimaryKeyName sysname = 
        (select CONSTRAINT_NAME 
         from INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
         where CONSTRAINT_TYPE = 'PRIMARY KEY' and TABLE_SCHEMA='dbo' and TABLE_NAME = 'PKTest'
        )
    
    IF @PrimaryKeyName is not null
    begin
        declare @SQL_PK NVARCHAR(MAX) = 'alter table dbo.PKTest drop constraint ' + @PrimaryKeyName
        print (@SQL_PK)
        EXEC sp_executesql @SQL_PK;
    end
    

提交回复
热议问题