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

前端 未结 7 628
闹比i
闹比i 2020-12-13 23:22

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 @My         


        
相关标签:
7条回答
  • 2020-12-13 23:25

    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.

    0 讨论(0)
  • 2020-12-13 23:27

    Use the ~ operator:

    DECLARE @MyBoolean bit
    SET @MyBoolean = 0
    SET @MyBoolean = ~@MyBoolean
    SELECT @MyBoolean
    
    0 讨论(0)
  • 2020-12-13 23:36

    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.

    0 讨论(0)
  • 2020-12-13 23:39

    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.

    0 讨论(0)
  • 2020-12-13 23:47

    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
    
    0 讨论(0)
  • 2020-12-13 23:48

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

    DECLARE @Trend AS BIT
    SET @Trend = 0
    SELECT @Trend, ABS(@Trend-1)
    
    0 讨论(0)
提交回复
热议问题