tags:

views:

51

answers:

2

I have the following columns in the database. AgreedStartDate, ActualStartDate. I need to apply the following logic: When the AcualStartDate is within the SAME business week as the AgreedStartDate, then it is 'inside' the SLA. If this is not the case then it is 'outside' the SLA. If either of the two columns is NULL, then it is 'incomplete'. There must be a simple solution to this, please help!

+2  A: 

A simple CASE statement? You don't need to use variables, you can just reference your column names instead. I just used variables for a complete statement.

DECLARE @agreedStartDate DATETIME
DECLARE @actualStartDate DATETIME

SET @agreedStartDate = GETDATE()
SET @actualStartDate = GETDATE()

SELECT
 CASE
  WHEN
   @agreedStartDate IS NULL
   OR
   @actualStartDate IS NULL
  THEN
   'Incomplete'
  WHEN
   DATEPART(wk, @agreedStartDate) = DATEPART(wk, @actualStartDate)
   AND
   DATEPART(yyyy, @agreedStartDate) = DATEPART(yyyy, @actualStartDate)
  THEN
   'Inside'
  ELSE
   'Outside'
 END
Robin Day
Might need some tweaking depending on your interpretation of a "business week". Otherwise, park it on top of a FROM clause, and you should be good.
Philip Kelley
I don't get the DATEPART function, how does this resolve the scenario of both columns having being contained in the SAME working week i.e. Monday-Friday. i.e. if the agreed start date is today 30 Nov, the actual start date has to be 4 Dec at latest, to be within SLA.
jeff
In regard to "business week" you can use SET DATEFIRST = 1 etc so indicate what your "start date" of a week is. However, in generaly you should try and keep this valid for you current server default rather than setting it for an individual query.
Robin Day
Where would i fit set datefirst in to the query? I don't know how to use this...
jeff
I consider DATEFIRST to be one of those "SET" settings that you set once and never touch again. It is best *if* you can rely on it always being the same thing no matter who what where when why connects to the database.
Philip Kelley
A: 

In SQL Server, you can use a CASE statement like:

select case 
    when ActualStateDate is null or AgreedStartDate is null then 'Incomplete'
    when datepart(wk,ActualStateDate) = datepart(AgreedStartDate) then 'Inside'
    else 'Outside'
    end as ColumnName
from YourTable
Andomar