Search code examples
sql-servershort-circuiting

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


I have this select scenario:

I would like to return exact matches first, then only check for partial matches progressively, using a simple T-sql query.

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

I understand that T-sql performs All-At-Once Operations.

How best can this be achieved?


Solution

  • You could evaluate in a CASE and provide a ranking value:

    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]