[英]Need Help Speeding Up a SQL Server Query
我有一個存儲過程,該過程在內存中創建了很多臨時表。 我有以下查詢,需要很長時間才能運行(7分鍾)。
select
a.DEPT,
a.DIV,
a.PART,
convert(datetime,convert(varchar(2),datepart("mm",a.Release_Date))+'/1/'+ convert(varchar(4),datepart("yyyy",a.Release_Date)),101) as rptng_mnth
from @tmpReportData3 a
where not exists
(select distinct DEPT,DIV,PART from @tmpReportData4 b
where a.DEPT = b.DEPT and a.DIV = b.DIV and a.PART = b.PART)
order by rptng_mnth
有沒有辦法加快速度?
這是您的查詢,從子查詢中刪除了不必要的select distinct
:
select a.DEPT, a.DIV, a.PART,
convert(datetime,convert(varchar(2),datepart("mm",a.Release_Date))+'/1/'+ convert(varchar(4),datepart("yyyy",a.Release_Date)),101) as rptng_mnth
from @tmpReportData3 a
where not exists (select DEPT, DIV, PART
from @tmpReportData4 b
where a.DEPT = b.DEPT and a.DIV = b.DIV and a.PART = b.PART
)
order by rptng_mnth;
您的性能問題可能是由not exists
引起的。 使用left join
編寫查詢可能會帶來一些好處。 但是,最簡單的方法是從使用表變量切換到臨時表#tmpReportData4
。 然后在臨時表上添加索引: #tmpReportData4(dept, div, part)
。
一個好的開始是將“ not in”更改為左聯接。
您可能還考慮使用“#”(而不是“ @”)臨時表,因為您可以索引#-表。
您可以包括完整的存儲過程嗎?
select
a.DEPT
,a.DIV
,a.PART
,convert(datetime,convert(varchar(2),datepart("mm",a.Release_Date))+'/1/'+ convert(varchar(4),datepart("yyyy",a.Release_Date)),101) as rptng_mnth
from
@tmpReportData3 a
left join @tmpReportData4 b on b.dept = a.dept and a.div = b.div and a.part = b.part
where b.dept is null
order by
a.rptng_mnth
嘗試重新創建sp,但不使用任何臨時表,不使用游標.. 您也可以發布整個sp代碼。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.