【问题标题】:SQL Function help- Daylight Savings calculationSQL 函数帮助 - 夏令时计算
【发布时间】:2015-02-06 12:20:45
【问题描述】:

所有, 我编写了一个函数,它基本上需要一个时间戳和一个购物者 ID,并根据购物者的邮政编码计算出 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

谢谢 ~J

【问题讨论】:

  • 您目前有哪些索引?
  • 邮政编码表和夏令时日期表都有索引
  • 我真的要请你告诉我它们的结构是什么吗?
  • 这个东西是标量函数。他们是出了名的表现不佳。这看起来可以很容易地转换为内联表值函数,这将有助于提高性能。不过要小心……如果您的函数有超过 1 个语句,您的性能实际上可能更差。给我一点,我想我可以做到这一点。

标签: sql sql-server function dst


【解决方案1】:

这是在黑暗中将其转换为 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

【讨论】:

  • 肖恩-非常感谢您的帮助!
猜你喜欢
  • 2013-01-20
  • 2013-11-24
  • 2011-05-07
  • 2017-07-11
  • 2016-08-02
  • 2018-06-15
  • 1970-01-01
  • 2011-03-13
  • 2011-08-01
相关资源
最近更新 更多