[英]How to add hours to work day in SQL?
I have seen many example adding working date (business days) to date in SQL. 我见过很多在SQL中添加工作日期(工作日)的例子。 But I would like to add hour.
但我想补充一小时。
For example; 例如; I would like to add 36 hour to date not in Sunday , Saturday Could one help me about it ?
我想在星期天,星期六增加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
The following will add N hours to a date (excluding Saturday and Sundays). 以下内容将在日期(周六和周日除外)中添加N小时。
Example 例
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
Returns 返回
2017-05-01 12:00:00.000
is it what you are looking for? 这是你在找什么?
declare @num_hours int;
set @num_hours = 1;
select dateadd(HOUR, @num_hours, getdate()) as time_with_hour;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.