Nesting ifs in where clause to define search values else ignore

时间:2015-07-28 15:45:14

标签: sql-server

I'm bashing my head into a wall it seems. So I have a stored procedure with multiple defined values upon running:

exec dbo.storedprocedure 'Value1', 'Value2', 'Value3','Value4'

I need to have a select statement in the procedure that will search for all of these values (using ands) but if any of them = a particular value ignore them in the search (but still use ands for the rest). I have 12 columns so is there any way I can do this without having to do 'if then else' for every possible combination? I feel like a cursor is needed but am stuck.

example:

SELECT * FROM #MY_Temp_Table
WHERE 
(Column1 = @Value1 only if @Value1 <> 'BaaadValue1' otherwise ignore) and
(Column2 = @Value2 only if @Value2 <> 'BaaadValue2' otherwise ignore) and
(Column3 = @Value3 only if @Value3 <> 'BaaadValue3' otherwise ignore)

1 个答案:

答案 0 :(得分:0)

You can use OR =

SELECT  *
FROM    #MY_Temp_Table
WHERE   (@Value1 = 'BaaadValue1' OR Column1 = @Value1) AND
        (@Value2 = 'BaaadValue2' OR Column2 = @Value2) AND
        (@Value3 = 'BaaadValue3' OR Column3 = @Value3)