Search code examples
sqlsql-serversyntaxdateadd

SQL Server - Combining a date field, a literal character and a DATEADD value in a case statment


I’ve created a case statement to work in this order.

Determine if it’s a “Priority Escalation”, “Ready for Pickup”, “Waiting for Routing”, ELSE a date range.

The above works if I exclude the ELSE portion of the case statement. If none of the other cases are true, then I need my else statement to produce a Shipment Date plus 2 days added to the Shipment date to give a date range for when a package will be shipped. i.e. 02/15/2016 – 02/17/2016

Select
    Case 
        When datediff (day, sl.[Shipment Date], sl.[Priority Escalation Date]) < 0 then  'Priority Escalation'
        When sh.[On Hold] = 'RFP' then 'Ready for Pickup'
        When sh.[On Hold] = 'WFR' then 'Waiting for Routing'
        Else sl.[Shipment date] + “ – “ + & DateAdd("d", 2, sl.[Shipment Date]) 
    End as 'Expected Value'

This is what the data should look like

Expected Value
02/24/2016 - 02/26/2016
02/24/2016 - 02/26/2016
02/24/2016 - 02/26/2016
02/24/2016 - 02/26/2016
Waiting for Routing
Waiting for Routing
Priority Escalation
Ready for Pickup
Ready for Pickup
Priority Escalation
Priority Escalation
Priority Escalation
Ready for Pickup

Solution

  • You might be running into a conversion error. To fix that, you need to CONVERT your dates to VARCHAR:

    SELECT
        CASE 
            WHEN DATEDIFF (DAY, sl.[Shipment Date], sl.[Priority Escalation Date]) < 0 THEN  'Priority Escalation'
            WHEN sh.[On Hold] = 'RFP' THEN 'Ready for Pickup'
            WHEN sh.[On Hold] = 'WFR' THEN 'Waiting for Routing'
            ELSE CONVERT(VARCHAR(10), sl.[Shipment date], 101) + ' - ' 
                    + CONVERT(VARCHAR(10), DATEADD(DAY, 2, sl.[Shipment Date]), 101) 
        END AS 'Expected Value'