我正在運行帶有多個連接的存儲過程,其中一個包含超過600,000條記錄的表。問題是這個過程非常緩慢,需要幾分鐘才能執行。我們編制了相關表格列,但仍然沒有運氣。SQL Server加速查詢
我們可以做些什麼來幫助提高性能?該查詢發佈在下面。
感謝
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
與領先的通配符LIKEs可能是什麼傷害你在這裏。沒有多少索引會提高他們的表現。 –
您還有(內部)加入下面的左(外部)連接。這些左連接將根據表格順序變成內連接。它看起來應該能夠在所有內部連接後移動而不會中斷查詢。 – billinkc