Andy00001 Andy00001 - 10 months ago 44
SQL Question

SQL: DATEDIFF If Start Date is greater than a date in another field

I'm looking to work out the difference between 2 dates that I have declared as variables,

SET @start_date= '20000728'

SET @end_date= '20161028'

But only if @start_date is greater than DATE_CREATED. If it is not I want to do the difference between DATE_CREATED and @end_date

How can I go about doing this?

All I have at the moment is:

DATEDIFF(DAY, @start_date, @end_date) AS 'DAYS_AVAIL_RANGE'

I'm not sure how I go about incorporating an IF statement to do this,

Any help is appreciated, cheers!

Answer Source

You want case:

select (case when @start_date > date_created
             then datediff(DAY, @start_date, @end_date) 
             else datediff(DAY, date_created, @end_date) 
        end) as days_avail_range