【发布时间】:2011-10-20 14:06:51
【问题描述】:
我正在运行一个包含多个连接的存储过程,其中一个表包含超过 600,000 条记录。问题是该过程非常缓慢,可能需要几分钟才能执行。我们已经索引了相关的表列,但仍然没有运气。
我们可以做些什么来帮助提高性能?查询发布在下面。
谢谢
with CTE
as
(
select * from
(
select distinct c.ContactId, c.FirstName, c.LastName,
(select top 1 ce.Email from dbo.ContactEmails as ce where ce.ContactId = c.ContactId and ce.IsPrimary = 1) as Email,
comp.CompanyName, j.JobName, c.MobileNumber, c.OfficeNumber, cse.DateSent, MAX(cse.DateSent) over(partition by ce.email) as maxdate
from dbo.ContactSentEmails as cse
join dbo.ContactEmails as ce on cse.ContactId = ce.ContactId
join dbo.Contacts as c on ce.ContactId = c.ContactId
left join dbo.Jobs as j on c.JobId = j.JobId
left join dbo.Companies as comp on c.CompanyId = comp.CompanyId
join dbo.StaffProjects as sp on cse.StaffProjectId = sp.StaffProjectId
join dbo.Staff as s on sp.StaffId = s.StaffId
join dbo.Projects as p on sp.ProjectId = p.ProjectId
where (@ContactSourceId = -1 or c.ContactSourceId = @ContactSourceId)
and (@FirstName = '' OR c.FirstName LIKE '%' + @FirstName + '%')
and (@LastName = '' OR c.LastName LIKE '%' + @LastName + '%')
and (@EmailAddress = '' OR ce.Email LIKE '%' + @EmailAddress + '%')
and (@StaffId = -1 or sp.StaffId = @StaffId)
and (@ProjectId = -1 or sp.ProjectId = @ProjectId)
and (@OfficeId = -1 or p.OfficeId = @OfficeId)
and cse.DateSent between CONVERT(datetime, @startDate) and CONVERT(datetime, @endDate)
group by c.ContactId, c.FirstName, c.LastName, Email,comp.CompanyName, j.JobName, c.MobileNumber, c.OfficeNumber, cse.DateSent
) as tbContacts
)
select ContactId, FirstName, LastName, Email, CompanyName, JobName, MobileNumber, OfficeNumber from CTE where cte.DateSent = CTE.maxdate order by CTE.Email
【问题讨论】:
-
带有前导通配符的 LIKE 可能是在这里伤害您的原因。再多的索引也不会提高它们的性能。
-
在左(外)连接之后还有(内)连接。那些左连接将成为基于表排序的内连接。看起来它们应该能够在所有内部连接之后移动而不会破坏您的查询。
标签: sql sql-server performance stored-procedures