I'm improving our SSIS process passing the variables through a declare and I found this:

Here you have the plan execution using variables brentozar.com/pastetheplan/?id=rkSxs7VPv for the following statement:

select *
from fact_Venta
where Data_ID >= @data1
and Data_ID <= @data2

And here without variables brentozar.com/pastetheplan/?id=SJ8soXEww

FROM [fact_Venta] 
WHERE [Data_ID]>=@1 
AND [Data_ID]<=@2

As you can see, when I use the declare SQL Database Engine doesn't use the index. The index used is a non-clustered for the column used on the where.

Both executions were on the same server, with the same set options and at the same time executed.


Why do you believe using variables instead of parameters will improve performance?

With local variables, the plan is optimized for unknown values using average density values gleaned from statistics to estimate row counts. With parameters, OTOH, SQL Server uses the actual parameter values provided for the initial compilation to estimate row counts. This generally provides a more optimal plan but at the risk of reusing a cached plan that is suboptimal for different values.

I suggest you use a parameterized query and ensure stats are up-to-date. Add an OPTION (RECOMPILE) hint to the query to avoid parameter sniffing for the range query. This will avoid reusing a suboptimal plan and the compilation overhead is insignificant in the case of a large query executed relatively infrequently by SSIS. The recompile hint should be used judiciously and isn't appropriate for an OLTP workload query executed many times per second.

Note that the actual values are sniffed with either parameters or variables when the recompile hint is specified.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.