Solved

How to delete a primary key in a table in SQL Server?

Posted on 2008-10-21
2
1,253 Views
Last Modified: 2012-05-05
I have a table: Company and I want to delete its primary ID, but below statement is not working:
#1
ALTER TABLE Company DROP CONSTRAINT pk_Company

When I checked the table properties in SQL Server and use below statement:
#2
ALTER TABLE Company DROP CONSTRAINT pk_Company__725BF7F6
then it will work.

My question is: how to write a script to delete the primary key of a table, just as simple as #1? Since if I want to write a script to be deployed to production server to delete a primary key, I couldn't know the exact name: pk_Company__725BF7F6 before viewing production.

I hope my question is clear and thanks for any help.
0
Comment
Question by:heyday2004
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 11

Expert Comment

by:Muhammad Kashif
ID: 22765639
You can get the name of primary key constraint

SELECT Constraint_Name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = 'TableName'

0
 
LVL 11

Accepted Solution

by:
Louis01 earned 500 total points
ID: 22765673

DECLARE @table nvarchar(255);
DECLARE @sql nvarchar(1024);
 
SET @table = 'Company';
 
SET @sql = (select 'ALTER TABLE [' + @table + '] DROP CONSTRAINT [' + [name] + ']'
			  from sys.objects 
			 where parent_object_id in (select object_id 
										  from sys.objects 
										 where [name] = @table)
			   and type='PK');
 
EXEC sp_executesql @sql;

Open in new window

0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

732 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