T-SQL LIKE 使用变量和索引

T-SQL LIKE using variable and index

如果[column1]被索引,下一个查询可能使用索引:

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

如果我引入变量,下面的查询将永远不会使用索引:

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

我想实现基于用户输入的 StartsWith 搜索,但我不确定该选择什么方式:

  1. 为 LIKE 正确转义用户输入,以便优化器能够根据文字选择计划

  2. 使用 WITH(FORCESEEK)

  3. 使用选项(重新编译)

您还有一个选择没有列出。您可以使用 OPTIMIZE FOR 选项来强制查询优化器对预期变量值的性质做出正确的假设。这似乎很符合您的需求。

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

this blog. There is also the MSDN documentation 中有更详细的描述。

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.