Monday, September 30, 2019

How to Rename a Column Name or Table Name in SQL

The script for renaming any column :
sp_RENAME 'TableName.[OldColumnName]' '[NewColumnName]''COLUMN'
 The script for renaming any object (table, sp etc) :
sp_RENAME '[OldTableName]' '[NewTableName]'
This article demonstrates two examples of renaming database object.
  1. Renaming database table column to new name.
  2. Renaming database table to new name.
In both the cases we will first see existing table. Rename the object. Test object again with new name.
1. Renaming database table column to new name.
Example uses AdventureWorks database. A small table with name “Table_First” is created. Table has two fields ID and Name.
SQL SERVER - How to Rename a Column Name or Table Name spRename1
Solarwinds
Now, to change the Column Name from “Name” to “NameChange” we can use command:
USE AdventureWorks
GO
sp_RENAME 'Table_First.Name''NameChange'COLUMN'GO
Following Fig. show use of SP_RENAME Command
SQL SERVER - How to Rename a Column Name or Table Name spRename2
You can see the column name “Name” is now changed to “NameChange“.
USE AdventureWorks
GO
SELECT *FROM Table_First
GO
Following fig. verify that the column name has been changed.
SQL SERVER - How to Rename a Column Name or Table Name spRename3
2.Renaming database table to new name.
We can change the table name too with the same command.
sp_RENAME 'Table_First''Table_Last'GO
Following fig. Shows how we can change Table Name.
SQL SERVER - How to Rename a Column Name or Table Name spRename4
Now, the table name “Table_First” is renamed as “Table_Last”.
“Table_First” will no longer be available in database. We can verify this by running script:
USE AdventureWorks
GO
SELECT *FROM Table_First
GO
The Messages shows an error “Invalid object name ‘Table_First’.”
To check that the new renamed table exist in database run script:
USE AdventureWorks
GO
SELECT *FROM Table_Last
GO
SQL SERVER - How to Rename a Column Name or Table Name spRename6
You can see the same data now available in new table named “Table_Last”