How to remove a column from an existing table?

前端 未结 11 1002
旧巷少年郎
旧巷少年郎 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:34

    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}
    
    0 讨论(0)
  • 2020-12-12 11:41

    Generic:

    ALTER TABLE table_name DROP COLUMN column_name;
    

    In your case:

    ALTER TABLE MEN DROP COLUMN Lname;
    
    0 讨论(0)
  • 2020-12-12 11:42

    Syntax:

    ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
    

    For Example:

    alter table Employee drop column address;
    
    0 讨论(0)
  • 2020-12-12 11:43

    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

    0 讨论(0)
  • 2020-12-12 11:49

    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

    0 讨论(0)
  • 2020-12-12 11:52
    ALTER TABLE MEN DROP COLUMN Lname
    
    0 讨论(0)
提交回复
热议问题