【问题标题】:making a where clause optional by checking a variable value in a sql statement通过检查 sql 语句中的变量值使 where 子句成为可选
【发布时间】:2020-07-30 22:58:30
【问题描述】:

在 sql 中有一个选项,我可以根据变量值在 select 语句中创建 where 子句可选。 例如:- 如果我有这样的查询。

Declare
@selection int=1
select name,age,department from employee where age > 25

我想让 where 子句仅在 @selection=1 时应用,而在 @selection 是其他东西时不应用。我可以在没有 if 条件的情况下这样做吗?

【问题讨论】:

标签: sql sql-server tsql select where-clause


【解决方案1】:

您可以在where 子句中使用布尔逻辑:

declare @selection int = 1
select name, age, department 
from employee 
where (@selection = 1 and age > 25) or @selection <> 1

【讨论】:

  • 如果@selection 包含一个空值,那么您的查询将不会返回任何行。
【解决方案2】:

您可以使用 OR 来表达该逻辑

select name,age,department 
from employee 
where @selection <> 1 or age > 25

如果@selection 1,则条件的第一部分确保返回所有行,但如果它正好是 1,那么您将检查“age > 25”

我会添加一个 isnull 函数来确保当@selection 包含一个空值时它仍然返回所有行。

select name,age,department 
from employee 
where isnull(@selection, 0) <> 1 or age > 25

【讨论】:

    【解决方案3】:

    如果您的查询很短,您可以复制查询,一个带有 where 语句,一个不带,然后根据变量的值执行它们。像这样:

    Declare @selection int=1
    IF @selection = 1
    BEGIN
     select name,age,department from employee where age > 25
    END
    ELSE
    BEGIN
     select name,age,department from employee
    END
    

    可能有更优雅的解决方案,但如果您赶时间并且不介意重复选择,这将完成工作。

    【讨论】:

    • 我有一个丑陋的长选择查询,所以想得比如果条件可能更好..布尔逻辑很流畅
    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2014-02-16
    • 2015-07-25
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多