문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top