Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 719
Chris Foot Avatar asked Dec 13 '09 15:12

Chris Foot


People also ask

How do you get a boolean result in SQL?

SQL Server does not support a Boolean type e.g. SELECT WHEN CAST(1 AS BIT) THEN 'YES' END AS result -- results in an error i.e. CAST(1 AS BIT) is not the same logical TRUE.

How can use compare operator with date in SQL?

This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.

How do you select a boolean in SQL Server?

SQL Server is in fact documented to have a Boolean data type. It just can not be returned from a SELECT or used as the type of a column or variable. For example, the type of a WHERE expression has to be Boolean, not bit . The = comparison operator returns a Boolean, for example.


2 Answers

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() 
like image 52
gbn Avatar answered Nov 15 '22 05:11

gbn


SELECT CASE WHEN expiry < getdate() THEN 'true' ELSE 'false' END AS Expired FROM MyTable WHERE (ID = 1)
like image 36
Paul Creasey Avatar answered Nov 15 '22 06:11

Paul Creasey