Drop primary key using script in SQL Server database

Sql ServerSql Server-2008Sql Server-2005

Sql Server Problem Overview


I need to drop the primary key of a table Student in a SQL Server database.

I have edited in the table and the script I got is

ALTER TABLE dbo.Student
	DROP CONSTRAINT PK__Student__9CC368536561EF8B

But when I run this script in SQL Server query browser to drop the primary key

It shows the message

> Msg 3728, Level 16, State 1, Line 1
> 'PK__Student__9CC368536561EF8B' is not a constraint.
> Msg 3727, Level 16, State 0, Line 1

To my concern I think PK__Student__9CC368536561EF8B this will be generated randomly please help me to drop the primary key constraint using script.

Thanks in advance

Sql Server Solutions


Solution 1 - Sql Server

You can look up the constraint name in the sys.key_constraints table:

SELECT name
FROM   sys.key_constraints
WHERE  [type] = 'PK'
       AND [parent_object_id] = Object_id('dbo.Student');

If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);

SELECT @table = N'dbo.Student';

SELECT @sql = 'ALTER TABLE ' + @table 
    + ' DROP CONSTRAINT ' + name + ';'
    FROM sys.key_constraints
    WHERE [type] = 'PK'
    AND [parent_object_id] = OBJECT_ID(@table);

EXEC sp_executeSQL @sql;

This code is from Aaron Bertrand (source).

Solution 2 - Sql Server

simply click

>'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

Solution 3 - Sql Server

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmuthukumarView Question on Stackoverflow
Solution 1 - Sql ServerBridgeView Answer on Stackoverflow
Solution 2 - Sql ServerHarsh BajajView Answer on Stackoverflow
Solution 3 - Sql ServermuthukumarView Answer on Stackoverflow