SQL:我可以否定 where 子句中的条件吗? [英] SQL: Can I negate a condition in a where clause?

查看:28
本文介绍了SQL:我可以否定 where 子句中的条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个布尔值是否为真,然后在 WHERE 子句中决定使用什么条件.

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

假设布尔变量是@checkbool:

Say the boolean variable is @checkbool:

SELECT *
FROM TableA A
WHERE
    --if @checkbool is true, run this
    A.Id = 123

    --if @checkbool is false, run this
    A.Id <> 123

有没有办法否定条件?就像在 C++ 中一样,你可以这样做 if !(condition).

Is there a way to negate a condition? Like in C++ you can do if !(condition).

如果不是,解决这个问题的最佳方法是什么?

If not, what is the best way to solve this problem?

谢谢!

推荐答案

SQL 中的 ! 在 C 中的等价物是 NOT.但是,在您的情况下,您还需要其他东西:您需要构建一个条件,根据 @checkbool 的值在两个选择之间做出决定,如下所示:

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))

这篇关于SQL:我可以否定 where 子句中的条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆