Getting a boolean from a date compare in t-sql select

蹲街弑〆低调 提交于 2019-12-10 09:33:29

问题


I am wondering if something along the lines of the following is possible in ms-sql (2005)

SELECT (expiry < getdate()) AS Expired FROM MyTable WHERE (ID = 1)

I basically want to evaluate the date compare to a boolean, is that possible in the select part of the statement?


回答1:


Not directly. You have to use CASE, the CAST means it's interpreted as boolean by client code

SELECT
    CAST(CASE WHEN expiry < getdate() THEN 1 ELSE 0 END AS bit) AS Expired
FROM
    MyTable WHERE (ID = 1)

Another solution where one or zero rows are expected:

SELECT
    CAST(COUNT(*) AS bit) AS Expired   
FROM
    MyTable
WHERE
    ID = 1 AND expiry < getdate() 



回答2:


SELECT CASE WHEN expiry < getdate() THEN 'true' ELSE 'false' END AS Expired FROM MyTable WHERE (ID = 1)


来源:https://stackoverflow.com/questions/1896828/getting-a-boolean-from-a-date-compare-in-t-sql-select

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