Fun with sp_rename

Leave a comment

January 11, 2018 by Kenneth Fisher

Currently the only way to rename objects in SQL Server is to use sp_rename. Although that may be changing in the near future. There is a new command RENAME that is specifically for Azure SQL Data Warehouse and Parallel Data Warehouse. With any luck they will migrate that to Azure SQL Database and eventually SQL Server itself. Regardless, for now it’s sp_rename, which is useful, but it does have a few odd properties.

The first thing is that if you change the name of a stored procedure, function, etc you aren’t changing the name as it exists in the code. That can be a real pain, but that’s not where the fun part of renaming comes in.

Let’s take a look at the parameters:

  • @objname
  • @newname
  • @objtype

 
We are going to ignore the third parameter (yes, sp_rename has a third parameter). I’ve probably used it 2, maybe 3 times in all the time I’ve been using SQL. Working backwards (since we started at the end), the second parameter is the new name of the object being renamed, and the first is the existing name of the object. So where does that get weird?

The first parameter is (or at least can be) the fully qualified name of the object. So dbo.tablename or dbo.tablename.columnname. But the second column is only the name of the object. Let’s say that last bit one more time. The second column is only the name of the object. Why does that matter? Well, let’s try a simple example:

EXEC sp_rename 'dbo.tablename', 'dbo.tablename'

Anyone want to guess what the new name is going to be?

  • Schema: dbo
  • Object: dbo.tablename

 
Or written out it would look like this [dbo].[dbo.tablename]. Unfortunately, since SQL requires []’s (or “s) around a name with spaces, periods, or other special characters we can’t just call it like this: dbo.dbo.tablename. What that means is that in order to fix this (and yea, it happens every now and again by accident) we have to do this:

EXEC sp_rename '[dbo].[dbo.tablename]', 'tablename'

End result, it’s not really all that hard to get right. You just have to remember that while that the first parameter is a fully qualified name, the second should only be the actual new name. Well, unless you feel like messing with someone.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 2,452 other followers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: