SQL Server 2012 - Case statement in where clause

我的未来我决定 提交于 2019-12-10 21:32:54

问题


SQL is not my strong suit, but I cannot figure out why this isn't working. I simply want to run a different AND statement based on a value. Specifically, I want to change the datePart in the dateDiff function if foo is = 0

SELECT foo,
       bar,
       test
FROM table
WHERE bar = 1,
CASE WHEN foo = 0
        AND dateDiff(dd, getDate(), 2 ) < test
ELSE
        AND dateDiff(hh, getDate(), 2 ) < test
END

回答1:


Try this one -

SELECT foo,
       bar,
       test
FROM [table]
WHERE bar = 1
    AND (
            (
                foo = 0 
                AND 
                DATEDIFF(dd, GETDATE(), 2 ) < test
            )
        OR  
            DATEDIFF(hh, GETDATE(), 2 ) < test
        )



回答2:


You can try like this

SELECT foo,
       bar,
       test
FROM table
WHERE bar = 1 And
(CASE WHEN foo = 0
    then   dateDiff(dd, getDate(), 2 )
ELSE
       dateDiff(hh, getDate(), 2 ) 
END)<test



回答3:


If I had to guess at what you're actually aiming for, it's that you wanted to subtract 2 hours or days from GETDATE() for use in your comparison.

Here's what I think you're aiming for:

SELECT foo,
       bar,
       test
FROM table
WHERE bar = 1 AND
(
   (foo = 0 AND DATEADD(day,-2, GETDATE()) < test)
   OR
   (foo<>0 AND DATEADD(hour,-2,GETDATE()) < test)
)

I can't think that you really intended those DATEDIFF calls. For example, today (3rd July 2013), this expression:

select CAST(DATEDIFF(dd,getdate(),2) as datetime)

Produces 1786-07-031. I'm assuming that test is a datetime and that the implicit conversion is being performed. Even if it's not, the numerical value of DATEDIFF(dd,getdate(),2) will always be a large negative number (unless or until it's run on a machine where GETDATE() returns a value from before the 20th Century)


1 Weirdly, I think 3rd July is the only day of the year on which the result will have the same month and day number.



来源:https://stackoverflow.com/questions/17441179/sql-server-2012-case-statement-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!