Frage

Currently I am using

If @City > 0 then
    SELECT * FROM table1 Where Column1 < @City
ELSE
    SELECT * FROM table1

How can I achieve the same effect in a single query?

War es hilfreich?

Lösung

You simply put the condition in the query:

select *
  from table1
 where ( @city > 0
         and column1 < @city )
    or @city <= 0 

Be warned though; this can confuse the optimizer slightly which might make your first query less performant. As with everything test before implementation.

Andere Tipps

Try this:

select *
  from table1
 where column1 < @city
    or @city <= 0 

One more option

SELECT * 
FROM table1 
WHERE Column1 < CASE WHEN @City > 0 
                     THEN @City 
                     ELSE Column1 + 1 END
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top