Search code examples
sql-serversql-server-2008sqldatatypes

Convert Bool to Bit in SQL Server


I need to write result of EXISTS function to a variable. I read that SQL Server has no 'bool' variables, so I want to store the result in a bit variable. And vice versa convert from 'bit' to 'bool'. How can I achieve it?


Solution

  • DECLARE @bool BIT;
    
    SELECT @bool = CASE WHEN EXISTS (some subquery) THEN 1 ELSE 0 END;
    

    I don't know what vice versa means. SQL Server doesn't have a boolean data type, so I don't know what you want to convert a BIT to... maybe:

    SELECT CASE WHEN @bool = 1 THEN 'True' ELSE 'False' END;
    

    If you're trying to do this in an IF statement:

    IF @bool = 1
    BEGIN
      PRINT 'True';
    END
    ELSE
    BEGIN
      PRINT 'False';
    END
    

    If you're looking for shorthand, where you can say IF (@bool) instead of IF (@bool) = 1, sorry, but you're out of luck. If this is where you are trying to "optimize" your code and you don't have more pressing problems, go home for the day and have a beer, you've earned it. Saving two characters has already cost you more time than it will ever gain you.