WHERE子句中的多个条件

时间:2011-09-13 14:12:57

标签: sql sql-server sql-server-2008

我必须将一个参数传递给一个条件来选择行,如果我传递0它应该选择所有行,1 - 只有HDD,2 - 除硬盘外的所有行

请参阅代码:

declare @Accessories table (id int, name nvarchar(20), atype nvarchar(20), itype int)

insert into @Accessories values (1, 'Seagate HDD 100GB', 'HDD', 1)
insert into @Accessories values (2, 'Samsung HDD 100GB', 'HDD', 1)
insert into @Accessories values (3, 'WD HDD 500GB', 'HDD', 1)
insert into @Accessories values (4, 'Samsung 4GB', 'RAM', 2)
insert into @Accessories values (5, 'GeForce 512MB', 'Video', 3)

declare @param int

set @param = 1 /* 0 - All records, 1 - Only HDD, 2 - All exclude HDD */

select 
    * 
from @Accessories
where itype = @param /* NEED RIGHT CONDITION HERE*/

我不能像@param = 0那样编写代码然后...... 是否可以在WHERE语句中写入条件?

谢谢!

3 个答案:

答案 0 :(得分:8)

您可以使用以下内容:

select * 
from @Accessories 
where (@Param = 0)
  or (@Param = 1 and atype = 'HDD') 
--or (@Param = 1 and itype = 1) , if itype and atype are connected
  or (@Param = 2 and atype != 'HDD')
option (recompile)

如果Param为0,则第一个条件变为0=0并匹配所有行,因此返回所有行。如果param为1或2,则只有相应或分支在第一个条件上匹配,因此它返回第二个条件指定的内容。

此外,option (recompile)非常重要(查看Martin评论中的文章)。它指示SQL Server在准备执行计划时使用参数的运行时值,基本上是这样的:

  • 当@Param = 0时,查询变为select * from @Accessories
  • 当@Param = 1时,查询变为select * from @Accessories where atype = 'HDD'
  • 当@Param = 2时,查询变为select * from @Accessories where atype != 'HDD'

答案 1 :(得分:2)

WHERE itype BETWEEN @param AND CASE 
    WHEN @param = 1 THEN 1
    ELSE 2000000000 END
OPTION (RECOMPILE); -- thanks for the reminder @Martin

答案 2 :(得分:0)

declare @Accessories table (id int, name nvarchar(20), atype nvarchar(20))

insert into @Accessories values (1, 'Seagate HDD 100GB', 'HDD')
insert into @Accessories values (2, 'Samsung HDD 100GB', 'HDD')
insert into @Accessories values (3, 'WD HDD 500GB', 'HDD')
insert into @Accessories values (4, 'Samsung 4GB', 'RAM')
insert into @Accessories values (5, 'GeForce 512MB', 'Video')

declare @param int

set @param = 0 /* 0 - All records, 1 - Only HDD, 2 - All exclude HDD */

if(@param =0)
begin
select * from @Accessories
end
if(@param =1)
begin
select * from @Accessories where atype in ('HDD')
end
if(@param =2)
begin
select * from @Accessories where atype not in('HDD')
end