【问题标题】:Sql case statement in where clause to list weeks and months between two datesSql case语句在where子句中列出两个日期之间的周和月
【发布时间】:2013-07-17 20:54:06
【问题描述】:

我刚刚找到了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'

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

但是,我可以在Select 语句上方添加一个If 语句,但它会在Where 子句中处理它。有什么想法吗?

【问题讨论】:

    标签: sql-server tsql if-statement case where


    【解决方案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'
    

    【讨论】:

    • 那行不通,因为 Month 是 int 类型,而 end_date ofc 是 date 类型。错误:操作数类型冲突:日期与 int 不兼容。如果您安装了 sql server 实例,您可以自己尝试查询,表 spt_values 在那里
    • @Labrinths - 很抱歉。我在运行查询后更新了答案。
    • 干得不错,我花了几分钟才看到差异,但现在可以正常工作了,谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多