合并条件的where子句中的表达式

时间:2017-05-16 09:02:46

标签: sql sql-server

表有一列名为 Type ,有没有办法合并两个条件在哪里关闭。

基础表

select Amount,Type,IsVisibleToCustomer,Status from LiveCustomerTransaction


declare @Type int=0;

--@Type=1

select * from LiveCustomerTransaction where Type in (1,4,5)

--@Type=2,3

select * from LiveCustomerTransaction where Type=@Type

如果在@type为1时关闭类型1和2,3条件,则只选择1,4,5种类型,当类型为2或3时,则选择2或3。

2 个答案:

答案 0 :(得分:1)

I believe this is what you are looking for:

select * from LiveCustomerTransaction
where ( @Type=1        and Type in (1,4,5) )
or    ( @Type in (2,3) and Type in ( 2,3 ) )

In this, 2 and 3 are interchangable (so Type is not necessarily the same as @Type, both should be either 2 or 3). If you meant it a bit more strict then it becomes this:

select * from LiveCustomerTransaction
where ( @Type=1        and Type in (1,4,5) )
or    ( @Type in (2,3) and Type=@Type      )

答案 1 :(得分:0)

You could try the following query

select * 
from LiveCustomerTransaction 
WHERE (@Type=1 and Type in (1,4,5))
      OR (@Type in (2,3) and Type = @Type)
相关问题