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

后端 未结 2 1555
粉色の甜心
粉色の甜心 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

    You'll have to use dynamic SQL for that, since ALTER TABLE does not accept variables or subqueries.

    CREATE TABLE PKTest ( ID INT PRIMARY KEY ) ;
    
    DECLARE @SQL VARCHAR(4000)
    SET @SQL = 'ALTER TABLE PKTEST DROP CONSTRAINT |ConstraintName| '
    
    SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                                   FROM     sysobjects
                                                   WHERE    xtype = 'PK'
                                                            AND parent_obj = OBJECT_ID('PKTest')
                                                 ))
    
    EXEC (@SQL)
    
    DROP TABLE PKTest
    

提交回复
热议问题