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?
Asked
Active
Viewed 2.0k times
5
-
2possible duplicate of [is it possible to select EXISTS directly as a bit?](http://stackoverflow.com/questions/2759756/is-it-possible-to-select-exists-directly-as-a-bit) – Tim Schmelter Sep 05 '12 at 22:27
1 Answers
14
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.

Aaron Bertrand
- 272,866
- 37
- 466
- 490