SQL: Can I negate a condition in a where clause?

后端 未结 5 805
栀梦
栀梦 2021-01-13 00:28

I want to check if a boolean is true, then decide in the WHERE clause what condition to use.

Say the boolean variable is @checkbool:

SELECT *
FROM Ta         


        
相关标签:
5条回答
  • 2021-01-13 00:46

    You can use IN clausule or even the != operator, like:

    A.Id NOT IN (123,x,y,z);
    

    or

    A.Id != 123;
    
    0 讨论(0)
  • 2021-01-13 00:54

    If checkbool is a coumn, then something like this will do.(Not in proper SQL syntax)

    WHERE (A.ID=123 AND A.checkbool=TRUE) OR (A.ID!=123 AND A.checkbool=TRUE)
    

    If checkbool is not a cloumn, replace A.checkbool with value of checkbool.

    here is the correct SQL

    WHERE ((checkbool) AND (A.Id =  123))OR ((NOT checkbool) AND (A.Id <> 123))
    
    0 讨论(0)
  • 2021-01-13 00:55

    Here is one solution:

    IF @Checkbool = 1
         SELECT * FROM Table A WHERE A.Id = 123
    ELSE
         SELECT * FROM Table A WHERE A.Id <> 123
    

    Here is another using just the WHERE Clause:

    SELECT * 
    FROM Table A 
    WHERE
         (@Checkbool = 1 AND A.Id = 123)
         OR
         (@Checkbool = 0 AND A.Id <> 123)
    

    Everything you put in the where clause needs to be in the form of an expression. Thus, the solution in this case is to write the condition in the form of an expression.

    Hope this helps. :)

    0 讨论(0)
  • 2021-01-13 01:00
    select *
    from TableA A
    where
        (@checkbool = 1 and A.Id = 123) or
        (@checkbool = 0 and A.Id <> 123)
    
    0 讨论(0)
  • 2021-01-13 01:01

    SQL's equivalent of ! in C is NOT. However, in your case you want something else: you need to build a condition that decides between the two choices based on the value of @checkbool, like this:

    SELECT *
    FROM TableA A
    WHERE (    (@checkbool) AND (A.Id =  123))
       OR ((NOT @checkbool) AND (A.Id <> 123))
    
    0 讨论(0)
提交回复
热议问题