?
Solved

Delete Primary key constraint without knowing the name. SQL 2008

Posted on 2009-04-16
2
Medium Priority
?
276 Views
Last Modified: 2012-05-06
Using a single SQL 2008 query, I'm trying to delete a primary key constraint from a table.  but the catch is I don't know the name of the primary key.  In this case, each table has a random number attached to the end of the pk....like, pk_WorkFlowDocumentsTable_234123.  So I just need a query that will delete the pk constraint, no matter what the name is.

I'm very close...

This query returns the name of the key i need to delete:

select a.CONSTRAINT_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE a inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME where a.table_name = 'test2_WorkFlowDocumentsTable' and constraint_type = 'Primary key'

This query will delete the pk constraint:

ALTER TABLE test2_WorkFlowDocumentsTable DROP CONSTRAINT [name]

But I just can't figure out how to put the two together?
0
Comment
Question by:OFGemini
2 Comments
 
LVL 60

Accepted Solution

by:
chapmandew earned 2000 total points
ID: 24160618
declare @constraint nvarchar(1000), @sql nvarchar(2000)

select @constraint = a.CONSTRAINT_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE a inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME where a.table_name = 'test2_WorkFlowDocumentsTable' and constraint_type = 'Primary key'

set @sql = 'ALTER TABLE test2_WorkFlowDocumentsTable DROP CONSTRAINT [' + @constraint + ']'

exec sp_executesql @sql

0
 

Author Closing Comment

by:OFGemini
ID: 31571120
Flawless
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Microsoft provides a rich set of technologies for High Availability and Disaster Recovery solutions.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

588 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question