简体   繁体   English

T-SQL LIKE使用变量和索引

[英]T-SQL LIKE using variable and index

If [column1] is indexed, the next query may use index: 如果[column1]被索引,则下一个查询可能使用索引:

SELECT * FROM [table] WHERE [column1] LIKE 'starts%'

If I introduce a variable, the query below will never use index: 如果我引入一个变量,下面的查询永远不会使用索引:

DECLARE @starts nvarchar(100)
SET @starts = 'starts%'
SELECT * FROM [table] WHERE [column1] LIKE @starts

I want to implement StartsWith search based on user input and i'm not sure what way to choose: 我想根据用户输入实现StartsWith搜索,我不知道选择何种方式:

  1. escape user input properly for LIKE so optimizer will be able to pick a plan based on literal 为LIKE正确转义用户输入,以便优化器能够根据文字选择一个计划

  2. use WITH(FORCESEEK) 使用WITH(FORCESEEK)

  3. use OPTION (RECOMPILE) 使用OPTION(RECOMPILE)

There is another choice you didn't list. 你没有列出另一个选择。 You can use the OPTIMIZE FOR option to force the query optimizer to make the correct assumption about the nature of the expected variable values. 您可以使用OPTIMIZE FOR选项强制查询优化器对预期变量值的性质做出正确的假设。 This seems to match your need very well. 这似乎很符合您的需求。

DECLARE @starts nvarchar(100)
SET @starts = 'starts%'
SELECT * FROM [table] WHERE [column1] LIKE @starts
OPTION (OPTIMIZE FOR (@starts = 'mnopq%'))

It's described in more detail in this blog . 它在本博客中有更详细的描述。 There is also the MSDN documentation . 还有MSDN文档

Instructs the query optimizer to use a particular value for a local variable when the query is compiled and optimized. 指示查询优化器在编译和优化查询时使用特定值作为局部变量。 The value is used only during query optimization, and not during query execution. 该值仅在查询优化期间使用,而不是在查询执行期间使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM