2012-03-14 30 views
0

我在SQL Server2005中有一個查詢,其中2個日期字段進行比較。如果我不包含時間並僅使用日期部分進行比較,則查詢運行速度很快(以毫秒爲單位)。但是,我需要將時間與日期部分進行比較。如果我包含時間部分,查詢運行速度非常慢,並最終返回連接超時錯誤。SQL服務器日期時間比較花費時間來執行

`((startdate1 >= @startdate2 and enddate1 <= @enddate2) or 
(startdate1 <= @startdate2 and enddate1 >= @startdate2 and enddate1 <= @enddate2) or 
(startdate1 >= @startdate2 and startdate1 < @enddate2 and enddate1 > @enddate2) or 
(startdate1 < @startdate2 and enddate1 > @enddate2))` 

這部分查詢花了很多時間來執行。但是,如果我將查詢更改爲以下格式,查詢運行速度非常快。

((cast(CONVERT(VARCHAR(10),startdate1,101) as datetime) >= cast(CONVERT(VARCHAR(10),@startdate2,101) as datetime)  
AND cast(CONVERT(VARCHAR(10),enddate1,101) as datetime)<= cast(CONVERT(VARCHAR(10),@enddate2,101) as datetime)) OR  

(cast(CONVERT(VARCHAR(10),startdate1,101) as datetime) <= cast(CONVERT(VARCHAR(10),@startdate2,101) as datetime)  
AND ((cast(CONVERT(VARCHAR(10),enddate1,101) as datetime) >= cast(CONVERT(VARCHAR(10),@startdate2,101) as datetime))  
AND (cast(CONVERT(VARCHAR(10),enddate1,101) as datetime) <= cast(CONVERT(VARCHAR(10),@enddate2,101) as datetime) ))) OR 

(cast(CONVERT(VARCHAR(10),startdate1,101) as datetime) >= cast(CONVERT(VARCHAR(10),@startdate2,101) as datetime) and  
((cast(CONVERT(VARCHAR(10),startdate1,101) as datetime) < cast(CONVERT(VARCHAR(10),@enddate2,101) as datetime)) AND  
(cast(CONVERT(VARCHAR(10),enddate1,101) as datetime) > cast(CONVERT(VARCHAR(10),@enddate2,101) as datetime) ))) OR  

(cast(CONVERT(VARCHAR(10),startdate1,101) as datetime) < cast(CONVERT(VARCHAR(10),@startdate2,101) as datetime) and  
cast(CONVERT(VARCHAR(10),enddate1,101) as datetime) > cast(CONVERT(VARCHAR(10),@enddate2,101) as datetime))) 

請給我建議一些想法。在此先感謝...

+0

......沒有意義。針對列的所有這些轉換應排除任何潛在的索引使用情況,而第一個查詢應能夠使用索引(如果存在)。你對這些列有任何有用的索引嗎? – 2012-03-14 10:50:40

+0

對第一種情況緩存錯誤的查詢計劃?使用fullscan運行'更新統計信息'(這應該刷新緩存並重新計算統計信息)並重試。 – Arvo 2012-03-14 10:51:34

+0

如何使用fullscan在yourtable上運行'更新統計信息' – ASD 2012-03-14 11:10:58

回答

0

你試過DateDiff函數嗎?

+0

是的..試過......這也是需要時間來執行的。代碼片段是:((dateiff(mm,@ startdate2,startdate1)> = 0且datediff(mm,@ enddate2,enddate1)<= 0)或 (datediff(mm,@startdate2,startdate1)<= 0且datediff mm,@startdate2,enddate1)> = 0且datediff(mm,@ enddate2,enddate1)<= 0)或 (datediff(mm,@startdate2,startdate1)> = 0且datediff(mm,@ enddate2,startdate1)< (mm,@ enddate2,enddate1)> 0) – ASD 2012-03-14 10:45:03

+0

執行時間超過20分鐘在表 – ASD 2012-03-14 10:46:32

+0

只有10條記錄這沒有意義,你定義這些變量的類型是什麼?你可以在你的程序中粘貼更多的代碼 – 2012-03-14 15:58:50