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

前端 未结 10 1225
情话喂你
情话喂你 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 22:00

    In Oracle, assuming you use 0 for false and 1 for true:-

    SELECT DECODE( col, NULL, 0, 1) FROM ...
    

    You can also write this using the CASE syntax, but the above is idiomatic in Oracle. DECODE is a bit like a switch/case; if col is NULL then 0 is returned, else 1.

    0 讨论(0)
  • 2021-02-06 22:00

    The shortest one I know for Oracle:

    SELECT NVL2(nullableColumn, 1, 0) FROM someTable
    

    NVL2(value, ifNotNull, ifNull) returns ifNotNull if the value is not null, and ifNull otherwise.

    0 讨论(0)
  • 2021-02-06 22:03

    Assuming you want 0,1 value as a return, and that we are talking about integer I would use the logic specified by Torbjörn and wrap it in the function

    create function dbo.isNotNull(@a int)
    returns bit
    as
    begin
    return isnull(@a-@a+1,0)
    end
    

    so then you can use it whenever you need by simply calling

    select dbo.isNotNull(myIntColumn) from myTable
    

    The answer provided by Tomalak is more universal though as it would work with any data type

    0 讨论(0)
  • 2021-02-06 22:07

    No need to use case... when:

    select (column_name is not null) as result from table_name;
    

    Returns 1 for all fields not NULL and 0 for all fields that are NULL, which is as close as you can get to booleans in SQL.

    0 讨论(0)
提交回复
热议问题