iho*_*rko 3 sql sql-server sql-server-2008
我必须将一个参数传递给一个条件来选择行,如果我传递0它应该选择所有行,1 - 只有HDD,2 - 除了HDD以外的所有行
请看代码:
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*/
Run Code Online (Sandbox Code Playgroud)
我不能像@param = 0那样编写代码然后......是否可以在WHERE语句中写入条件?
谢谢!
你可以使用这样的东西:
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)
Run Code Online (Sandbox Code Playgroud)
如果Param为0,则第一个条件变为0=0
并匹配所有行,因此返回所有行.如果param为1或2,则只有相应或分支在第一个条件上匹配,因此它返回第二个条件指定的内容.
此外,这option (recompile)
非常重要(查看Martin评论中的文章).它指示SQL Server在准备执行计划时使用参数的运行时值,所以基本上:
select * from @Accessories
select * from @Accessories where atype = 'HDD'
select * from @Accessories where atype != 'HDD'
归档时间: |
|
查看次数: |
4703 次 |
最近记录: |