2010-09-15 124 views
0

查询优化

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 

它很好用,但我想优化这个,因为肌酸g太多的临时表。

有人能帮助我吗?

+0

如果不存在,你可以不插入...',你正在使用什么sql引擎/服务器? – RobertPitt 2010-09-15 10:29:04

+0

我认为条件1和条件2不相互排斥? '#temp1'和'#temp2'具有相同的结构吗? – 2010-09-15 10:57:07

+0

你可以确认你是否使用SQLServer,如果是,哪个版本? – 2010-09-15 14:39:50

回答

0

您可以在程序开始时删除表格。这是一个有点棘手,但你可以检查临时表像的存在:

if object_id('tempdb..#temp1') is not null 
    drop table #temp1 
0

我创建/删除条件语句像这样的外临时表:

create table #temp ... 

if(condition 1) 
begin 
(
    ----- 
    ----- 
    select into @temp 
    ---- 
) 
end 
if(condition 2) 
begin 
(
    ----- 
    ----- 
    select into @temp2 
    ---- 
) 
end 

drop table #temp 

假设您的SQL Server版本支持它们,并且您知道日志记录和事务回滚方面的差异,使用表变量可能会更好。这样,您不必担心它一旦超出范围就不会被放弃。

+0

无论如何,临时表总是应该在程序结束时被删除。 – 2010-09-15 14:38:53

+0

是的,但如果这是程序最后做的事情,那么为什么要写两遍? – MLT 2010-09-15 16:17:40

0

您可以尝试在if(condition 2)之前立即在第一个布局中添加TRUNCATE TABLE #temp1,但this question and accepted answer意味着表变量的性能会更好。