sql - 基于参数执行的存储过程
问题描述
我有一个 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 的表
如何避免这种情况?
解决方案
我建议将这些组合成一个语句:
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)
.
推荐阅读
- reactjs - Eslint react/prop-types vs react/require-default-props
- jquery - 单击模式中的按钮时,尝试更改启动模式的按钮上的属性
- node.js - 如何嵌入架构
- python - 具有一个客户指标 IoU 的多输出回归
- python - 使用python计算词频
- excel - 如何在 Excel VBA 中将字典设置为字典值?
- r - 如何使用ggplot通过第三个分组变量对散点图中的离散变量进行排序?
- excel - 如何使用python在excel中显示数据?
- noclassdeffounderror - FlyWay NoClassDefFoundError
- nuget - TeamCity 克隆的构建配置因 NuGet 错误而失败