Return Boolean Value on SQL Select Statement

后端 未结 9 904
不知归路
不知归路 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:57

    I do it like this:

    SELECT 1 FROM [dbo].[User] WHERE UserID = 20070022
    

    Seeing as a boolean can never be null (at least in .NET), it should default to false or you can set it to that yourself if it's defaulting true. However 1 = true, so null = false, and no extra syntax.

    Note: I use Dapper as my micro orm, I'd imagine ADO should work the same.

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

    Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.

    SELECT DISTINCT 1 AS Expr1
    FROM [User]
    WHERE (UserID = 20070022)
    
    0 讨论(0)
  • 2021-01-29 22:01
    DECLARE @isAvailable      BIT = 0;
    
    IF EXISTS(SELECT 1  FROM [User] WHERE (UserID = 20070022))
    BEGIN
     SET @isAvailable = 1
    END
    

    initially isAvailable boolean value is set to 0

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