使用SQL Server查询将多个选择语句合二为一

时间:2019-06-24 20:06:14

标签: sql sql-server

我想使用以下逻辑在SQL Server数据库中查询一个表:

declare @crntusrdept nvarchar(128)
set @crntusrdept = 'A'

if @crntusrdept includes ('A', 'B', 'C') then (select * from comps where dept in ('A', 'B', 'C'))
if @crntusrdept includes ('D','E') then (select * from comps where dept in ('D','E'))
if @crntusrdept includes ('F', 'G') then (select * from comps where dept in ('F', 'G'))
if @crntusrdept includes ('H') then (select * from comps where dept in ('H'))

1 个答案:

答案 0 :(得分:2)

您可以这样做:

select * 
from comps 
where @crntusrdept in ('A', 'B', 'C') and dept in ('A', 'B', 'C')
   or @crntusrdept in ('D', 'E') and dept in ('D', 'E')
   or @crntusrdept in ('F', 'G') and dept in ('F', 'G')
   or @crntusrdept in ('H') and dept in ('H')