Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 Script to Drop PK Constraint that has a System Generated Name

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
like image 800
wired_in Avatar asked Oct 06 '22 17:10

wired_in


1 Answers

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';
like image 131
Joe Stefanelli Avatar answered Oct 22 '22 08:10

Joe Stefanelli