首页 > 解决方案 > 基于参数执行的存储过程

问题描述

我有一个 SQL Server 存储过程

CREATE PROCEDURE spGetValues
    @Value varchar(50) = ‘ALL’,
    @date datetime
AS
BEGIN
    IF @Value <> 'ALL'
    BEGIN
        SELECT Col1, Col2 
        INTO #TempTable
        FROM NewTable
        WHERE DATEDIFF(day, datecol, @date) = 0
          AND detail = @Value
    END
    ELSE
    BEGIN
        SELECT col1, Col2 
        INTO #TempTable
        FROM NewTable
        WHERE DATEDIFF(day, datecol, @date) = 0 
    END
    
    ……../* Use the #TempTable and calculate */

END

我收到一个错误

数据库中已经有一个名为#TempTable 的表

如何避免这种情况?

标签: sqlsql-serversql-server-2012

解决方案


我建议将这些组合成一个语句:

select Col1, Col2 into #TempTable
from NewTable
where datediff(day, datecol, @date) = 0 and
      (detail = @Value or @Value = 'All')

如果您希望针对每个参数值进行优化,则可以添加option (recompile).

但是,如果性能是一个问题,那么我建议将逻辑编写为:

where datecol >= @date and
      datecol < dateadd(day, 1, @date) and
      (detail = @Value or @Value = 'All')

或者:

where convert(date, datecol) = @date 
      (detail = @Value or @Value = 'All')

其中任何一个都可以利用(datecol).


推荐阅读