2012-03-08 39 views
0

因此,我现在有一个按其货币和值进行分组的值,它可以显示过去30天的值,但是我希望按日期进行搜索,最终使用另一个表中的参数。在DATEADD/datediff上定义一个搜索参数DATEADD/datediff - SQL server 2005

;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搜索的天数,这可能吗?例如。

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,过程亲c_getCurrencyHistory,第48行 “@dayparameter”附近语法不正确。

希望这是有道理的。

+2

我没有看到任何地方'@ days'。你的意思是' - @ dayparameter'而不是'@ dayparameter'(注意减号)? – 2012-03-08 14:46:26

+0

对不起,我已经改变了声明名称,使其更容易在眼睛上,我没有包括声明(我将更新我的示例将其带入上下文中)。这将是'@ dayparameter' int,然后是@ @ dayparameters' = -30 – Rexxo 2012-03-08 14:50:45

+1

来自@Aaron Bertrand的有效点。无论如何,您肯定可以计算cte之外的“from date”吗? – kaj 2012-03-08 14:51:05

回答

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 
+0

啊!太棒了,谢谢你的支持。 – Rexxo 2012-03-08 15:01:00