Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot rename the column of a temp table

I created a global temp table like this -

CREATE TABLE ##BigTable
(Nos varchar(10) null)

Then try to rename the Nos column like this -

EXEC sp_RENAME '##BigTable.Nos' , 'Numbers', 'COLUMN'

I got the error -

Either the parameter @objname is ambiguous or the 
claimed @objtype (COLUMN) is wrong.

Why could this be happening and how do I solve the problem ?



EXTRA stuff not exactly related to the question, but for reference.

I want to add this - I tried to create the global temp table using a fully qualified name like this -

CREATE TABLE [NotMyTempDataBase].[dbo].[##BigTable]
(Nos varchar(10) null)

Then, I tried to rename it using -

EXEC tempdb.sys.sp_rename N'[NotMyTempDataBase].[dbo].[##BigTable].Nos', 
N'Numbers', N'COLUMN';

Error - The qualified @oldname references a database other than the current database.

This is wrong. I realized that the temp table is created in the system database tempdb, even though you specify another DB name while creating it.

use this instead -

CREATE TABLE [tempdb].[dbo].[##BigTable]
(Nos varchar(10) null)

--SQL server message : Database name 'tempdb' ignored, referencing object in tempdb.

EXEC tempdb.sys.sp_rename N'[tempdb].[dbo].[##BigTable].Nos', 
N'Numbers', N'COLUMN';
like image 726
HappyCoder Avatar asked Jan 30 '14 19:01

HappyCoder


People also ask

How do I rename a column in a SQL temp table?

How to rename column name in Sql Server. Many times we come across a scenario where we need to rename / change the existing table column name. We can use the SP_RENAME system stored to change/rename the table column name.

How do I rename a column in a table?

You select the table with ALTER TABLE table_name and then write which column to rename and what to rename it to with RENAME COLUMN old_name TO new_name .

How do I rename an existing column?

ALTER TABLE table_name RENAME TO new_table_name; Columns can be also be given new name with the use of ALTER TABLE. QUERY: Change the name of column NAME to FIRST_NAME in table Student.


1 Answers

Ok, so the actual solution is:

EXEC tempdb.sys.sp_rename N'##BigTable.Nos', N'Numbers', N'COLUMN';

Since the #temp table (even a ##global temp table) lives in tempdb, you need to invoke sp_rename there.

But further questions to consider:

  • Why on earth are you using a ##global temp table? You know this effectively limits concurrency to ONE, right? What do you think will happen when two users call this code at the same time? Probably you want to use a #local temp table here, or maybe avoid #temp tables altogether.

  • Why do you have the need to change the column name halfway through the script? Either name it right in the first place, or keep referencing the old name. How is the script later on going to know you changed the name? For what purpose?

like image 147
Aaron Bertrand Avatar answered Sep 23 '22 00:09

Aaron Bertrand