我已经有一个现有的问题,但是即使答案有帮助,我仍然无法解决我的问题。
Exclude weekends and public holiday for SQL datediff
不是使用2 while循环,而是使用1 while循环和更多的IF-ELSE语句,因为我对此更加熟悉。但是,我意识到我应该数数的方式也不同
问题
我认为我的代码将给我7天+时间,但正确的答案应该是6天+时间。我尝试减掉一天的代码,它在某些情况下有效,但在其他情况下失败。
当StartDate大约是14:00 PM而ENDDate是8:00 AM时,获取变量“时间”的奇怪答案。 (开始日期超过ENDDate)
条件:排除(周末和公众假期)(数据库中已存在PH表,代码显示为HolidayTable,此问题已省略)
Declare @numdays int=0
DECLARE @numDaysExclude int = 0
/*1. Calculate only time difference*/
DECLARE @time AS DECIMAL(18,2) = CAST(DATEDIFF(second, CONVERT(time, @StartDate), CONVERT(time, @ENDDate)) as Decimal(18,2))/86400.00
/*2. Calculate only datediff*/
SET @numDays = DATEDIFF(day,@StartDate,@ENDDate)
/*For cases such as (20-12-2017, 1-1-2018)*/
IF DATEDIFF(day,@StartDate,@ENDDate)>0
BEGIN
WHILE DATEDIFF(day,@StartDate,@ENDDate)>0
BEGIN
IF exists (SELECT Holiday_Date FROM Holiday where Holiday_Date=CONVERT(date, @StartDate)) or DATENAME(DW,@StartDate)='saturday' or DATENAME(DW,@StartDate)='sunday'
BEGIN
SET @numDaysExclude = @numDaysExclude +1
END
SET @StartDate = DATEADD(d,1,@StartDate)
END
/*
IF DATENAME(DW,@ENDDate)='sunday'
SET @numDays=@numDays-1 */
DECLARE @result AS DECIMAL(18,2) = (@numDays-@numDaysExclude) + @time
END
/*For cases such as (1-1-2018, 10-12-2017)*/
ELSE IF DATEDIFF(day,@StartDate,@ENDDate)<0
BEGIN
/*Set @time = 1-@time
IF @time > 1
SET @time = CAST(DATEDIFF(second, CONVERT(time, @ENDDate), CONVERT(time, @StartDate)) as Decimal(18,2))/86400.00
IF DATENAME(DW,@ENDDate)='sunday'
SET @numDays=@numDays-1 */
WHILE DATEDIFF(day,@StartDate,@ENDDate)<0
BEGIN
IF exists (SELECT Holiday_Date FROM Holiday where Holiday_Date=CONVERT(date, @ENDDate)) or DATENAME(DW,@ENDDate)='saturday' or DATENAME(DW,@ENDDate)='sunday'
BEGIN
SET @numDaysExclude = @numDaysExclude +1
END
SET @ENDDate = DATEADD(d,1,@ENDDate)
END
SET @result = @numDays + @numDaysExclude + @time
END
RETURN @result
END
有人可以帮忙看看吗?我在这里呆了很长时间,尝试了许多我知道的方法...这对我来说是最容易理解的,因为我不太擅长编程。 谢谢!
[1]: https://i.stack.imgur.com/SOije.jpg