Return Boolean Value on SQL Select Statement

后端 未结 9 903
不知归路
不知归路 2021-01-29 21:36

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)

相关标签:
9条回答
  • 2021-01-29 21:43

    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
    
    0 讨论(0)
  • 2021-01-29 21:44

    Possibly something along these lines:

    SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT)
    FROM dummy WHERE id = 1;
    

    http://sqlfiddle.com/#!3/5e555/1

    0 讨论(0)
  • 2021-01-29 21:46

    Given that commonly 1 = true and 0 = false, all you need to do is count the number of rows, and cast to a boolean.

    Hence, your posted code only needs a COUNT() function added:

    SELECT CAST(COUNT(1) AS BIT) AS Expr1
    FROM [User]
    WHERE (UserID = 20070022)
    
    0 讨论(0)
  • 2021-01-29 21:55
    select CAST(COUNT(*) AS BIT) FROM [User] WHERE (UserID = 20070022)
    

    If count(*) = 0 returns false. If count(*) > 0 returns true.

    0 讨论(0)
  • 2021-01-29 21:56

    Use 'Exists' which returns either 0 or 1.

    The query will be like:

    SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)
    
    0 讨论(0)
  • 2021-01-29 21:56

    For those of you who are interested in getting the value adding a custom column name, this worked for me:

    CAST(
        CASE WHEN EXISTS ( 
               SELECT * 
               FROM mytable 
               WHERE mytable.id = 1
        ) 
        THEN TRUE 
        ELSE FALSE 
        END AS bool) 
    AS "nameOfMyColumn"
    

    You can skip the double quotes from the column name in case you're not interested in keeping the case sensitivity of the name (in some clients).

    I slightly tweaked @Chad's answer for this.

    0 讨论(0)
提交回复
热议问题