How do I rename a column in a database table using SQL?

前端 未结 11 1672
时光说笑
时光说笑 2020-12-12 18:25

If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?

This

相关标签:
11条回答
  • 2020-12-12 19:01

    Specifically for SQL Server, use sp_rename

    USE AdventureWorks;
    GO
    EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
    GO
    
    0 讨论(0)
  • 2020-12-12 19:01

    You can use the following command to rename the column of any table in SQL Server:

    exec sp_rename 'TableName.OldColumnName', 'New colunmName'
    
    0 讨论(0)
  • 2020-12-12 19:03

    Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.

    ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;
    UPDATE MyTable SET MyNewColumn = MyOldColumn;
    -- add all necessary triggers and constraints to the new column...
    -- update all foreign key usages to point to the new column...
    ALTER TABLE MyTable DROP COLUMN MyOldColumn;
    

    For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.

    However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.

    0 讨论(0)
  • 2020-12-12 19:06

    I think this is the easiest way to change column name.

    SP_RENAME 'TABLE_NAME.OLD_COLUMN_NAME','NEW_COLUMN_NAME'
    
    0 讨论(0)
  • 2020-12-12 19:13

    In sql server you can use

    exec sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'
    

    or

    sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'
    
    0 讨论(0)
  • 2020-12-12 19:15

    Alternatively to SQL, you can do this in Microsoft SQL Server Management Studio, from the table Design Panel.

    First Way

    Slow double-click on the column. The column name will become an editable text box.

    Second Way

    SqlManagement Studio>>DataBases>>tables>>specificTable>>Column Folder>>Right Click on column>>Reman

    Third Way

    Table>>RightClick>>Design

    0 讨论(0)
提交回复
热议问题