[sql] Rename column SQL Server 2008

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;

This statement doesn't work.

This question is related to sql sql-server sql-server-2008 alter-table

The answer is


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.


Or you could just slow-click twice on the column in SQL Management Studio and rename it through the UI...


Run Query:

    SP_RENAME '[TableName].[ColumnName]','NewNameForColumn'

Improved version of @Taher

DECLARE @SchemaName AS VARCHAR(128)
DECLARE @TableName AS VARCHAR(128)
DECLARE @OldColumnName AS VARCHAR(128)
DECLARE @NewColumnName AS VARCHAR(128)
DECLARE @ParamValue AS VARCHAR(1000)

SET @SchemaName = 'dbo'
SET @TableName = 'tableName'
SET @OldColumnName = 'OldColumnName'
SET @NewColumnName = 'NewColumnName'
SET @ParamValue = @SchemaName + '.' + @TableName + '.' + @OldColumnName

IF EXISTS
(
    SELECT 1 FROM sys.columns WHERE name = @OldColumnName AND OBJECT_NAME(object_id) = @TableName
)
AND NOT EXISTS
(
    SELECT 1 FROM sys.columns WHERE name = @NewColumnName AND OBJECT_NAME(object_id) = @TableName
)
BEGIN
    EXEC sp_rename @ParamValue, @NewColumnName, 'COLUMN';
END

Alternatively to SQL, you can do this in Microsoft SQL Server Management Studio. Here are a few quick ways using the GUI:

First Way

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


Second Way

Right click on column and choose Rename from the context menu.

For example:

To Rename column name


Third Way

This way is preferable for when you need to rename multiple columns in one go.

  1. Right-click on the table that contains the column that needs renaming.
  2. Click Design.
  3. In the table design panel, click and edit the textbox of the column name you want to alter.

For example: MSSMS Table Design Example

NOTE: I know OP specifically asked for SQL solution, thought this might help others :)


Sql Server management studio has some system defined Stored Procedures(SP)
One of which is used to rename a column.The SP is sp_rename

Syntax: sp_rename '[table_name].old_column_name', 'new_column_name'
For further help refer this article: sp_rename by Microsoft Docs

Note: On execution of this SP the sql server will give you a caution message as 'Caution: Changing any part of an object name could break scripts and stored procedures'.This is critical only if you have written your own sp which involves the column in the table you are about to change.


Since I often come here and then wondering how to use the brackets, this answer might be useful for those like me.

EXEC sp_rename '[DB].[dbo].[Tablename].OldColumnName', 'NewColumnName', 'COLUMN'; 
  • The OldColumnName must not be in []. It will not work.
  • Don't put NewColumnName into [], it will result into [[NewColumnName]].

You can use sp_rename to rename a column.

USE YourDatabase;  
GO  
EXEC sp_rename 'TableName.OldColumnName', 'NewColumnName', 'COLUMN';  
GO  

The first parameter is the object to be modified, the second parameter is the new name that will be given to the object, and the third parameter COLUMN informs the server that the rename is for the column, and can also be used to rename tables, index and alias data type.


Try:

EXEC sp_rename 'TableName.OldName', 'NewName', 'COLUMN'

In my case, I was using MySQL WorkBench and

ALTER TABLE table_name RENAME COLUMN old_name new_name varchar(50) not null; 
// without TO and specify data type of that column 

was enough to change the column name!


You should also specify the schema of the table or you might get this error:

Msg 15248, Level 11, State 1, Procedure sp_rename, Line 238 Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.

If it is a deployment script I would also recommend adding some additional security to it.

IF EXISTS (
        SELECT 1
        FROM sys.columns
        WHERE
            name = 'OldColumnName' AND
            object_name(object_id) = 'TableName'
    ) AND
    NOT EXISTS (
        SELECT 1
        FROM sys.columns
        WHERE
            name = 'NewColumnName' AND
            object_name(object_id) = 'TableName'
    )
    EXEC sp_RENAME 'SchemaName.TableName.OldColumnName', 'NewColumnName', 'COLUMN';

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to alter-table

How to add a boolean datatype column to an existing table in sql? how to modify the size of a column MySQL: ALTER TABLE if column not exists Hive Alter table change Column Name Alter table to modify default value of column Rename column SQL Server 2008 How to delete a column from a table in MySQL Altering column size in SQL Server ALTER TABLE on dependent column ALTER TABLE to add a composite primary key