Before we get started…
I know. I know. BOL. It’s documented.
They even show you how to rename a table.
But sometimes…
You just forget.
And as with most simple mistakes, fixing them is… Weird.
Here’s what happened to me recently, when I was working on a table swapping demo.
CREATE TABLE dbo.Whatever (i int) SELECT * FROM dbo.[Whatever] AS [w]
Here’s where I was going to rename it, and then make another table with the INT column as a BIGINT.
EXEC [sys].[sp_rename] @objname = N'dbo.Whatever' , @newname = N'dbo.Whatever_New'
Which worked, except…
dbo.dbo.
Like most people who make mistakes, I decided to revisit the documentation afterwards. And, yeah, you don’t specify schema in the new object name.
So, now that you all know you’re smarter than me, how would you fix it?
I’ll spare you the trial and error:
EXEC [sys].[sp_rename] @objname = N'dbo.[dbo.Whatever_New]' , @newname = N'Whatever_New'
There were quite a few different arrangements of brackets and schema prefixes leading up to this.
I hope this post saves someone a little time.
Brent says: dear reader, please use this as part of an April Fool’s prank. Just not in production.