Published on

August 12, 2008

Renaming Database Objects in SQL Server

As a SQL Server developer, you may come across situations where you need to rename a table or a column within a table. In this article, we will explore how to rename database objects using T-SQL scripts.

Renaming a Table Column

Let’s start by looking at an example of renaming a column within a table. Suppose we have a table called “Table_First” in the AdventureWorks database, which has two columns: ID and Name.

To rename the column “Name” to “NameChange”, we can use the following T-SQL command:

USE AdventureWorks;
GO

sp_RENAME 'Table_First.Name', 'NameChange', 'COLUMN';
GO

After executing the above script, the column name will be changed from “Name” to “NameChange”. You can verify this by running the following query:

USE AdventureWorks;
GO

SELECT * FROM Table_First;

The query result will show that the column name has been successfully changed to “NameChange”.

Renaming a Table

In addition to renaming a column, you may also need to rename an entire table. To do this, we can use the same “sp_RENAME” command, but with a different syntax.

Let’s say we want to rename the table “Table_First” to “Table_Last”. We can achieve this by executing the following T-SQL script:

sp_RENAME 'Table_First', 'Table_Last';
GO

After running the script, the table name “Table_First” will be changed to “Table_Last”. The old table name will no longer be available in the database.

To verify that the new renamed table exists in the database, you can run the following query:

USE AdventureWorks;
GO

SELECT * FROM Table_Last;

The query result will show the same data that was previously available in the “Table_First” table, now accessible through the new table name “Table_Last”.

Renaming database objects can be a useful technique when you need to make changes to your database structure without affecting the existing data or breaking any dependencies. It is important to note that renaming objects should be done with caution and proper testing to ensure the integrity of your database.

That’s it for this article! We have explored how to rename database objects in SQL Server using T-SQL scripts. I hope you found this information helpful in your SQL Server development journey.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.