我有一项任务是创建T-SQL函数以添加12小时的当前日期和时间,但它不应包括任何假期/周末。
ALTER FUNCTION [dbo].[GetNextWorkingDay_Custom] (@givenDate DATETIME)
RETURNS DATE
AS
BEGIN
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
DECLARE @DiffDate INT
DECLARE @workingDate DATETIME
IF (DATENAME(dw , @givenDate) = 'Friday')
BEGIN
SET @workingDate = DATEADD(day, 3, @givenDate)
END
ELSE IF (DATENAME(dw , @givenDate) = 'Saturday')
BEGIN
SET @workingDate = DATEADD(day, 2, @givenDate)
END
ELSE
BEGIN
SET @workingDate = DATEADD(day, 1, @givenDate)
END
SELECT @StartDate = START_DATE
,@EndDate = END_DATE
FROM special_time WHERE START_DATE = @workingDate AND IS_HOLIDAY = 1
-- Select count(*) from tblHolidays where holdate = @workingDate
while ((select count(*) from special_time WHERE START_DATE = @workingDate AND IS_HOLIDAY = 1) > 0)
begin
set @DiffDate = DATEDIFF(day,@StartDate,@EndDate)
set @workingDate = dateadd(dd,@DiffDate,@WorkingDate)
end
-- if adding a day makes it a Saturday, add 2 more to get to Monday (and test to make sure the week doesn't start with a holiday)
IF (DATENAME(dw , @workingDate) = 'Saturday')
BEGIN
SET @workingDate = DATEADD(day, 2, @workingDate)
END
RETURN @workingDate
END
答案 0 :(得分:0)
创建静态日期查找表(您可以通过Google找到许多指导,例如https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/),然后添加一个表示该日期是工作日还是假日的列
您的功能就像:
select min(DateValue) as NextWorkingDay
from DatesLookupTable
where DateValue > @GivenDate
and WorkingDay = 1