【问题标题】:WHERE clause on or off depending on variableWHERE 子句根据变量打开或关闭
【发布时间】:2013-12-06 01:07:24
【问题描述】:

您好,我使用的是 SQL Server 2008 R2。想做以下事情:

declare
    -- only one of these @ vars will be used
    @specificAccountNumber int = NULL
    @specificAccountNumber int = 123456


select
    account
    ,accountinfo1
    ,accountinfo2
from tableA
where
    if @specificAccountNumber is NULL
    then use the whole table
    else /* @specificaAccountNumber is not null */
    account = @specificAccountNumber


select
    account
    ,accountinfo3
    ,accountinfo4
from tableB
where
    if @specificAccountNumber is NULL
    then use the whole table
    else /* @specificAccountNumber is not null */
    account = @specificAccountNumber

如果我没有指定帐号(或将 @specificAccountNumber 设置为 NULL),则目标是查询选择所有行,但如果我指定了,那么它只会为该帐号带来数据。

【问题讨论】:

  • 任何答案都解决了您的问题吗?如果是这样,请考虑接受它。如果没有,我建议发布您自己的答案。 (StackOverflow 会让您在几天后接受自己的答案。)

标签: sql-server-2008-r2 global-variables where-clause case-when


【解决方案1】:

在应用程序中使用不同的 where 子句发送不同的查询将是处理此问题的最佳方式。

但是,如果它必须在数据库中完成,我认为COALESCE 将适用于这种特殊情况。试试这个:

WHERE account = COALESCE(@specificAccountNumber, account)

COALESCE 在其输入列表中选择第一个非NULL 条目。如果@specificAccountNumberNULL,则应该将account 列与其自身进行比较。我不确定这是否会在指定 @specificAccountNumber 时影响性能。如果tableA 在生产中会很大,你应该检查查询计划。

【讨论】:

  • 谢谢。这是将表中的帐号与其自身进行比较的一个很好的解决方案。完全想不到。我正在针对多个生产表运行此脚本文件。我正在做的一件事是使用 object_id 子句和 @testing 变量来控制将数据选择到临时表中。我还想在完整故事和特定帐户之间轻松切换,以用于 QA 目的。
  • @VISQL 如果这在性能方面不起作用,您可以只使用运行 2 个不同查询的 if/else 块。
【解决方案2】:

你可以在类似这样的 where 子句中使用 case 语句

declare
    -- only one of these @ vars will be used
    @specificAccountNumber int = NULL
    @specificAccountNumber int = 123456


select
    account
    ,accountinfo1
    ,accountinfo2
from tableA
where account = CASE 
                    WHEN  @specificAccountNumber IS NULL THEN account 
                    ELSE @specificAccountNumber END

【讨论】:

  • 谢谢。这是一个很好的解决方案,可以将表中的帐号与其自身进行比较。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2019-07-30
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多