从引用先前声明的变量的CASE语句中分配T-SQL变量

时间:2014-08-22 18:38:23

标签: sql sql-server reporting-services case dateadd

我正在尝试动态定义查询的时间段,并在将用户输入转换为日期时间格式时遇到问题,如下所示:

declare @ObjectName nvarchar(256) = '%',
        @TimePeriod int = '1',
        @TimeInterval nvarchar(128) = 'month',
        @PastPeriodDate datetime


SET @PastPeriodDate = 
  CASE @TimeInterval 
    WHEN 'hour'     THEN (select DATEADD(hour,-@TimePeriod,getdate())
    WHEN 'day'      THEN (select DATEADD(day,-@TimePeriod,getdate())
    WHEN 'week'     THEN (select DATEADD(week,-@TimePeriod,getdate())
    WHEN 'month'    THEN (select DATEADD(month,-@TimePeriod,getdate())
    WHEN 'year'     THEN (select DATEADD(year,-@TimePeriod,getdate())
    ELSE ''
  END

print @PastPeriodDate

我需要在执行时间前一周将'1''周'转换为日期时间字符串,并且在过去完成此操作,但从不涉及案例陈述。这是使用where子句过滤以下查询中的结果:

select * 
from table1 t1
where t1.time > @PastPeriodDate

尝试运行此查询时,我收到以下输出:

Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'WHEN'.
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'WHEN'.
Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'WHEN'.
Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword 'WHEN'.
Msg 156, Level 15, State 1, Line 13
Incorrect syntax near the keyword 'ELSE'.

任何有关我出错的建议或更有效的方法都会受到赞赏。

2 个答案:

答案 0 :(得分:6)

看起来你在每条WHEN线上都缺少一个括号。您应该能够像这样修复和简化:

    DECLARE @ObjectName NVARCHAR(256) = '%' ,
    @TimePeriod INT = '1' ,
    @TimeInterval NVARCHAR(128) = 'month' ,
    @PastPeriodDate DATETIME


SET @PastPeriodDate = CASE @TimeInterval
                        WHEN 'hour'
                        THEN DATEADD(hour, @TimePeriod * -1, GETDATE())
                        WHEN 'day'
                        THEN DATEADD(day, @TimePeriod * -1, GETDATE())
                        WHEN 'week'
                        THEN DATEADD(week, @TimePeriod * -1, GETDATE())
                        WHEN 'month'
                        THEN DATEADD(month, @TimePeriod * -1, GETDATE())
                        WHEN 'year'
                        THEN DATEADD(year, @TimePeriod * -1, GETDATE())
                        ELSE ''
                      END

PRINT @PastPeriodDate

答案 1 :(得分:1)

你很接近......不需要选择,而你将留下一个不应该在那里的开放式支架。尝试:

 declare @ObjectName nvarchar(256) = '%',
    @TimePeriod int = '1',
    @TimeInterval nvarchar(128) = 'month',
    @PastPeriodDate datetime


 SET @PastPeriodDate = CASE @TimeInterval 
                        WHEN 'hour'     THEN DATEADD(hour,-@TimePeriod,getdate())
                        WHEN 'day'      THEN DATEADD(day,-@TimePeriod,getdate())
                        WHEN 'week'     THEN DATEADD(week,-@TimePeriod,getdate())
                        WHEN 'month'    THEN DATEADD(month,-@TimePeriod,getdate())
                        WHEN 'year'     THEN DATEADD(year,-@TimePeriod,getdate())
                        ELSE ''
                END

 print @PastPeriodDate