Use sql script to delete the column of the specified table in the SQL Server database

To delete a column in a SQL Server database, it is very simple to use database management tools to directly visualize the operation, but what if you use SQL scripts? Maybe you can say that it is very simple, just use
ALTER TABLE [the table name where the field to be deleted is located]
DROP COLUMN [the field to be deleted];
GO
Is this OK?


But if there is a constraint on this field, a prompt similar to the following will pop up:
Message 5074, Level 16, State 1, Line 1
Object 'DF__***__***__682A18F4' depends on column '*** '.
Msg 4922, Level 16, State 9, Line 1 ALTER TABLE DROP COLUMN *** failed
because one or more objects accessed this column.


How to solve this problem?
First, you can find the constraint of the field, and then delete it
-- query all field constraints of a table
sp_helpconstraint [the table name where the field to be deleted is located]


-- query the default constraint 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 delete]) 
and id=(select id 
from sysobjects 

where name = [table name of the field to delete]))


After the constraint is queried, it is necessary to delete the constraint


--Remove constraints on fields
ALTER TABLE [table name where the field to be deleted is located]
DROP constraint name;

GO


Now there is no problem in deleting the field you want to delete, hehe
ALTER TABLE [the table name where the field to be deleted is located]
DROP COLUMN [the field to be deleted];
GO

Reprinted in: https://www.cnblogs.com/kevinGao/archive/2012/07/16/2605588.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324090702&siteId=291194637