In a previous post, I showed you how to rename a database in Microsoft SQL. If you haven’t already been hit with a request to change the name of a table or column by now… it’s coming. In order to prepare you, I’m not giving you the master sword. It’s almost as helpful, right?
To rename a table using code, execute the sp_rename stored procedure using the following formula:
EXEC sp_rename ExistingTableName, TableNewName;
Here is an example:
EXEC sp_rename 'baddies', 'Enemies'; GO
In this case, the interpreter would look for a table named baddies in the current or selected database. If it finds it, it would rename it Enemies. If the table doesn’t exist, you would receive an error.
Msg 15225, Level 11, State 1, Procedure sp_rename, Line 338
No item by the name of ‘baddies’ could be found in the current database ‘databaseName’, given that @itemtype was input as ‘(null)’.
To rename a column, first open an empty query window. In a query window, execute sp_rename using the following formula:
EXEC sp_rename 'TableName.ColumnName', 'NewColumnName', 'COLUMN'
The TableName is the name of the table that the column belongs to. The ColumnName is the current name of the column. The NewColumnName is the desired name you want to give to the column.
Here is an example:
EXEC sp_rename 'baddies.FullName', 'Name', 'COLUMN' GO
When this code is executed, the interpreter will look for a column named FullName in the baddies table of the current or selected database. If it finds that column in the table, then it renames it name. Again, if the table or column doesn’t exist, you’ll get an error message.
Msg 15248, Level 11, State 1, Procedure sp_rename, Line 215
Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.
Pretty easy to use, right? If you have any questions, please, let me know! I’m here to help you learn as much as you want in Microsoft SQL Server!