SQLTeam.com | Weblogs | Forums

Use an if or statement


I need a third column checking to see if [Days Late] is greater than 5 or less than -5. If True, "Out of Limits", if false, "Within Limits"

SELECT rtrim(pl.PARTNUMBER) as [Part Number]
, cast(rh.RECV_DATE-pl.DUE_DATE as integer) as [Days Late]

Thanks for your help.


case when cast(rh.RECV_DATE-pl.DUE_DATE as integer) > 5 or cast(rh.RECV_DATE-pl.DUE_DATE as integer) < -5 then 'Out of Limits'
else 'Within Limits'

Are those columns datetime data type? If so, you should be using DATEADD function on them. Which version of SQL Server are you using?


Yes, they are datetime data. I'm using SQL Server 2008 R2


You can use outer apply to tidy up a bit and you can further reference in the select statement if needed.

SELECT rtrim(PARTNUMBER) as [Part Number]
, a.DaysLate as [Days Late]
, case when a.DaysLate > 5 or a.DaysLate < -5 then 'Out of Limits' else 'Within Limits' end as [Check]
from YourTable
outer apply
select cast(RECV_DATE-DUE_DATE as integer)
) a(DaysLate);


I believe that code will break in 2012+ which is why I asked about the version. You have to use date functions going forward.


I thank you both for your suggestions. I have it working now.


I believe it only breaks if you change the data type from datetime to datetime2 - but it would be much better to use date functions anyways to prevent code breaking in a future version when the data type is changed.


yes, it errors if it's datetime2