Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renaming a temporary table into a physical one

Can I do something like this?

create table #tbl_tmp (col1 int)

insert into #tbl_tmp select 3

exec sp_rename '#tbl_tmp','tbl_new'
like image 452
Corovei Andrei Avatar asked Sep 26 '11 08:09

Corovei Andrei


People also ask

How can I temporarily rename a table in SQL?

You can rename a table or a column temporarily by giving another name known as Alias. The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database.

Can we alter temporary table in SQL Server?

You can ALTER the SQL Server temp tables after creating it, but table variables don't support any DDL statement like ALTER statement. SQL temp tables can't be used in User Defined Functions, but table variables can be.

Can you alias a temp table?

In order to change the column names of the temporary table, we can give aliases to the source table columns in the select query.

Can we pass temp table as parameter to stored procedure?

A TEMP Table of User Defined Table Type has to be created of the same schema as that of the Table Valued parameter and then it is passed as Parameter to the Stored Procedure in SQL Server.


2 Answers

No.

If you are running this from a database other than tempdb you get

No item by the name of '#tbl_tmp' could be found in the current database ....

Which is not surprising as all the data pages etc. are in the tempdb data files so you wouldn't be able to rename this to suddenly become a permanent table in an other database.

If you are running this from tempdb you get

An invalid parameter or option was specified for procedure 'sys.sp_rename'.

If you do EXEC sp_helptext sp_rename and look at the definition the relevant bit of code disallowing this is

--------------------------------------------------------------------------  
 --------------------  PHASE 32:  Temporay Table Isssue -------------------  
 --------------------------------------------------------------------------  
 -- Disallow renaming object to or from a temp name (starts with #)  
 if (@objtype = 'object' AND  
  (substring(@newname,1,1) = N'#' OR  
  substring(object_name(@objid),1,1) = N'#'))  
 begin  
  COMMIT TRANSACTION  
  raiserror(15600,-1,-1, 'sys.sp_rename')  
  return 1  
 end  

Why wouldn't you just create a permanent table in the first place then do the rename?

like image 159
Martin Smith Avatar answered Sep 19 '22 06:09

Martin Smith


As far as I know this is not possible outside of tempdb.

Instead of renaming the table, you can create a new one from the temporary one.

Untested:

SELECT * 
INTO tbl_new
FROM #tbl_tmp
like image 41
Oded Avatar answered Sep 18 '22 06:09

Oded