Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 407
Joannes Vermorel Avatar asked Oct 07 '08 09:10

Joannes Vermorel


People also ask

Which datatype is used for boolean in SQL?

SQL Server Boolean There is no boolean data type in SQL Server. However, a common option is to use the BIT data type. A BIT data type is used to store bit values from 1 to 64. So, a BIT field can be used for booleans, providing 1 for TRUE and 0 for FALSE.

Is boolean same as bit?

SQL Server bit data type is 1 bit numeric datatype. It is also used as Boolean data type in SQL Server. You can store only 0, 1 or NULL in a bit data type.

What is the bit datatype in SQL Server?

Solution. SQL Server bit data type is an integer data type that can take only one of these values: 0, 1, NULL. With regard to the storage, if there are less than 9 columns of the bit data in the table, they are stored as 1 byte. If there are 9 to 16 such columns, they consume 2 bytes and so on.

How do you assign a bit value in SQL?

To insert a new value to the BIT column, use INSERT statement: INSERT INTO table_name (bit_column) VALUES (1); You can also use TRUE and FALSE as the inputs for the BIT columns, SQL Server will automatically convert them as follow: TRUE will be converted to 1.


2 Answers

Use the ~ operator:

DECLARE @MyBoolean bit SET @MyBoolean = 0 SET @MyBoolean = ~@MyBoolean SELECT @MyBoolean 
like image 132
Jonas Lincoln Avatar answered Sep 22 '22 14:09

Jonas Lincoln


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; 
like image 29
Galwegian Avatar answered Sep 21 '22 14:09

Galwegian