SQL Server - boolean literal?

前端 未结 13 862
深忆病人
深忆病人 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:43

    You should consider that a "true value" is everything except 0 and not only 1. So instead of 1=1 you should write 1<>0.

    Because when you will use parameter (@param <> 0) you could have some conversion issue.

    The most know is Access which translate True value on control as -1 instead of 1.

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

    How to write literal boolean value in SQL Server?
    select * from SomeTable where PSEUDO_TRUE

    There is no such thing.

    You have to compare the value with something using = < > like .... The closest you get a boolean value in SQL Server is the bit. And that is an integer that can have the values null, 0 and 1.

    0 讨论(0)
  • 2020-12-04 23:46
    select * from SomeTable where 1=1
    
    0 讨论(0)
  • 2020-12-04 23:50

    I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!

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

    According to Microsoft: syntax for searching is

    [ WHERE <search_condition> ]*
    

    And search condition is:

    <search_condition> ::= 
        { [ NOT ] <predicate> | ( <search_condition> ) } 
        [ { AND | OR } [ NOT ] { <predicate> | ( <search_condition> ) } ] 
    [ ,...n ] 
    

    And predicate is:

    <predicate> ::= 
        { expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } expression 
    

    As you can see, you always have to write two expressions to compare. Here search condition is boolean expression like 1=1, a!=b

    Do not confuse search expressions with boolean constants like 'True' or 'False'. You can assign boolean constants to BIT variables

    DECLARE @B BIT
    SET @B='True'
    

    but in TSQL you can not use boolean constants instead of boolean expressions like this:

    SELECT * FROM Somewhere WHERE 'True'
    

    It will not work.

    But you can use boolean constants to build two-sided search expression like this:

    SEARCH * FROM Somewhere WHERE 'True'='True' 
    
    0 讨论(0)
  • 2020-12-04 23:57

    SQL Server does not have literal true or false values. You'll need to use the 1=1 method (or similar) in the rare cases this is needed.

    One option is to create your own named variables for true and false

    DECLARE @TRUE bit
    DECLARE @FALSE bit
    SET @TRUE = 1
    SET @FALSE = 0
    
    select * from SomeTable where @TRUE = @TRUE
    

    But these will only exist within the scope of the batch (you'll have to redeclare them in every batch in which you want to use them)

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