如何在SQL中添加工作日的小时数?

时间:2017-04-30 12:09:23

标签: sql sql-server tsql datetime

我见过许多在SQL中添加工作日期(工作日)的示例。但我想补充一小时。

例如;我想在周日,周六增加36小时 有人可以帮我吗?

CREATE FUNCTION AddWorkDays 
(    
    @WorkingDays As Int, 
    @StartDate AS DateTime 
) 
RETURNS DateTime 
AS
BEGIN
    DECLARE @Count AS Int
    DECLARE @i As Int
    DECLARE @NewDate As DateTime 
    SET @Count = 0 
    SET @i = 0 

    WHILE (@i < @WorkingDays) --runs through the number of days to add 
    BEGIN
-- increments the count variable 
        SELECT @Count = @Count + 1 
-- increments the i variable 
        SELECT @i = @i + 1 
-- adds the count on to the StartDate and checks if this new date is a Saturday or Sunday 
-- if it is a Saturday or Sunday it enters the nested while loop and increments the count variable 
           WHILE DATEPART(weekday,DATEADD(d, @Count, @StartDate)) IN (1,7) 
            BEGIN
                SELECT @Count = @Count + 1 
            END
    END

-- adds the eventual count on to the Start Date and returns the new date 
    SELECT @NewDate = DATEADD(d,@Count,@StartDate) 
    RETURN @NewDate 
END
GO

3 个答案:

答案 0 :(得分:2)

以下内容将在日期(周六和周日除外)中添加N小时。

示例

Declare @Date1 datetime = '2017-04-28'
Declare @Hours int  = 36

Select D=max(D)
 From  (
        Select D,HN=-1+Row_Number() over (Order by D)
         From  (Select D=DateAdd(HOUR,-1+Row_Number() Over (Order By (select null)),@Date1) From  master..spt_values n1 ) D
         Where DateName(WEEKDAY,D) not in ('Saturday','Sunday') 
       ) D1
 Where HN=@Hours

<强>返回

2017-05-01 12:00:00.000

答案 1 :(得分:1)

你在找什么?

declare @num_hours int; 
    set @num_hours = 1; 

select dateadd(HOUR, @num_hours, getdate()) as time_with_hour;

答案 2 :(得分:1)

declare @num_hours int; 
set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
   getdate() as curr_date  

此问题已经回答Here