定义用于在DATEADD / datediff - SQL server 2005上搜索的参数

时间:2012-03-08 14:44:58

标签: sql-server-2005 stored-procedures datediff dateadd

所以我现在有一个按货币和价值组合的值,它会显示过去30天的值,但是我想按日期搜索,最后使用另一个表中的参数。

;WITH cte AS (SELECT ROW_NUMBER() OVER (ORDER BY date_loaded Asc) AS n, value, 
date_loaded, cast(round(value * 0.0001  / 100 * 0.5 + (value * 0.0001),4)AS dec(12,4)) as buy_rate,
        cast(round(value * 0.0001  / 100 * -0.5 + (value * 0.0001), 4) AS dec(12,4)) as sell_rate 

FROM texchange_rate WHERE source_currency_code = @source_currency_code 
and target_currency_code = @target_currency_code
and date_loaded between dateadd(day, datediff(day, 0 ,getdate())-30, 0) and getdate())

SELECT t2.value, t2.date_loaded, @source_currency_code as source_currency_code,
@target_currency_code as target_currency_code, t2.buy_rate, t2.sell_rate
    FROM cte t2 LEFT JOIN cte t1 ON t2.n = t1.n + 1
    WHERE t2.value <> ISNULL(t1.value, -1)

    order by date_loaded desc

END

我想定义dateadd从单独的表中搜索的天数,这可能吗? E.g。

来自

dateadd(day, datediff(day, 0 ,getdate())-30, 0) and getdate())

dateadd(day, datediff(day, 0 ,getdate())@dayparameter, 0) and getdate())

为了让这个工作,我尝试在存储过程开始时声明@dayparameter(类似于这里 - http://msdn.microsoft.com/en-us/library/ms186819%28v=sql.100%29.aspx,虽然这是针对服务器2008),并将其放在dateadd中会给出错误

  

消息102,级别15,状态1,过程proc_getCurrencyHistory,第48行   '@dayparameter'附近的语法不正确。

希望这是有道理的。

1 个答案:

答案 0 :(得分:1)

您仍需要执行操作。如果你想传入-30然后你需要添加,如果你想传入30,那么你需要减去。

如果@dayparameter是-30:

dateadd(day, datediff(day, 0 ,getdate()) + @dayparameter, 0) and getdate())
-----------------------------------------^ this operator is important

如果@dayparameter为30:

dateadd(day, datediff(day, 0 ,getdate()) - @dayparameter, 0) and getdate())
-----------------------------------------^ this operator is still important