2013-05-09 23 views
0

我有一個簡單的SQL查詢(見下文),長期運行下去(我無法等待其完成)存在()條件下的性能問題

if exists(
    select 1 
    from [files].[Contacts_Migration_Template] c 
    where not exists(select 1 
        from [files].[Additional_Contact_Migration_Template] 
        where contact = c.[migration id]) 
) print 'warning message' 

但子查詢(如果存在(子查詢)打印 '警告信息')本身是立即執行(見下面的截圖)

「全」 查詢 enter image description here

子查詢 enter image description here

產生的預估執行計劃(見下文)兩個查詢表明,子查詢必須比「完全」查詢更高查詢成本......其中,正如我上面說的,第一(子查詢)立即運行,第二個( 「全」)無限長的運行...

enter image description here

這是怎麼回事?


原始查詢

enter image description here

+0

快一個使用哈希聯接,只掃描'Additional_Contact_Migration_Template'一次。慢速掃描它(或至少是一個假脫機複製)多次。統計信息是否最新? – 2013-05-09 08:28:13

+0

,但爲什麼第一個相對查詢的成本是83%(對比17%),如果它更快? – 2013-05-09 08:31:08

+0

這是基於估計是錯誤的。它可能假定嵌套循環的內部執行次數將比實際發生的小得多。實際上可能是[行目標走向流氓](http://dba.stackexchange.com/questions/18637/unexpected-scans-during-delete-operation-using-where-in/18746#18746)。 – 2013-05-09 08:32:14

回答

0

我使用臨時表中斷執行順序。它有幫助。

select 1 [x] into #tmp_87624435 
from [files].[Contacts_Migration_Template] c 
where not exists(select 1 
    from [files].[Additional_Contact_Migration_Template] 
    where contact = c.[migration id]); 
if exists(select 1 from #tmp_87624435) throw 51000, 'warning', 1; 

,但我仍然認爲,即使這是矯枉過正這樣一個簡單的問題:)

0

試試這個:

if exists(

    select 1 from [files].[Contacts_Migration_Template] c left join 
    [files].[Additional_Contact_Migration_Template] a 
    on c.[migration id]=a.contact 
    where a.contact is null 
     ) 

print 'warning message' 
+0

在帖子中查看我的更正(我添加了原始查詢) - 原來我已加入,但他們也一直工作很長 – 2013-05-09 08:37:29

+0

由於我辦公室中的某些檢查點,我無法看到您的圖像。那麼你在查詢中使用了左連接嗎? – AnandPhadke 2013-05-09 08:44:28

+0

是的。最初,我使用完全相同的查詢,因爲你寫了:) – 2013-05-09 08:47:00