SQL Server deletes and recreates a primary key

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.