下面的函数计算两个日期之间的总时间减去周末,当两个日期差异超过一天时它可以正常工作,但是在一天之内结果带有负面影响,我真的不明白,任何人都可以解决它?< / p>
ALTER FUNCTION [dbo].[Gettotalhours]
(
@startdate datetime2,@enddate datetime2
)
RETURNS bigint
AS
BEGIN
declare @dateweekends int
declare @totaltime bigint
Set @Dateweekends =
(DATEDIFF(wk, @StartDate, @EndDate) * 2)
+(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
+(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
set @totaltime= DATEDIFF(second,@StartDate,@EndDate)-@dateweekends*24*60*60
return @totaltime
END
答案 0 :(得分:0)
SELECT dbo.Gettotalhours('2012-01-01 22:09:45.000','2012-01-01 22:09:50.000')在您的情况下不起作用,因为 2012-01-01 - 周日所以如果两个参数都有一天出现,你根本不需要计算@Dateweekends:
CREATE FUNCTION [dbo].[Gettotalhours]
(
@startdate datetime2,@enddate datetime2
)
RETURNS bigint
AS
BEGIN
declare @dateweekends int
declare @totaltime bigint
Set @Dateweekends =
(DATEDIFF(wk, @StartDate, @EndDate) * 2)
+(CASE WHEN DATEDIFF(day, @StartDate, @EndDate) > 1 AND DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
+(CASE WHEN DATEDIFF(day, @StartDate, @EndDate) > 1 AND DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
set @totaltime= DATEDIFF(second,@StartDate,@EndDate)-@dateweekends*24*60*60
return @totaltime
END
GO
您可以使用以下测试用例集调试您的函数:
WITH t AS (
SELECT 2 [sec] UNION ALL
SELECT 20 UNION ALL
SELECT 200 UNION ALL
SELECT 2000 UNION ALL
SELECT 20000 UNION ALL
SELECT 200000),
[source] AS (
SELECT DATEADD(second, -t.[sec], GETDATE()) [from], GETDATE() [to]
FROM t)
SELECT *, [dbo].[Gettotalhours]([from], [to]) [result] from [source]
答案 1 :(得分:0)
我改变了我的功能,它对我有用,如果现在正确的话,你们可以看看吗?
ALTER FUNCTION [dbo]。[Gettotalhours] ( @startdate datetime2,@ enddate datetime2 ) 返回bigint 如 BEGIN
声明@dateweekends int 声明@totaltime bigint
如果DATENAME(dw,@ StartDate)在('星期日','星期六') 设置@ dateweekends = 0 其他 设置@Dateweekends = (DATEDIFF(周刊,@ StartDate,@ EndDate)* 2) +(DATENAME(dw,@ StartDate)='星期日'然后1节0结束时的情况) +(DATENAME(dw,@ EndDate)='星期六'然后1节0结束时的情况)
设置@ totaltime = DATEDIFF(第二,@ StartDate,@ EndDate) - @ dateweekends * 24 * 60 * 60
返回@totaltime
END