views:

11362

answers:

7

Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work

DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = NOT @MyBoolean;
SELECT @MyBoolean;

Instead, I am getting more successful with

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

Yet, this looks a bit a twisted way to express something as simple as a negation.

Am I missing something?

+5  A: 

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;
Galwegian
This solution did work ... thanks.
Martin
+3  A: 

BIT is a numeric data type, not boolean. That's why you can't apply boolean operators to it.
SQL Server doesn't have BOOLEAN data type (not sure about SQL SERVER 2008) so you have to stick with something like @Matt Hamilton's solution.

aku
+5  A: 

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.

Matt Hamilton
+15  A: 

Use the ~ operator:

DECLARE @MyBoolean bit
SET @MyBoolean = 0
SET @MyBoolean = ~@MyBoolean
SELECT @MyBoolean
Jonas Lincoln
This did not work. It turned 0 into -1, and 1 into -2.
Martin
It's because you're using an int, not a bit.
Jonas Lincoln
Column is a bit ... could the DB version matter?
Martin
+2  A: 

In SQL 2005 there isn't a real boolean value, the bit value is something else really.

A bit can have three states, 1, 0 and null (because it's data). SQL doesn't automatically convert these to true or false (although, confusingly SQL enterprise manager will)

The best way to think of bit fields in logic is as an integer that's 1 or 0.

If you use logic directly on a bit field it will behave like any other value variable - i.e. the logic will be true if it has a value (any value) and false otherwise.

Keith
A: 

i think the this sol. might work :

bit not null,

Abdullah Ashi
A: 

Use ABS to get the absolute value (-1 becomes 1)...

DECLARE @Trend AS BIT

SET @Trend = 0

SELECT @Trend, ABS(@Trend-1)

Stephen B Craver