我有一个这种格式的存储过程
if(condition 1)
begin
(
-----
-----
select into #temp1
----
drop #temp1
)
end
if(condition 2)
begin
(
-----
-----
select into #temp1
----
drop #temp1
)
end现在,当执行上面的存储过程时,它向我显示了一个错误:
"There is already an object named '#temp1' in the database."当我像这样修改存储过程时,
if(condition 1)
begin
(
-----
-----
select into #temp1
----
drop #temp1
)
end
if(condition 2)
begin
(
-----
-----
select into #temp2
----
drop #temp2
)
end它的工作good.But我想优化这个,因为创建了太多的临时表。
有人能帮我解决这个问题吗?
发布于 2010-09-15 18:28:35
您可以在过程开始时删除该表。这有点棘手,但您可以检查是否存在临时表,如下所示:
if object_id('tempdb..#temp1') is not null
drop table #temp1发布于 2010-09-15 18:50:24
我会在条件语句之外创建/删除临时表,如下所示:
create table #temp ...
if(condition 1)
begin
(
-----
-----
select into @temp
----
)
end
if(condition 2)
begin
(
-----
-----
select into @temp2
----
)
end
drop table #temp假设您的SQL Server版本支持它们,并且您知道日志记录和事务回滚方面的差异,则使用表变量可能更好。这样,您就不必担心它一旦超出范围就不会被丢弃。
发布于 2010-09-15 22:46:04
在第一个布局中,您可以尝试在if(condition 2)之前添加TRUNCATE TABLE #temp1,但是this question and accepted answer意味着表变量的性能会更好。
https://stackoverflow.com/questions/3716735
复制相似问题