2010-09-15 120 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意味着表變量的性能會更好。