0

私はSQLを初めて使用しますが、次のSQLステートメントを関数に変換するのを手伝ってください。このステートメントは機能します。これから関数を作成することはできません。

declare @start datetime, @end datetime
set @start = '2012/07/25 09:00:00'
set @end = '2012/07/25 12:55:00';

with weeks as (
  select @start as WeekStart
    , dateadd(hh, 24, dateadd(dd, 0, datediff(dd, 0, dateadd(dd, 6 - (@@datefirst + datepart(dw, @start)) % 7, @start)))) as WeekEnd
union all
  select dateadd(hh, 48, WeekEnd)
    , dateadd(hh, 24, dateadd(dd, 0, datediff(dd, 0, dateadd(dd, 13 - (@@datefirst + datepart(dw, WeekEnd)) % 7, WeekEnd)))) as WeekEnd
  from weeks
  where dateadd(hh, 48, WeekEnd) <= @end
)
select Seconds / (60 * 60) as Hours
from (
  select sum(datediff(ss, WeekStart, case when @end < WeekEnd then @end else WeekEnd end)) as Seconds
  from weeks) x
4

1 に答える 1

1

SQLServerを想定

create function CalculateHours
(
    @Start datetime,
    @End datetime
) returns int
as
begin
    declare @Hours int
    ;with weeks as (
      select @start as WeekStart
        , dateadd(hh, 24, dateadd(dd, 0, datediff(dd, 0, dateadd(dd, 6 - (@@datefirst + datepart(dw, @start)) % 7, @start)))) as WeekEnd
    union all
      select dateadd(hh, 48, WeekEnd)
        , dateadd(hh, 24, dateadd(dd, 0, datediff(dd, 0, dateadd(dd, 13 - (@@datefirst + datepart(dw, WeekEnd)) % 7, WeekEnd)))) as WeekEnd
      from weeks
      where dateadd(hh, 48, WeekEnd) <= @end
    )
    select @Hours = Seconds / (60 * 60)
    from (
      select sum(datediff(ss, WeekStart, case when @end < WeekEnd then @end else WeekEnd end)) as Seconds
      from weeks) x

      return @Hours
end

使用例:

select dbo.CalculateHours('2012/07/25 09:00:00','2012/07/25 12:55:00')
于 2012-07-25T03:16:49.680 に答える