Pregunta

How to ignore a where condition when the value of a filter is null in one statement?

-- if @filter1LowerBound is null then
select * from MyTable

-- if @filter1LowerBound is not null then
select * from MyTable
where column1 > @filter1LowerBound

Would that be possible to write one single where condition to handle the above situations?

I know I can CASE WHEN statement when my column is using "=".

or like:

select * from MyTable
where column1 = ISNULL(@filter1LowerBound, column1) 

But I am having greater than and less than operators.

I have more greater than and less than filters like that so I'd need to make it work.

How would that be achieved?

Thanks

¿Fue útil?

Solución

How about

select * from MyTable where 
   (@filter1LowerBound is null or column1 > @filter1LowerBound)

Otros consejos

One way is to combine the clauses like so:

SELECT * FROM MyTable 
WHERE (@filter1LowBound IS NULL OR column1 > @filter1LowerBound)
   -- AND other conditions here

Assuming column1 is numeric

select * from MyTable where column1 > ISNULL(@filter1LowerBound, column1-1)
select * from MyTable where column1 < ISNULL(@filter1LowerBound, column1+1) 

Similarly, if it's a string

select * from MyTable where column1 > ISNULL(@filter1LowerBound, '') 

etc

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top