0

我刚刚找到了spt_values我发现非常有用的表格,现在我想要根据输入参数列出几周或几个月@Month

DECLARE @start_date [date]       = CAST('2013-08-01' as [date])
DECLARE @end_date [date]         = CAST('2013-10-01' as [date])
DECLARE @Month [bit]  = 0

SELECT
   case @Month when 0 then
              DATEPART(week,DATEADD(WEEK, [v].[number], @start_date))
           else DATEPART(MONTH,DATEADD(MONTH, [v].[number], @start_date)) end
           as 'Timespan'
FROM [master].[dbo].[spt_values] [v]
WHERE
    DATEADD(WEEK, [v].[number], @start_date) <= @end_date AND
           [v].[type] = 'P'

因此,如果我现在传入,@Month = 1我想要一个这样的 where 子句来列出几个月而不是几周。

WHERE 
CASE @Month WHEN 1 THEN 
 DATEADD(MONTH, [v].[number], @start_date) <= @end_date) when 0 then 
 DATEADD(WEEK, [v].[number], @start_date) <= @end_date) AND
           [v].[type] = 'P'

但不幸的是,这不起作用。

但是,我可以在声明 wwitch will work的If上方声明,但最好在子句中处理它。有任何想法吗?SelectWhere

4

1 回答 1

1

怎么样:

where case @Month
  when 0 then DATEADD(WEEK, [v].[number], @start_date)
  else DATEADD(MONTH, [v].[number], @start_date) end <= @end_date AND
  [v].[type] = 'P'
于 2013-07-18T19:12:02.370 回答