Not satisfied by the Answer? Still have doubts?
Ask Question

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.
sql-server sql
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.

  • Be descriptive with your answer, and try to avoid copy-pasting external links, instead guide the user who has asked the question, where can they find the detailed answer.
  • You cannot share any URL in answer.
  • To make a text bold, surround the text with single asterisk, for example *bold text*
  • To format a text like code, surround the text within double asterisk, for example **code**
  • To add a multiline piece of code, surround the whole code within triple asterisk, for example *** multiline code ***
  • Please verify before submitting the answer.