I would like to write a single SQL command to drop multiple columns from a single table in one ALTER TABLE
statement.
From MSDN\'s ALTER TABLE documenta
The Syntax as specified by Microsoft for the dropping a column part of an ALTER statement is this
DROP
{
[ CONSTRAINT ]
{
constraint_name
[ WITH
( [ ,...n ] )
]
} [ ,...n ]
| COLUMN
{
column_name
} [ ,...n ]
} [ ,...n ]
Notice that the [,...n] appears after both the column name and at the end of the whole drop clause. What this means is that there are two ways to delete multiple columns. You can either do this:
ALTER TABLE TableName
DROP COLUMN Column1, Column2, Column3
or this
ALTER TABLE TableName
DROP
COLUMN Column1,
COLUMN Column2,
COLUMN Column3
This second syntax is useful if you want to combine the drop of a column with dropping a constraint:
ALTER TBALE TableName
DROP
CONSTRAINT DF_TableName_Column1,
COLUMN Column1;
When dropping columns SQL Sever does not reclaim the space taken up by the columns dropped. For data types that are stored inline in the rows (int for example) it may even take up space on the new rows added after the alter statement. To get around this you need to create a clustered index on the table or rebuild the clustered index if it already has one. Rebuilding the index can be done with a REBUILD command after modifying the table. But be warned this can be slow on very big tables. For example:
ALTER TABLE Test
REBUILD;