I have to pass a parameter into a condition to select rows, if I pass 0 it should select all rows, 1 - only HDD, 2 - All except HDD
Please see code:
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*/
I can't write code like if @param = 0 then ... Is it way to write condition in WHERE statement?
Thanks!
You could use something like this:
If Param is 0 the first condition becomes
0=0
and matches for all rows, so all rows are returned. If param is 1 or 2, only the respective or branch matches on the first condition, so it returns what the second condition specifies.Also, the
option (recompile)
is really important (view the article in Martin's comment). It instructs SQL server to use the runtime values of the parameters when preparing an execution plan, so basically:select * from @Accessories
select * from @Accessories where atype = 'HDD'
select * from @Accessories where atype != 'HDD'