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
ALTER TABLE [table name where the field to be deleted is located]
DROP constraint name;
ALTER TABLE [the table name where the field to be deleted is located]
DROP COLUMN [the field to be deleted];
GO
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
ALTER TABLE [table name where the field to be deleted is located]
DROP constraint name;
GO
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