Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Rename column SQL Server

I'm utilizing SQL Server and Navicat. I need to rename a section in a table utilizing SQL.
ALTER TABLE table_name RENAME COLUMN old_name to new_name;

This statement doesn't work.
by

2 Answers

espadacoder11
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.
RoliMishra
If it is a deployment script then you can add adding some additional security to it by using this code

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';

Login / Signup to Answer the Question.