SQL存储过程案例何时

时间:2014-08-11 09:04:06

标签: sql sql-server stored-procedures

在SQL存储过程中可以这样做吗?或者我必须有3个单独的程序?这是单独的,但现在我只得到一个错误:关键字附近的语法不正确'介于'。

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

2 个答案:

答案 0 :(得分:3)

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

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

对于最大的scalabilty,我可能会看一下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

答案 1 :(得分:1)

您也可以完全替换case语句,并且只使用where 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