SQL函数帮助 - 夏令时计算

时间:2014-12-08 18:52:58

标签: sql sql-server function dst

全部, 我写了一个基本上采用时间戳和购物者ID的函数,并根据购物者的zipcode计算出UTC偏移量并更正时间。

我遇到的问题是:它是懒散的!

有人能看到一种加快速度的简单方法吗?

    CREATE FUNCTION TimeModifier 
    (
        -- Add the parameters for the function here
       @InputDate datetime,@shopperid int
    )
    RETURNS datetime
AS
  BEGIN



--Declare @shopperid int
--set @shopperid=25

    -- Declare the return variable here


    -- Declare the return variable here
    DECLARE @Result datetime
    Declare @zip nvarchar(10)
    Declare @TimeofYear int
    declare @Year int
    declare @Winter int
    declare @Summer int

    select @year=datepart(yyyy,@InputDate)



--If 0 then its outside of the summer hours. 
    SELECT  @timeofyear=count(*)  FROM [d].[dbo].[DST-Dates] where @inputdate>=startdate and @inputdate<=enddate 


    select @zip=zip from d..shopper  where shopperid=@shopperid


    --Gets the UTC offset for winter and summer
  select @winter=winter,@summer=summer FROM [MMD_Feed].[dbo].[ZipCodeZones] where zip=@zip

  if(@TimeofYear=0)--IE is it Winter
  set @Result=DATEADD(HH,@winter, @Inputdate)
  else--Use summer offset 
  set @Result=DATEADD(HH,@summer, @Inputdate)
  --select @Result

        -- Return the result of the function
    RETURN @Result

END
GO

由于 〜Ĵ

1 个答案:

答案 0 :(得分:0)

这是在黑暗中将其转换为iTVF的总镜头。

CREATE FUNCTION TimeModifier 
    (
        -- Add the parameters for the function here
       @InputDate datetime
       , @shopperid int
    )
    RETURNS TABLE WITH SCHEMABINDING
AS RETURN

    select DATEADD(Hour, case when t.TimeOfYear = 0 then z.winter else z.summer end, @InputDate) as MyResult
    from d.dbo.shopper s
    join [MMD_Feed].[dbo].[ZipCodeZones] z on s.zip = z.zip
    cross apply 
    (
        SELECT count(*) as TimeOfYear
        FROM [d].[dbo].[DST-Dates] 
        where @inputdate >= startdate 
            and @inputdate <= enddate 
    ) t
    where s.shopperid = @shopperid