sql - 在 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”值,并且具有相同电子邮件地址的多条记录。所以我不能创建全文索引。
是否有任何替代方法来优化这种类型的查询
解决方案
全文搜索将是最佳选择。如果可以将查询拆分为 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
推荐阅读
- powerbi - 1 列在视觉中使用了两次
- sql - 根据 SQL 中另一列中特定 ID 的条件计算持续时间
- javascript - 网页打开几分钟后变慢并刷新排序
- javascript - 如何使用 Google Maps JavaScript API 和 Places Library 将自动完成地址字段建议限制在一个国家/地区?
- python - FPDF:将变量插入 PDF
- c++ - C++ 中的 3 x 3 字符向量
- python - 尝试使用硒在linkedin中加载和保存登录cookie
- r - R中按组的多行乘积
- android - 从 Util / Jetpack Composee 访问 rememberLauncherForActivityResult
- mongodb - 如何按日期在我的聚合重复组中排序