将临时表格重命名为物理表格
问题描述:
我可以这样做吗?将临时表格重命名为物理表格
create table #tbl_tmp (col1 int)
insert into #tbl_tmp select 3
exec sp_rename '#tbl_tmp','tbl_new'
答
如果是从比tempdb
以外的数据库运行这个你
通过“#tbl_tmp”的名义无项目编号可以在当前 数据库中找到...
这并不奇怪,因为所有的数据页等都在tempdb
数据文件中所以你将无法重命名为突然成为其他数据库中的永久表。
如果从tempdb
运行这个你
无效的参数或选项是为程序指定 “sys.sp_rename”。
如果你EXEC sp_helptext sp_rename
并查看定义的代码不允许此相关的位
--------------------------------------------------------------------------
-------------------- 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
你为什么不只是创建摆在首位永久表然后做重命名?
答
#tbl_tmp
和tbl_new
是两个不同的对象:#tbl_tmp
存储在tempdb
系统数据库和tbl_new
(通常)存储在一个用户数据库中。
所以:
- 重命名一个临时表,以标准表可以假设从源数据库对象转移到另一个数据库。
- 重命名一个临时表,标准表意味着你要的对象从一种类型转变成另一种类型(在两种情况下
type
(从sys.objects中查看)是U
,但由于SQL Server
行为不同,我认为是正确的认为这两个对象有不同的类型)。这就像通过重命名将临时表转换为表变量。
在这两种情况下,我认为不可能仅使用sp_rename
来执行此操作。
答
答案是肯定的。你可以实现类似的东西,但以一种解决方法。 尝试下面的方法,一个小老头,但绕过限制。我测试了它自己以及
/* Create an empty temporary staging table **/
use aw_08r2
go
-- create temporary table
select * into #temp from person.address
-- select data from temporary staging table
select * from #temp
-- convert the temporary table and save as physical table in tempdb
select * into tempdb.dbo.test from #temp
-- save a copy of the physical table from tempdb in aw_08r2
select * into person.test from tempdb.dbo.test
-- select data from physical table
select * from #temp
select * from tempdb.dbo.test
select * from person.test
-- drop temporary table and physical table from tempdb
drop table #temp
drop table tempdb.dbo.test
go
是的,我意识到,为了能够调用sp_rename表必须有,而临时表相关的OBJECT_ID没有之一。 –
@CoroveiAndrei - 他们做的。尝试'使用tempdb;选择object_id('#tbl_tmp')'或从另一个数据库上下文'select object_id('tempdb ..#tbl_tmp')' –