Sql server 2008 r2 WHERE子句on或off取决于变量
您好,我正在使用SQL server 2008 R2。希望执行以下操作:Sql server 2008 r2 WHERE子句on或off取决于变量,sql-server-2008-r2,global-variables,where-clause,case-when,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
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),则查询的目标是选择所有行,但如果我指定了,则只会为该帐号带来数据。在应用程序中使用不同的where子句发送不同的查询将是处理此问题的最佳方法 但是,如果必须在数据库中执行,我认为
COALESCE
将适用于这种特殊情况。试试这个:
其中account=COALESCE(@specificcountnumber,account)
COALESCE
在其输入列表中选择第一个非空的条目。如果@specificcountnumber
为NULL
,则应将帐户
列与其自身进行比较。当指定@specificcountnumber
时,我不确定这是否会影响性能。如果tableA
将在生产中大量使用,您应该检查查询计划。您可以在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
非常感谢。这是一个很好的解决方案,可以将表中的帐号与其自身进行比较。谢谢。将表中的帐号与其自身进行比较是一个很好的解决方案。我完全想不到。我正在对几个生产表运行这个脚本文件。我正在做的一件事是使用object_id子句和@testing变量来控制将数据选择到临时表中。出于qa目的,我还想在完整故事和特定帐户之间轻松切换。@VISQL如果这在性能方面不起作用,您可能只需要使用一个If/else块来运行两个不同的查询。有任何答案可以解决您的问题吗?如果是的话,请考虑接受。如果没有,我建议你发表自己的答案。(StackOverflow会让您在几天后接受自己的答案。)