How to remove a column from an existing table?

前端 未结 11 1005
旧巷少年郎
旧巷少年郎 2020-12-12 11:22

How to remove a column from an existing table?

I have a table MEN with Fname and Lname

I need to remove the Lnam

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 11:55

    The simple answer to this is to use this:

    ALTER TABLE MEN DROP COLUMN Lname;
    

    More than one column can be specified like this:

    ALTER TABLE MEN DROP COLUMN Lname, secondcol, thirdcol;
    

    From SQL Server 2016 it is also possible to only drop the column only if it exists. This stops you getting an error when the column doesn't exist which is something you probably don't care about.

    ALTER TABLE MEN DROP COLUMN IF EXISTS Lname;
    

    There are some prerequisites to dropping columns. The columns dropped can't be:

    • Used by an Index
    • Used by CHECK, FOREIGN KEY, UNIQUE, or PRIMARY KEY constraints
    • Associated with a DEFAULT
    • Bound to a rule

    If any of the above are true you need to drop those associations first.

    Also, it should be noted, that dropping a column does not reclaim the space from the hard disk until the table's clustered index is rebuilt. As such it is often a good idea to follow the above with a table rebuild command like this:

    ALTER TABLE MEN REBUILD;
    

    Finally as some have said this can be slow and will probably lock the table for the duration. It is possible to create a new table with the desired structure and then rename like this:

    SELECT 
       Fname 
       -- Note LName the column not wanted is not selected
    INTO 
       new_MEN
    FROM
       MEN;
    
    EXEC sp_rename 'MEN', 'old_MEN';
    EXEC sp_rename 'new_MEN', 'MEN';
    
    DROP TABLE old_MEN;
    

    But be warned there is a window for data loss of inserted rows here between the first select and the last rename command.

提交回复
热议问题