SQL 服务器过程变量声明

SQL Server PROCEDURE Variable Declaration

我有一个疑问,为什么我们在调用带参数的存储过程时必须将变量重新分配给新值。 在程序中我们需要 2 个变量。并且需要重新分配变量以便在过程中使用。

我相信这回答了你的问题(或者我对此的理解):

Global variables in SQL

参数嗅探

https://blogs.msdn.microsoft.com/turgays/2013/09/10/parameter-sniffing-problem-and-possible-workarounds/

SQL Server compiles the stored procedures using (sniffing) the parameters send the first time the procedure is compiled and put it in plan cache. After that every time the procedure executed again, SQL Server retrieves the execution plan from the cache and uses it (unless there is a reason for recompilation). The potential problem arises when the first time the stored procedure is executed, the set of parameters generate an acceptable plan for that set of parameters but very bad for other more common sets of parameters.

link提供的解决方案之一是使用局部变量。例如,您已经在做什么。