首页 > 解决方案 > 在 T-SQL 中优化 LIKE 语句的替代方法

问题描述

我需要执行以下操作:

select * from customer_details
where
Case When @LicenseNo != '' Then  dbo.customer_details.LicenseNo Else '' End LIKE  
'%' + @LicenseNo + '%'             
And Case When @EmailAddress = '' Then '' Else dbo.customer_details.ContactEmail End  LIKE  
'%'+  @EmailAddress+ '%' 

这是从存储过程执行的动态查询。虽然使用 LIKE 运算符查询执行会很慢。如何优化此类查询?

电子邮件地址列具有“NULL”值,并且具有相同电子邮件地址的多条记录。所以我不能创建全文索引。

是否有任何替代方法来优化这种类型的查询

标签: sqlsql-servertsql

解决方案


全文搜索将是最佳选择。如果可以将查询拆分为 4 个较小的查询,则可以改进查询,并且仅在确实需要时才执行“昂贵”的查询。您需要在存储过程中为此使用过程逻辑,而不是使用单个查询。

这个想法是您首先执行“最便宜”的查询,如果您获得业务逻辑规定的结果,则立即返回;如果没有得到结果,则执行下一个最便宜的查询,依此类推。根据您的数据,这可以使您免于运行昂贵的“捕获所有”查询。

我现在无法访问 SQL Server,因此无法编写实际的 proc,但它会类似于:

if @LicenseNo != '' and @EmailAddress != ''
  @result = select * from customer_details 
  where LicenseNo LIKE  @LicenseNo + '%'
  and   EmailAddress like @EmailAddress + '%'
  if %result 
    return %result
  else
    @result = select * from customer_details 
    where LicenseNo LIKE  '%' + @LicenseNo + '%'
    and   EmailAddress like @EmailAddress + '%'
    if %result 
      return
    end
   else
    @result = select * from customer_details 
    where LicenseNo LIKE  '%' + @LicenseNo + '%'
    and   EmailAddress like '%' + @EmailAddress + '%'
    if %result 
      return
    end
end

推荐阅读