Transfer primary key using script to SQL Server database

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

I edited in the table and the script got

 ALTER TABLE dbo.Student DROP CONSTRAINT PK__Student__9CC368536561EF8B 

But when I ran this script in SQL Server Query Browser to remove the primary key

Message is displayed

Msg 3728, Level 16, State 1, Line 1
"PK__Student__9CC368536561EF8B" is not a limitation.
Msg 3727, Level 16, State 0, Line 1

To my concern, I think that PK__Student__9CC368536561EF8B will be randomly generated, please help me reset the primary key constraint using a script .

Thank you in advance

+26
sql-server sql-server-2008 sql-server-2005
Dec 19
source share
3 answers

You can find the name of the constraint 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 are not interested in the name, but just want to remove 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 belongs to Aaron Bertrand ( source ).

+56
Dec 19
source share

just click

Database> tables> your table name> keys> copy restrictions like "PK__TableName__30242045"

and execute the following query:

 Query:alter Table 'TableName' drop constraint PK__TableName__30242045 
+13
Jun 04 '15 at 9:23
source share

The answer I received is that the variables and subqueries will not work, and we have a custom 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) 
+3
Dec 19 '12 at 10:05
source share



All Articles