Datum + 3 Tage / Wochenende überspringen

Mr. Robot

Fleissiger Benutzer
Beiträge
88
Hallo zusammen,

ich möchte für den Start eines Intervalls ERSTELLUNGSDATUM + 3 vornehmen. Wochenende sollen dabei nicht berücksichtigt bzw. übersprungen werden. Wenn ich z.B. folgendes nehme:

CONVERT(DATETIME, [ERSTELLUNGSDATUM], 102)+3

klappt es nur für Montag und Dienstag:

Mo --> Do --> OK
Di --> Fr --> OK
Mi --> Sa --> MÜSSTE MONTAG SEIN
Do --> So --> MÜSSTE DIENSTAG SEIN
Fr --> Mo --> MÜSSTE MITTWOCH SEIN



Vielleicht kann man folgende Funktion anpassen? Für Mittwoch sollte es eigentlich passen aber die Tage ergeben bei mir noch Samstag.

CREATE FUNCTION [dbo].[DAYSADDNOWK](@addDate AS DATE, @numDays AS INT)
RETURNS DATETIME
AS
BEGIN
SET @addDate = DATEADD(d, @numDays, @addDate)
IF DATENAME(DW, @addDate) = 'sunday' SET @addDate = DATEADD(d, 1, @addDate)
IF DATENAME(DW, @addDate) = 'saturday' SET @addDate = DATEADD(d, 2, @addDate)

RETURN CAST(@addDate AS DATETIME)
END
GO
 
Werbung:
ähm, so?

Code:
edb=*> select *, case when extract(dow from d) in (3,4,5) then d+5 else d+3 end as tag from db_neuling;
 id |         d          |        tag         
----+--------------------+--------------------
  1 | 01-APR-21 00:00:00 | 06-APR-21 00:00:00
  2 | 02-APR-21 00:00:00 | 07-APR-21 00:00:00
  3 | 03-APR-21 00:00:00 | 06-APR-21 00:00:00
  4 | 04-APR-21 00:00:00 | 07-APR-21 00:00:00
  5 | 05-APR-21 00:00:00 | 08-APR-21 00:00:00
  6 | 06-APR-21 00:00:00 | 09-APR-21 00:00:00
  7 | 07-APR-21 00:00:00 | 12-APR-21 00:00:00
  8 | 08-APR-21 00:00:00 | 13-APR-21 00:00:00
  9 | 09-APR-21 00:00:00 | 14-APR-21 00:00:00
 10 | 10-APR-21 00:00:00 | 13-APR-21 00:00:00
 11 | 11-APR-21 00:00:00 | 14-APR-21 00:00:00
(11 rows)
 
Danke. Vielleicht der einfachste Weg :)

Da ERSTELLUNGSDATUM + 3 schon in einem CASE WHEN enthalten ist wollte ich eine Verschachtelung mehrerer CASE WHEN Fälle vermeiden. Aber so geht es auch.
 
Danke. Vielleicht der einfachste Weg :)
Da ERSTELLUNGSDATUM + 3 schon in einem CASE WHEN enthalten ist wollte ich eine Verschachtelung mehrerer CASE WHEN Fälle vermeiden. Aber so geht es auch.
Damit gehts.
Code:
declare @startDate as datetime;
declare @endDate as datetime;
declare @numDays as int;


set @startDate = dateadd(d, 7, getdate()) ;
-- set @startDate = getdate();
set @numDays = 3;

select @startDate, datename(weekday, @startDate);

SET @endDate = DATEADD(d, @numDays, @startDate)
IF DATENAME(DW, @endDate) = 'saturday'
  SET @endDate = DATEADD(d, 5, @startDate)
IF DATENAME(DW, @endDate) = 'sunday'
    SET @endDate = DATEADD(d, 4, @startDate)
if datename(dw , @endDate) = 'monday'
    SET @endDate = DATEADD(d, 5, @startDate)

SELECT @endDate, DATENAME(weekday, @endDate) AS Result;
 
Werbung:
Hi,
so was geht auch mit 'nem Einzeiler (ab SQL Server 2012):

Code:
SET @Datum = DATEADD(day, CHOOSE(DATEPART(weekday, @Datum)-FLOOR(@@DATEFIRST / 7.0),3,3,5,5,5), @Datum)

Viele Grüße,
Tommi
 
Zurück
Oben