我有一个客户提供的sql查询,我们需要进行性能优化。
有没有人可以指出我在哪里开始寻找优化以下查询的正确方向?
我本地计算机上的查询大约需要6-7秒,但对用户来说大约需要30秒,它会在mssql 2008r2上执行
谢谢!
var query = @"
DECLARE @SearchString nvarchar(250)
set @SearchString = '1811820001'
;with BaseSelectorCTE (ID) as
(
SELECT ID FROM BaseCases b
where
b.CPR like @SearchString
OR (b.FirstName + ' ' + b.LastName) like @SearchString
OR b.CustomerInfo_InstitutionName like @SearchString
UNION
Select ID from FlexjobCase
where Kommune like @SearchString
UNION
Select ID from DisabledAssistantCase
where Kommune like @SearchString
UNION
Select ID from AdultStudentCase
where Kommune like @SearchString
UNION
Select ID from DiseaseCase
where Kommune like @SearchString
UNION
Select ID from MaternityCase
where Kommune like @SearchString
UNION
Select ID from MiscellaneousCase
where Kommune like @SearchString
UNION
Select ID from WageSubsidyCase
where Kommune like @SearchString
UNION
Select w.ID from WageSubsidyCase w inner join JobCenters j on
w.JobcenterID = j.ID
where
j.Name like @SearchString
UNION
Select a.ID from AdultStudentCase a inner join JobCenters j on
a.JobcenterID = j.ID
where
j.Name like @SearchString
)
--
-- Select BaseCases mapped to result type
--
,ResultSelectorCTE AS
(
select
bc.Id as CaseID,
bc.ChildCaseName,
bc.CPR,
bc.FirstName,
bc.LastName,
bc.CustomerInfo_CustomerInfoID as CustomerInfoID,
bc.CustomerInfo_InstitutionName as InstitutionName,
bc.CaseDeadline,
bc.StatusID,
cs.Name as [StatusName],
cs.Owner as [StatusOwner],
bc.MetaData_Updated as [LastChange],
bc.LastActionDay,
,CASE bc.StatusID WHEN 9 THEN 1 ELSE 0 END as SidstePeriodeSoegt
from BaseCases bc
inner join CaseStatus cs ON
bc.StatusID = cs.ID
inner join BaseSelectorCTE bsCTE ON
bc.ID = bsCTE.ID
)
select * from (Select *, ROW_NUMBER() Over(Order By @@version , CASE WHEN StatusID = 9 then 2 ELSE 1 END, CaseDeadline ASC,
SidstePeriodeSoegt)
As rownum from ResultSelectorCTE where 1=1 AND StatusOwner <> 2 AND StatusOwner <> 3
AND SUBSTRING(CPR, 0, 3) BETWEEN 26-08-2014 AND 26-08-2015) As Result
where rownum Between ((1 - 1) * 100 + 1) AND (1 * 100);
答案 0 :(得分:0)
SQL Server数据库引擎可以显示它如何导航表并使用索引访问或处理查询或其他DML语句(如更新)的数据。这是执行计划的显示。要分析运行缓慢的查询,检查查询执行计划以确定导致问题的原因非常有用。
答案 1 :(得分:0)
在不知情的情况下,首先丢失通配符(*)。它几乎总是如你所说的那样糟糕,发送所有内容而忘记实际审查它。
然后,正确格式化你的代码,CTE很棒,简化了代码,但是如果你的选择看起来像意大利面,它就胜过了目的,这与性能无关。
此外,当UNION ALL表现优于UNION时,我有很多次,我真的不认为重复是否有问题,所以你可能想看看that。
你没有说你是从Management Studio运行它,你是在本地或远程服务器上,CTE如何单独执行等等。上下文就是这个问题。 希望这可以帮助。