Boolean 'NOT' in T-SQL not working on 'bit' datatype?

Use the ~ operator:

DECLARE @MyBoolean bit
SET @MyBoolean = 0
SET @MyBoolean = ~@MyBoolean
SELECT @MyBoolean

Your solution is a good one... you can also use this syntax to toggle a bit in SQL...

DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = @MyBoolean ^ 1; 
SELECT @MyBoolean;

Subtracting the value from 1 looks like it'll do the trick, but in terms of expressing intent I think I'd prefer to go with:

SET @MyBoolean = CASE @MyBoolean WHEN 0 THEN 1 ELSE 0 END

It's more verbose but I think it's a little easier to understand.


To assign an inverted bit, you'll need to use the bitwise NOT operator. When using the bitwise NOT operator, '~', you have to make sure your column or variable is declared as a bit.

This won't give you zero:

Select ~1 

This will:

select ~convert(bit, 1)

So will this:

declare @t bit
set @t=1
select ~@t