将SQL转换为函数

时间:2012-07-25 02:49:10

标签: sql function

我是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

1 个答案:

答案 0 :(得分:1)

假设SQL Server

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')