Return Boolean Value on SQL Select Statement

mrjimoy_05 picture mrjimoy_05 · Apr 30, 2012 · Viewed 310.1k times · Source

How to return a boolean value on SQL Select Statement?

I tried this code:

SELECT CAST(1 AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)

And it only returns TRUE if the UserID exists on the table. I want it to return FALSE if the UserID doesn't exist on the table.

Answer

Chad picture Chad · Apr 30, 2012

What you have there will return no row at all if the user doesn't exist. Here's what you need:

SELECT CASE WHEN EXISTS (
    SELECT *
    FROM [User]
    WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END