2011-01-28 134 views
1

我有一個查詢:不同的執行時間相同的查詢 - SQL服務器

Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 

當我執行這個查詢,它正在採取1-2秒來執行,但是當我使用相同的查詢存儲過程,下面的查詢花費5分鐘以上:

If(Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12)) 
    BEGIN 
     -- CREATE TEMPORARY TABLE [Say: #temp1] 
#temp1 => Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
     inserting the same value in the temp table 
     drop #temp1 
    END 

這可能是什麼原因?我該如何解決這個問題?我從asp.net運行SP

+0

爲什麼IF語句?你想做什麼? – gbn 2011-01-28 06:32:02

+0

您是否檢查過查詢計劃和io/cpu統計信息? – sisve 2011-01-28 07:27:10

+0

對於那些面臨同樣問題的人:兩個答案[by:binil&by:gbn]都適合我。 – Zerotoinfinity 2011-01-28 08:49:05

回答

3

一個EXISTS意志短路如果你

If EXISTS (Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12)) 
    BEGIN 
     -- CREATE TEMPORARY TABLE [Say: #temp1] 
#temp1 => Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
     inserting the same value in the temp table 

    END 

但是,爲什麼不詢問tbl_abc和tbl_xyz一次?

Select a 
    INTO #temp1 
    from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
    IF EXISTS (SELECT * FROM #temp1) /* or use @@ROWCOUNT*/ 
    BEGIN 
    --DoStuff 
    END 
    drop TABLE #temp1 
2

試試這個

declare @Count int 

select @Count = count (a) from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 

if(@Count > 0) 
begin 
    #temp1 => Select a from tbl_abc where id in (select id from tbl_xyz where mainid = 12) 
     inserting the same value in the temp table 
     drop #temp1 
end 

我也有同樣的情況,解決了這個樣子。

這可能是因爲執行查詢時的兩倍,它包含一個子查詢。不知道在執行這樣的查詢時發生了什麼。但改變這樣的查詢解決了我的得到延遲問題

0

mainid值是否實際硬編碼(12),還是僅僅是示例,實際上,您將此值作爲參數傳遞給您的存儲過程? (如果它是硬編碼的,你可能希望忽略以下內容)。

如果「12」是逸岸參數,你可能是參數嗅探的受害者。 Here's a question with some useful answers

一個方案中提到不可言傳是掩蓋參數 - 通過聲明一個局部變量做到這一點,將其設置爲您的參數值,並在查詢中使用。

相關問題