SQL Variable takes longer to return than static value SQL Variable takes longer to return than static value sql-server sql-server

SQL Variable takes longer to return than static value


This is called Parameter sniffing

when executing queries or stored procedures that use parameters. During compilation, the value passed into the parameter is evaluated and used to create an execution plan. That value is also stored with the execution plan in the plan cache. Future executions of the plan will re-use the plan that was compiled with that reference value.

You can avoid this by various methods. one is

Recompiling

You can add the option(Recompile) to the query so that every time the query is compiled a new execution plan will be generated

select top(1) ciid, businessdatefrom checkitemsaleswhere businessdate = @var1OPTION (RECOMPILE);

Disadvantages

  • Queries run frequently.
  • CPU resources are limited.
  • Some variance in query performance is acceptable.

Other methods are

  • Optimize For Value
  • Optimize For Unknown
  • Exceptions

Check the below articles on details of all the above methods

sp_BlitzCacheā„¢ Result: Parameter Sniffing

Parameter Sniffing


declare @var1 datetimeset @var1='10/9/16 00:00:00:000'select top(1) ciid, businessdatefrom checkitemsaleswhere (businessdate = @var1) option (recompile)

try this,and let me know the result,it might be faster


Can you try this approach:

declare @var1 datetimeset @var1='10/9/16 00:00:00:000'declare @cmd varchar(max) = 'select top(1) ciid, businessdatefrom #tablewhere businessdate = ''' + CONVERT(VARCHAR(10), @var1, 1) + ' '  + convert(VARCHAR(12), @var1, 114) + ''''EXEC (@cmd)