如果使用声明参数,则像 sql 一样查询速度慢,如果不使用则查询速度快 [英] sql like query slow if using declare parameter but fast if not

查看:47
本文介绍了如果使用声明参数,则像 sql 一样查询速度慢,如果不使用则查询速度快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQL 2008:这很慢(需要 1 1/2 分钟):

<前>声明@p1 varchar(50)设置@p1 = '976j%'select * from invsearch_query where comparepnfwd like @p1

这只需不到一秒钟:

<前>select * from invsearch_query where comparepnfwd like '976j%'

为什么???

解决方案

我想你必须有一个非覆盖索引,其前导列 comparepnfwd 被文字查询使用,而不是被文字查询使用使用变量查询.

您可以使用 OPTION (RECOMPILE) 让 SQL Server 在考虑实际变量值的情况下重新编译计划.

SQL 2008: This is slow (takes 1 1/2 minutes):

declare @p1 varchar(50)
set @p1 = '976j%'
select * from invsearch_query where comparepnfwd like @p1

This takes less than a second:

select * from invsearch_query where comparepnfwd like '976j%'

Why???

解决方案

I would imagine that you must have a non covering index with leading column comparepnfwd that is used by the literal query but not by the query with the variable.

You can use OPTION (RECOMPILE) to get SQL Server to recompile the plan taking into account the actual variable value.

这篇关于如果使用声明参数,则像 sql 一样查询速度慢,如果不使用则查询速度快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆