Rename column SQL Server 2008

前端 未结 12 2116
名媛妹妹
名媛妹妹 2020-11-27 08:52

I am using SQL Server 2008 and Navicat. I need to rename a column in a table using SQL.

ALTER TABLE table_name RENAME COLUMN old_name to new_name;

12条回答
  •  难免孤独
    2020-11-27 09:43

    It would be a good suggestion to use an already built-in function but another way around is to:

    1. Create a new column with same data type and NEW NAME.
    2. Run an UPDATE/INSERT statement to copy all the data into new column.
    3. Drop the old column.

    The benefit behind using the sp_rename is that it takes care of all the relations associated with it.

    From the documentation:

    sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically renamed by sp_rename. sp_rename can be used to rename primary and secondary XML indexes.

提交回复
热议问题