如何在 T-sql 中实现 "short-circuit evaluation" 的等价物

How to achieve the equivalent of "short-circuit evaluation" in T-sql

我有这个 select 场景:

我想 return 首先完全匹配 ,然后只逐步检查部分匹配,使用简单的 T-sql 查询。

select * from accounts where 
   mobile = @mobile or  
   mobile like @mobile +'%' or 
   mobile like '%'+@mobile or 
   mobile like '%'+@mobile +'%'

我了解 T-sql 执行 All-At-Once 操作

如何最好地实现这一目标?

一种方法是将查询拆分为多个查询。我并不是说这提供了最好的性能,但是:

select * from accounts
where mobile = @mobile

union

select * from accounts
where like @mobile +'%'
    and not exists (select 1 from accounts where mobile = @mobile)

union

select * from accounts
where mobile like '%'+@mobile
    and not exists (select 1 from accounts where like @mobile +'%')

union

select * from accounts
where mobile like '%'+@mobile +'%'
    and not exists (select 1 from accounts where like '%'+@mobile)

您可以做的其他事情,更重要的是 "programatic" 是使用 @@ROWCOUNT,因为它模拟了短路,所以应该会提供更好的性能。

select * from accounts
where mobile = @mobile

if @@rowcount = 0
    select * from accounts
    where like @mobile +'%'

if @@rowcount = 0
    select * from accounts
    where mobile like '%'+@mobile

if @@rowcount = 0
    select * from accounts
    where mobile like '%'+@mobile +'%'

您可以在CASE中进行评估并提供排名值:

select
  mobile,
  case 
    when mobile = @mobile             then 1  
    when mobile like @mobile +'%'     then 2 
    when mobile like '%'+@mobile      then 3 
    when mobile like '%'+@mobile +'%' then 4
  end as [Rank]
from accounts where 
   mobile = @mobile or  
   mobile like @mobile +'%' or 
   mobile like '%'+@mobile or 
   mobile like '%'+@mobile +'%'
order by [Rank]