Tuesday, June 23, 2009

Renaming a Column in a Temp Table in SQL Server 2005 - Yes, You Can!

For whatever weird reason, you may need to create a temp table in one step, and then rename one of the columns. Perhaps you're creating the temp table in one stored procedure, and modifying it in another. I'm not going to tell you that's a silly thing to do, or you should just create it with the right names in the first place - I saw those kind of responses online, and it's very unhelpful! Sometimes you just need to do this type of thing.

It's not a straightforward thing to do, though. When you just run the below script that calls sp_rename:

if object_id('tempdb..#Test123') is not null drop table #Test123
create table #Test123 (field1 int)
exec sp_rename '#Test123.Field1', 'Field2', 'COLUMN'

...you get this error: "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."

The key is to call sp_rename from the tempdb, like so:

if object_id('tempdb..#Test123') is not null drop table #Test123
create table #Test123 (field1 int)
exec tempdb..sp_rename '#Test123.Field1', 'Field2', 'COLUMN'
select * from #Test123

And - success! Note that you'll still have problems referencing the specific fieldname that was renamed. I solved this by doing a select into another temp table. Also, the procedure you're doing this in will probably have to do a recompile - that wasn't a problem for me, either. Overall, it was a better solution than the alternatives.

16 comments:

  1. Thanks! Lovely precise solution!

    Marek J.

    ReplyDelete
  2. THANK YOU!!
    I killed two hours not realizing I must use:
    exec tempdb..sp_rename ...
    instead of
    exec sp_rename

    ReplyDelete
  3. Fantastic!!! Just what i needed. :)

    ReplyDelete
  4. You're great, thank you

    ReplyDelete
  5. Brilliant, thank you Sylvia

    ReplyDelete
  6. Excellent solution. Too many spend too much time telling you should never have to do this.

    ReplyDelete
  7. Thanks Sylvia, not often I need to do this, and each time I forget to call sp_rename in tempdb

    ReplyDelete
  8. Thanks. Awesome tip.

    ReplyDelete
  9. Just what I was looking for...thanks!

    ReplyDelete
  10. Thanks, Ms. Vasilik. I spent 3 days poring over many websites and tons of code samples. You fixed my problem in 40 seconds. Pat yourself on the back!!!!

    ReplyDelete
  11. I need to thank you for this tip very much also :)

    ReplyDelete