0

I am trying to make this a trigger, but so fat this is all I've got:

CREATE TRIGGER trg_SetDateToNextBusinessDay
ON dbo.Orders
AFTER INSERT
AS
    UPDATE dbo.Orders
    SET OrderDateTime = {next  day that is Monday-Friday, 8:00 am}
    WHERE OrderDateTime {is after 4:00} OR OrderDateTime {is on a saturday or sunday}

What is the easiest way to do this?

drewwyatt
  • 5,889
  • 15
  • 56
  • 103

2 Answers2

4

Try this:

CREATE TRIGGER trg_SetDateToNextBusinessDay
ON dbo.Orders
AFTER INSERT
AS
UPDATE dbo.Orders
    SET OrderDateTime = 
                    (CASE DATENAME(DW, OrderDateTime)
                        WHEN 'Friday' THEN DATEADD(DAY, DATEDIFF(DAY, -3, OrderDateTime), '08:00:00') -- if friday, add 3 days
                        WHEN 'Saturday' THEN DATEADD(DAY, DATEDIFF(DAY, -2, OrderDateTime), '08:00:00') -- if saturday add 2 days
                        ELSE DATEADD(DAY, DATEDIFF(DAY, -1, OrderDateTime), '08:00:00') -- on all other days just add one day
                    END) -- {next  day that is Monday-Friday, 8:00 am}
    WHERE DATEPART(HH, OrderDateTime) > 3 OR-- {is after 4:00} (this includes 4:00!)
            DATENAME(DW, OrderDateTime) IN ('Saturday', 'Sunday') -- {is on a saturday or sunday}
martin
  • 279
  • 1
  • 6
1

To check if the date is a Saturday or Sunady I suggest datename.

You can check:

datename("dw", OrderDateTime) in ("Saturday", "Sunday").

You can use datepart to get the hour and check if it is after four.

datepart(hh, OrderDateTime) >= 4

For your set statement you can use a case:

case datename("dw", OrderDateTime) 
when "Saturday" 
then DATEADD(hh, 56,cast(OrderDateTime As Date)) 
when "Friday"
then DATEADD(hh, 80,cast(OrderDateTime As Date))
else DATEADD(hh, 32,cast(OrderDateTime As Date))

In all cases we are getting rid of the time. Then, if it is Saturday, add two days worth of hours to get us to Monday and add an additional eight hours to get us to eight am.

If it is Friday, add three days plus eight hours. Otherwise add a single day plus eight hours.

Vulcronos
  • 3,358
  • 3
  • 15
  • 24