Renaming a table or view column is not something a SQL developer needs to do every day. However, when the time comes, how can it be done easily and effortlessly?
Just renaming a column is not difficult. To rename the column TerritoryID in the Sales.SalesTerritory table into TerID, execute the following statement:
EXECUTE sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
The problem is that you will get the following warning:
Caution: Changing any part of an object name could break scripts and stored procedures.
In addition, maybe even this:
Object ‘Sales.SalesTerritory.TerritoryID’ cannot be renamed because the object participates in enforced dependencies.
What are these scripts that will be broken?
For example, let’s say there is a Sales.vTer stored procedure that references the TerritoryID column in the Sales.SalesTerritory table. The sp_rename procedure will only rename the TerritoryID column in the Sales.SalesTerritory table, but not the one in the Sales.vTer stored procedure.
Therefore, the Sales.SalesTerritory table will contain the TerrID column, but the stored procedure will call Sales.SalesTerritory.TerritoryID, which does not exist anymore. The script will be broken, and its execution will fail.
What are enforced dependencies?
A dependency is “enforced” when the referencing object has a schema-bound expression. This message is also shown, if there are any other objects that need to be dropped and re-created with the new column name, in order to rename the column successfully.
How to find the stored procedures and other objects that will be affected by the column name change?
SQL Server Management Studio can track dependencies, via its View Dependencies option. It shows the objects that depend on the selected one, but the objects that reference the renamed column need to be updated one by one.
To rename a column using sp_rename, the following needs to be done:
It is not an appealing process. It makes you want to give up the renaming, rather than continue with it.
How to rename a column without too much trouble?
ApexSQL Search can help. It’s a FREE SQL Server Management Studio and Visual Studio add-in which finds text in SQL database objects, and data in SQL database tables and views. It allows changing the tables, views, stored procedures, functions, columns, parameter names and schemas without breaking dependencies, while visualizing all object interdependencies.
Review, modify if needed and execute it by clicking Execute or save it to a file.
Renaming a column can be easy and FREE. There is no need to analyze a whole database and search for dependencies yourself. Use ApexSQL Search to do that. It will find all dependent objects, rename and drop–recreate when necessary, to avoid breaking the scripts.
© ALL RIGHTS RESERVED. 使用条款 隐私 Cookie Preference Center