In our applications, we sometimes need to delete the primary keys of some tables first, and then do some exception operations, and then re-create the primary keys, but we do not want to use SQL server manager studio or, when using code in a program to perform these operations, you can write an SQL statement or stored procedure, allowing you to click a button to implement the function. Let's take a look at how to delete the primary key.
Delete primary key:
Declare @ Pk varChar (100 );
Select @ Pk = Name from sysobjects where Parent_Obj = OBJECT_ID ('tablename') and xtype = 'pk ';
If @ Pk is not null
Exec ('alter table tableName drop' + @ Pk)
Primary key reconstruction:
ALTER Table tableName add constraint pkName primary key (pkfield)
In this way, we can use the. net code to dynamically pass the table name and primary key name to delete the primary key and recreate the primary key.