【问题标题】:SQL Stored Procedure Case WhenSQL 存储过程案例何时
【发布时间】:2014-08-11 17:33:53
【问题描述】:

这样的事情可以在 SQL 存储过程中执行吗?还是我必须有 3 个单独的程序?这可以单独工作,但现在我只收到一个错误:关键字'between'附近的语法不正确。

FROM table a

WHERE
field1 = 'asd'
and field2 is null
and field3  not in ('a','b','c') 
and

case @input

when 'now' then
    (a.datefield between dateadd(day, -31, getdate()) and getdate())
when '24_hour' then
    (a.datefield between getdate() and dateadd(hour, 24, getdate()))
when '3_days' then
    (a.datefield between getdate() and dateadd(day, 3, getdate()))
end

order by a.datefield asc
end

【问题讨论】:

  • 你的问题不清楚。请详细说明。你想做什么?
  • @DH__ 似乎很清楚:他希望最后通过 @input 的值切换 where 子句中的检查。
  • 是的,添加了更多信息以使其更清晰。但我不确定是否可以根据输入设置 where 条件。如果中间条件相同,我可以在 getdate() 和 dateadd(hour, @input, getdate())) 之间执行 WHERE a.datefield 之类的操作。但它也会改变今天日期之前的行

标签: sql sql-server stored-procedures


【解决方案1】:

有几种方法可以实现这一点。以下是一种可能性:

case
    when @input ='now' and (a.datefield between dateadd(day, -31, getdate()) and getdate()) then 1
    when @input ='24_hour' and (a.datefield between getdate() and dateadd(hour, 24, getdate())) then 1
    when @input ='3_days' and (a.datefield between getdate() and dateadd(day, 3, getdate())) then 1
    else 0        
end = 1

为了最大的可扩展性,我可能会查看 TVC:

FROM table a
join (values 
        ('now',dateadd(day, -31, getdate()),getdate()),
        ('24_hour',getdate(),dateadd(hour, 24, getdate())),
        ('3_days',getdate(),dateadd(day, 3, getdate()))
     ) t(input,startdate,enddate) 
on t.input = @input
WHERE
field1 = 'asd'
and field2 is null
and field3  not in ('a','b','c') 
and a.datefield between t.startdate and t.enddate

【讨论】:

    【解决方案2】:

    您也可以完全替换 case 语句,只在 where 子句中使用 ANDOR 运算符。像这样……

    FROM table a
    
    WHERE field1 = 'asd'
    and   field2 is null
    and   field3  not in ('a','b','c') 
    and 
       (
        (@input ='now'     AND a.datefield between getdate()-31 and getdate())
        OR
        (@input ='24_hour' AND a.datefield between getdate() and dateadd(hour, 24, getdate()))
        OR
        (@input ='3_days'  AND a.datefield between getdate() and  getdate()+3)
       )
    order by a.datefield asc
    

    【讨论】:

    • 嗯,我收到此错误:从字符串转换日期和/或时间时转换失败。
    • 这意味着您没有将日期存储为 datetime 但字符串,这确实是个坏主意,始终使用适当的数据类型。
    • 啊,它成功了。它存储为日期时间。过程中是否有其他问题
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2016-12-23
    相关资源
    最近更新 更多