根据变量开启或关闭WHERE子句

时间:2013-12-06 01:07:25

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

您好我正在使用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),目标是让查询选择所有行,但是如果我指定那么它只会为该帐户提供数据。

2 个答案:

答案 0 :(得分:1)

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

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

WHERE account = COALESCE(@specificAccountNumber, account)

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

答案 1 :(得分:1)

您可以在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