I would typically use Management Studio to rename columns or tables in SQL Server. Afterall, it is an easy thing to do to open up the GUI make your changes and then save them back to the SQL Server.
Have you ever been in a situation where you wanted to make a number of such changes and then later on you needed to repeat those changes on another system?
I was in such a situation recently where due to some application changes, many columns had to be renamed, the application tested and then I had to repeat the procedure on production.
I did not want to have to open up every table in Management Studio and click the save button each time all over again!
I needed something that I could execute quickly, so I prepared a file of T-SQL commands to make my changes in one swift stroke. I achieved it all using sp_rename
T-SQL example – renaming columns and tables
So here we have an example for renaming a column:
[sourcecode language=’sql’]
EXEC sp_rename ‘Table.[OldColumnName]’, ‘[NewColumnName]’, ‘[COLUMN]’;
[/sourcecode]
If we wanted to rename a table then we can use:
[sourcecode language=’sql’]
EXEC sp_rename ‘[OldTableName]’, ‘[NewTableName]’;
[/sourcecode]
Note that the square brackets are not mandatory but are necessary when you have silly database designers who have put such things as hyphens or spaces in their field names. Makes me cringe just thinking about it! 😐
Permissions needed for sp_rename
You need ALTER permission if you want to rename tables or columns.
One final note
You can use sp_rename for renaming other objects besides tables. It can also be used for renaming indexes, constraints, types databases and statistics. More more information on this useful little proc, visit this link
Leave a Reply