繁体   English   中英

需要帮助来加速SQL Server查询

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM