QUERY TIEMPO ENTRE FECHAS CONSIDERANDO HORARIO Y FERIADOS
Estimados, hace unos días me vi en la necesidad de crear una función para calcular el tiempo entre dos fechas, teniendo las siguientes consideraciones:
- Horario laborable (9 - 6)
- Feriados (Tabla con un solo campo de fechas feriado)
Estuve buscando por toda la web pero no encontré nada, por ello veo conveniente compartirlo, espero les sea de gran ayuda.
El procedimiento es ver el paso del tiempo como un camino y a medida que avanzamos en el camino variar "la posición" que en nuestro caso sería el tiempo y al final darle un ajuste. Ahí les va!
CREATE FUNCTION segundos_entre_dos_fechas
( @FechaInicial datetime,
@FechaFinal datetime )
RETURNS INT
AS
BEGIN
DECLARE @varfecha DATETIME
DECLARE @tiempo_inicial int
DECLARE @aux_tmp int
SET @varfecha = @FechaInicial
SET @tiempo_inicial = datediff(second,@FechaInicial,@FechaFinal)
WHILE (datediff(second,@varfecha,@FechaFinal) )>0
BEGIN
IF (DATEPART(dw,@varfecha) IN (1,7)) OR (CONVERT(date,@varfecha) in (select * from Tbl_Feriados))
BEGIN
SET @aux_tmp = datediff(second,@varfecha,dateadd(hh,24,convert (datetime, convert(date,@varfecha)))
SET @tiempo_inicial = @tiempo_inicial - @aux_tmp ;
SET @varfecha = dateadd(hh,24,convert (datetime, convert(date,@varfecha))) ;
END
ELSE
BEGIN
IF @varfecha < dateadd(hh,9,convert (datetime, convert(date,@varfecha)))
BEGIN
SET @aux_tmp = datediff(second,@varfecha,dateadd(hh,9,convert (datetime, convert(date,@varfecha))));
SET @tiempo_inicial = @tiempo_inicial - @aux_tmp;
SET @varfecha = dateadd(hh,9,convert (datetime, convert(date,@varfecha)));
END
ELSE
BEGIN
IF @varfecha < dateadd(hh,18,convert (datetime, convert(date,@varfecha)))
BEGIN
SET @aux_tmp = 0;
SET @tiempo_inicial = @tiempo_inicial - @aux_tmp;
SET @varfecha = dateadd(hh,18,convert (datetime, convert(date,@varfecha)));
END
ELSE
BEGIN
SET @aux_tmp = datediff(second,@varfecha,dateadd(hh,24+9,convert (datetime, convert(date,@varfecha))));
SET @tiempo_inicial = @tiempo_inicial - @aux_tmp;
SET @varfecha = dateadd(hh,24+9,convert (datetime, convert(date,@varfecha)));
END
END
END
END
IF @aux_tmp <> 0
BEGIN
SET @tiempo_inicial = @tiempo_inicial + datediff(second,@FechaFinal,@varfecha);
END
RETURN @tiempo_inicial
END
Comentarios
Publicar un comentario