如何按值传递sql函数参数 [英] How to pass sql function parameter by value
问题描述
这是一个更大的选择的一部分,但我已经把它简化为基本问题:
This is part of a bigger selection, but I have stripped it down to the essential question :
比较这两个 SQL 查询 - 第一个使用常量,第二个使用变量,两者都具有相同的值(假设为 180).带有常量的立即显示结果(例如在几毫秒内),带有变量的需要几秒钟才能产生相同的结果.
Compare this two SQL queries - the first works with a constant, the second with a variable, both have the same value (lets say 180). The one with the constant displays result immediately (e.g. within milliseconds), the one with the variable takes a few seconds to yield the same result.
钓点在哪里?
查询 1:
SELECT *
FROM table
WHERE field > 180
查询 2:
DECLARE @V INT
SET @v = 180
SELECT *
FROM table
WHERE field > @v
推荐答案
问题在于 参数嗅探.从提到的文章:
The catch lies in parameter sniffing. From the article mentioned:
当参数化查询使用缓存的基数估计来做出查询计划决策时,会发生参数嗅探.当第一次执行具有非典型参数值时就会出现问题.对于每次后续执行,优化器将假设估计是好的即使估计值可能相差甚远.例如,假设您有一个返回 1 到 1000 之间的所有 id 值的存储过程.如果使用如此大范围的参数值执行存储过程,优化器将缓存这些非典型值值,这间接导致优化器低估基数.问题是典型的执行可能只返回几行.这种嗅探"会导致查询扫描表反对寻找,因为优化器假设基数估计不准确."
这篇关于如何按值传递sql函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!