2

I have a date column in my table. I want to get all the records where the number of months compared to today's date is greater than 10, but I want to apply this condition only if my declared parameter has value @parameter='Apply'. Otherwise, I do not want to enforce the date criteria.

My results should be the 1st, 2nd, and 3rd rows when @parameter ='Apply', else if @parameter is something else, then all four rows would be returned.

  GetDate         Val
------------     -----
 1/12/2013         A
 1/12/2012         B
 1/12/2014         C
 1/12/2015         D

The following works as expected, but with lots of redundant code. Is there way to put the if condition in the where clause ?

DECLARE @parameter VARCHAR(10)='Apply'
if(@parameter='Apply')
begin
select * from testTable where
    DATEDIFF(MONTH,GetDate,GETDATE()) >10
end
else
begin
    select * from testTable
end
1

1 Answer 1

3

This will do the same thing:

select * 
from testTable 
where (DATEDIFF(MONTH,GetDate,GETDATE()) >10 AND @parameter='Apply')
OR @parameter <> 'Apply'
Sign up to request clarification or add additional context in comments.

1 Comment

This will have the same output, but is SQL server smart enough to optimize this in a way that makes sense?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.