SQL Server 2008 Script to Drop PK Constraint that

2020-07-15 15:40发布

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.

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."

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!

UPDATE:

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

1条回答
一纸荒年 Trace。
2楼-- · 2020-07-15 15:50

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';
查看更多
登录 后发表回答