简体   繁体   English

需要帮助来加速SQL Server查询

[英]Need Help Speeding Up a SQL Server Query

I have a stored procedure that creates quite a few temp tables in memory. 我有一个存储过程,该过程在内存中创建了很多临时表。 I have the following query which takes an extremely long time to run (7 minutes). 我有以下查询,需要很长时间才能运行(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

Is there a way to speed this up? 有没有办法加快速度?

This is your query, with the unnecessary select distinct removed from the subquery: 这是您的查询,从子查询中删除了不必要的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;

Your performance problem is probably caused by the not exists . 您的性能问题可能是由not exists引起的。 Writing the query using left join might provide some benefit. 使用left join编写查询可能会带来一些好处。 But, the easiest approach is to switch from using a table variable to a temporary table, #tmpReportData4 . 但是,最简单的方法是从使用表变量切换到临时表#tmpReportData4 Then add an index on the temporary table: #tmpReportData4(dept, div, part) . 然后在临时表上添加索引: #tmpReportData4(dept, div, part)

A good start would be to change the "not in" to a left join. 一个好的开始是将“ not in”更改为左联接。

You might also consider using "#" (rather than "@") temp tables, because you can index #-tables. 您可能还考虑使用“#”(而不是“ @”)临时表,因为您可以索引#-表。

Can you include the complete stored procedure? 您可以包括完整的存储过程吗?

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

Try to re-create the sp, but no use any temp table, no use cursors.. that works for me. 尝试重新创建sp,但不使用任何临时表,不使用游标.. Also you can post your whole sp code. 您也可以发布整个sp代码。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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