如何在T-sql中实现相当于“短路评估”

时间:2017-01-06 13:56:25

标签: sql-server short-circuiting

我有这个选择场景:

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

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

我了解T-sql执行一次性操作

如何才能实现这一目标?

2 个答案:

答案 0 :(得分:4)

您可以在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]

答案 1 :(得分:2)

您可以采用的一种方法是将查询拆分为多个查询。我并不是说这会带来最好的表现,但是:

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)

你可以做的其他事情,更“编程”是使用@@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 +'%'