Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop primary key using script in SQL Server database [duplicate]

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

like image 810
muthukumar Avatar asked Dec 19 '12 08:12

muthukumar


People also ask

How can you delete duplicate records in a table with no primary key?

DELETE Duplicate Records Using ROWCOUNT So to delete the duplicate record with SQL Server we can use the SET ROWCOUNT command to limit the number of rows affected by a query. By setting it to 1 we can just delete one of these rows in the table.

Can I drop the primary key in SQL Server?

You can delete (drop) a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. When the primary key is deleted, the corresponding index is deleted. This may be the clustered index of the table, causing the table to become a heap.

Can a primary key have duplicate values SQL Server?

A primary key is a column of table which uniquely identifies each tuple (row) in that table. Primary key enforces integrity constraints to the table. Only one primary key is allowed to use in a table. The primary key does not accept the any duplicate and NULL values.


1 Answers

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

like image 70
Bridge Avatar answered Oct 09 '22 02:10

Bridge