0

下面的函数计算两个日期之间的总时间减去周末,当两个日期相差超过一天时它工作正常,但在一天之内结果是负面的,我不太明白,任何人都可以解决它?

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
4

2 回答 2

0

我稍微改变了我的功能,它对我有用,你们可以看看,如果它现在正确吗?

ALTER FUNCTION [dbo].[Gettotalhours] (@startdate datetime2,@enddate datetime2) 返回 bigint 作为开始

声明@dateweekends int 声明@totaltime bigint

if DATENAME(dw, @StartDate) in ('Sunday','Saturday') set @dateweekends=0 else 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)

设置@totaltime= DATEDIFF(秒,@StartDate,@EndDate)-@dateweekends*24*60*60

返回@totaltime

结尾

于 2013-03-14T14:16:46.770 回答
0

SELECT dbo.Gettotalhours('2012-01-01 22:09:45.000','2012-01-01 22:09:50.000')在你的情况下不起作用,因为2012-01-01 - Sunday 所以你不需要如果两个参数都出现一天,则完全计算@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

SQL小提琴

您可以使用如下测试用例集调试您的函数:

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]
于 2013-03-13T18:54:04.473 回答