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'
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.
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.
In order to change the column names of the temporary table, we can give aliases to the source table columns in the select query.
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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With