如果我在SQL Server 2012中有这样一个非常基本的存储过程:
Create Procedure [MyStoredProcedure] (@ input as int)
As
Select 1 as col1, 2 as Col2
Into #mytemp1
Drop Table #mytemp1
Select 3 as col1, 4 as Col2, 5 as Col3
Into #mytemp1
Drop Table #mytemp1
我尝试运行它失败并出现错误'已经有一个名为' #mytemp1'在数据库中。' 如果这不是一个存储过程,我可以在最初删除临时表后使用GO。 有没有解决的办法? 感谢
答案 0 :(得分:1)
如果在单个存储过程或批处理中创建了多个临时表,则它们必须具有不同的名称。
Create Procedure [MyStoredProcedure] (@ input as in)
As
begin
Select 1 as col1, 2 as Col2
Into #mytemp1
Drop Table #mytemp1
Select 3 as col1, 4 as Col2, 5 as Col3
Into #mytemp1 // you cant use same **temp table** name in sp
Drop Table #mytemp1
end
这不是因为该表已被删除而无法重新创建;这段代码永远不会执行,解析器实际上会看到你试图创建两次相同的表
答案 1 :(得分:1)
由于没有明确需要重复使用相同的临时表名称,因此只需为每个临时表使用唯一的名称。
嗯,技术上你可以做类似以下的事情:
EXEC('
Select 1 as col1, 2 as Col2
Into #mytemp1
something else related to #mytemp1
');
EXEC('
Select 3 as col1, 4 as Col2, 5 as Col3
Into #mytemp1
something else related to #mytemp1
');
这不会失败,因为每个临时表都在一个未解析的子进程中被隔离,直到EXEC
实际运行。并且,EXEC
完成时临时表消失(因此不需要显式的DROP
语句)。但在大多数情况下,这不是一个实际的解决方案,因为创建临时表的典型目的是将数据传递给其他操作,但是这些临时表仅在其特定的EXEC
上下文中可行,所以有点有限的。
答案 2 :(得分:0)
使用OBJECT_ID
Create Procedure [MyStoredProcedure] (@ input as in)
As
if OBJECT_ID('tempdb..#mytemp1') is not null
Drop Table #mytemp1
Select 1 as col1, 2 as Col2
Into #mytemp1 from mytable
-- perform your operations here
if OBJECT_ID('tempdb..#mytemp1') is not null
Drop Table #mytemp1
Select 3 as col1, 4 as Col2, 5 as Col3
Into #mytemp1 from mytable
-- perform your operations here