SQL Server - boolean literal?

前端 未结 13 859
深忆病人
深忆病人 2020-12-04 22:56

How to write literal boolean value in SQL Server? See sample use:

select * from SomeTable where PSEUDO_TRUE

another sample:



        
相关标签:
13条回答
  • 2020-12-04 23:31

    This isn't mentioned in any of the other answers. If you want a value that orms (should) hydrate as boolean you can use

    CONVERT(bit, 0) -- false CONVERT(bit, 1) -- true

    This gives you a bit which is not a boolean. You cannot use that value in an if statement for example:

    IF CONVERT(bit, 0)
    BEGIN
        print 'Yay'
    END
    

    woudl not parse. You would still need to write

    IF CONVERT(bit, 0) = 0
    

    So its not terribly useful.

    0 讨论(0)
  • 2020-12-04 23:31

    You can use the values 'TRUE' and 'FALSE'. From https://docs.microsoft.com/en-us/sql/t-sql/data-types/bit-transact-sql:

    The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

    0 讨论(0)
  • 2020-12-04 23:32
    select * from SomeTable where null is null
    

    or

    select * from SomeTable where null is not null
    

    maybe this is the best performance?

    0 讨论(0)
  • 2020-12-04 23:34

    SQL Server doesn't have a boolean data type. As @Mikael has indicated, the closest approximation is the bit. But that is a numeric type, not a boolean type. In addition, it only supports 2 values - 0 or 1 (and one non-value, NULL).

    SQL (standard SQL, as well as T-SQL dialect) describes a Three valued logic. The boolean type for SQL should support 3 values - TRUE, FALSE and UNKNOWN (and also, the non-value NULL). So bit isn't actually a good match here.

    Given that SQL Server has no support for the data type, we should not expect to be able to write literals of that "type".

    0 讨论(0)
  • 2020-12-04 23:35

    You can use 'True' or 'False' strings for simulate bolean type data.

    Select *
    From <table>
    Where <columna> = 'True'
    

    I think this way maybe slow than just put 1 because it's resolved with Convert_implicit function.

    0 讨论(0)
  • 2020-12-04 23:38

    Most databases will accept this:

    select * from SomeTable where true
    

    However some databases (eg SQL Server, Oracle) do not have a boolean type. In these cases you may use:

    select * from SomeTable where 1=1
    

    BTW, if building up an sql where clause by hand, this is the basis for simplifying your code because you can avoid having to know if the condition you're about to add to a where clause is the first one (which should be preceded by "WHERE"), or a subsequent one (which should be preceded by "AND"). By always starting with "WHERE 1=1", all conditions (if any) added to the where clause are preceded by "AND".

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