What is the best way to convert an int or null to boolean value in an SQL query?

前端 未结 10 1237
情话喂你
情话喂你 2021-02-06 21:07

What is the best way to convert an int or null to boolean value in an SQL query, such that:

  • Any non-null value is TRUE in the results
  • Any
相关标签:
10条回答
  • 2021-02-06 21:40

    To my knowledge (correct me if I'm wrong), there is no concept of literal boolean values in SQL. You can have expressions evaluating to boolean values, but you cannot output them.

    This said, you can use CASE WHEN to produce a value you can use in a comparison:

    SELECT 
        CASE WHEN ValueColumn IS NULL THEN 'FALSE' ELSE 'TRUE' END BooleanOutput 
    FROM 
        table 
    
    0 讨论(0)
  • 2021-02-06 21:40
    isnull(column - column + 1, 0) != 0
    
    0 讨论(0)
  • 2021-02-06 21:45
    SELECT 
        CASE
            WHEN thevalue IS NULL THEN 0
            ELSE 1
        END AS newVal
    FROM .... (rest of select)
    

    I think it goes something like this

    Actually, the ISNULL, may need to be WHEN thevalue IS NULL THEN 0

    0 讨论(0)
  • 2021-02-06 21:49

    The syntax works, but I had to figure out how to place it in my query. If OK, I'd like to share an example on how to fit into an extended query:

    select count(*) as count, inventory,
    CASE WHEN inventory = 0 THEN 'empty' ELSE 'not empty' END as InventoryStatus
    from mytable group by count, inventory
    
    0 讨论(0)
  • 2021-02-06 21:57

    You may want to do a Convert(BIT, Value) of your result. Because something SQL will return an error that the value is not a boolean.

    0 讨论(0)
  • 2021-02-06 21:57

    Usually when use 1, it means is true and else in other case.

    So:

    SELECT  IsDefault = CASE WHEN IsDefault = 1 THEN 'true' ELSE 'false' END
    FROM table
    
    0 讨论(0)
提交回复
热议问题