martes, 15 de abril de 2014

Calculate days off

COPY THIS INTO SQL SERVER

--TABLE


SET ANSI_NULLS ON

GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ETL_Days_Off](
[DayOffID] [int] IDENTITY(1,1) NOT NULL,
[DayOff] [date] NOT NULL,
 CONSTRAINT [PK_ETL_DAYS_OFF] PRIMARY KEY CLUSTERED 
(
[DayOffID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

--DATA


DayOffID DayOff

1 2014-04-17
3 2014-04-18

--FUNCTION


IF OBJECT_ID (N'dbo.NextAvailableDay', N'FN') IS NOT NULL

    DROP FUNCTION dbo.NextAvailableDay;
GO
CREATE FUNCTION dbo.NextAvailableDay (@Date datetime)
RETURNS DATETIME
WITH EXECUTE AS CALLER
AS
BEGIN
     
DECLARE @OK BIT = 0

WHILE (@OK = 0)

BEGIN

SELECT @Date = @Date + 1


IF ((SELECT COUNT(1) FROM ETL_Days_Off WHERE DayOff = @Date) = 0

AND (SELECT DATEPART(DW, @Date)) <> '6'  --SABADO
AND (SELECT DATEPART(DW, @Date)) <> '7') --DOMINGO
SELECT @OK = 1

END


     RETURN(DATEADD(HOUR,9,@Date));

END;
GO

--CALL

SET DATEFIRST 1;
SELECT dbo.NextAvailableDay(CONVERT(DATETIME,'04/16/2014',101)) AS 'ISO Week';