1

我有一个查询,谓词是在运行时确定的。根据我当前的设计,查询的返回时间不是最佳的。查询并不复杂,我已经验证了所需的索引(使用 Tuning Adviser)已经到位。我已经向自己证明,如果谓词是硬编码的,查询会更快。

以下是我遇到问题的查询。

以下查询需要几分钟才能完成

declare
   @matchFN                   bit         = 1     -- match on first name
  ,@matchLN                   bit         = 1     -- match on last name

;with cteContact1 as (
  select distinct
     c.ContactID 
    ,ltrim(rtrim(FirstName)) FN
    ,ltrim(rtrim(LastName)) LN
  from 
    dbo.contact c 
  left outer join
    dbo.ContactCertification cc on c.ContactID = cc.ContactID   
)
,cteContact2 as (
  select 
     c.ContactID 
    ,ltrim(rtrim(FirstName)) FN
    ,ltrim(rtrim(LastName)) LN
  from 
    dbo.contact c  
  left outer join
    dbo.ContactCertification cc on c.ContactID = cc.ContactID   
)
select distinct
   *
from
  cteContact1 c1
join
  cteContact2 c2 on 
    c1.FN = case when @matchFN = 1 then c2.FN else c1.FN end
    and
    c1.LN = case when @matchLN = 1 then c2.LN else c1.LN end

但是,如果我将最终查询更改为以下查询,则查询将在 5 秒内完成。

select distinct
   *
from
  cteContact1 c1
join      
  cteContact2 c2 on c1.FN = c2.FN  and c1.LN = c2.LN 

最终,这两个查询都应该归结为同一件事,那么为什么性能会有如此大的差异呢?

4

0 回答 0