Use SQL scripts in the SQL Server database to delete columns in a specified table

Source: Internet
Author: User
It is very easy to use the database management tool to directly visualize a column in the SQL Server database, but what if you want to use an SQL script? You may say it's very simple to use it directly.
Alter table [name of the table where the field to be deleted is located]
Drop column [fields to be deleted];
Go
Isn't it OK?

However, if there is a constraint on this field, a prompt similar to the following will pop up:
Message 5074, level 16, state 1, 1st rows
The object 'df _ *** _ 682a18f4 'depends on the column '***'.
Message 4922, level 16, status 9, 1st rows
Alter table drop column *** failed because one or more objects access this column.

How can this problem be solved?
First, you can find the constraint for this field and then delete it.
-- Query all the field constraints of a table
Sp_helpconstraint [name of the table where the field to be deleted is located]

-- Query the default constraints of a field in a table
Select name as constraint name
From sysobjects
Where ID in (select cdefault
From syscolumns
Where name in ([field to be deleted])
And Id = (select ID
From sysobjects

Where name = [name of the table where the field to be deleted is located])

After the constraints are found, the constraints will be deleted.

-- Delete constraints on fields
Alter table [name of the table where the field to be deleted is located]
Drop constraint name;

Go

Now let's Delete the field you want to delete.
Alter table [name of the table where the field to be deleted is located]
Drop column [fields to be deleted];
Go

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.