How to remove a column from an existing table?
Solution 1:
ALTER TABLE MEN DROP COLUMN Lname
Solution 2:
Generic:
ALTER TABLE table_name DROP COLUMN column_name;
In your case:
ALTER TABLE MEN DROP COLUMN Lname;
Solution 3:
Your example is simple and doesn’t require any additional table changes but generally speaking this is not so trivial.
If this column is referenced by other tables then you need to figure out what to do with other tables/columns. One option is to remove foreign keys and keep referenced data in other tables.
Another option is to find all referencing columns and remove them as well if they are not needed any longer.
In such cases the real challenge is finding all foreign keys. You can do this by querying system tables or using third party tools such as ApexSQL Search (free) or Red Gate Dependency tracker (premium but more features). There a whole thread on foreign keys here
Solution 4:
This is the correct answer:
ALTER TABLE MEN DROP COLUMN Lname
But... if a CONSTRAINT
exists on the COLUMN
, then you must DROP
the CONSTRAINT
first, then you will be able to DROP
the COLUMN
. In order to drop a CONSTRAINT
, run:
ALTER TABLE MEN DROP CONSTRAINT {constraint_name_on_column_Lname}
Solution 5:
In SQL Server 2016 you can use new DIE statements.
ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name
The above query is re-runnable it drops
the column only if it exists
in the table else it will not throw error.
Instead of using big IF
wrappers to check the existence of column
before dropping it you can just run the above DDL
statement