admin

SQL Server在另一个时区中指定时间

sql

我想编写一个查询,使其仅在英国时间下午2点之后才返回结果。我也知道,美国东部标准时间(EST)到伦敦的时间目前偏移5个小时。我怎样才能做到这一点?

select *
from table
where blah blah
and 2pm UK time < GETDATE()

阅读 171

收藏
2021-06-07

共1个答案

admin

由于夏令时可能会影响英国时区,因此建议您建立一个DST表,并使用该表创建日期。

此解决方案引用了本文:http :
//www.mssqltips.com/sqlservertip/3173/handle-conversion-between-time-zones-
in-sql-server–part-1/

创建表:

CREATE TABLE dbo.TZCalendar
(
  [Year]        Int PRIMARY KEY,
  UTC_DST_Start SMALLDATETIME NOT NULL,
  UTC_DST_End   SMALLDATETIME NOT NULL,
  ET_DST_Start  AS CONVERT(SMALLDATETIME,DATEADD(HOUR, -4, UTC_DST_Start)),
  ET_DST_End    AS CONVERT(SMALLDATETIME,DATEADD(HOUR, -5, UTC_DST_End))
);

SET DATEFIRST 7;
;WITH cte(d,p) AS 
(
  -- all the years from 2000 through 50 years after the current year:
  SELECT TOP (YEAR(GETDATE())-2000+51) DATEADD(YEAR,number,'20000101'),
    CASE WHEN number < 7 THEN 1 ELSE 0 END -- year < 2007 = 1, else 0
    FROM [master].dbo.spt_values WHERE [type] = N'P' ORDER BY number
)
INSERT dbo.TZCalendar([Year],UTC_DST_Start,UTC_DST_End)
SELECT Year(d),
 -- First Sunday in April (< 2007) or second Sunday in March (>= 2007):
 DATEADD(HOUR, 7, DATEADD(DAY,(7-DATEPART(WEEKDAY,DATEADD(MONTH,2+p,d))+1)%7
    +(7*ABS(p-1)),DATEADD(MONTH,2+p,d))),
 -- Last Sunday in October (< 2007) or first Sunday in November (>= 2007):
 DATEADD(HOUR, 6, DATEADD(DAY,(7-DATEPART(WEEKDAY,DATEADD(MONTH,10,d))+1)%7
    -(7*p),DATEADD(MONTH,10,d)))
FROM cte
ORDER BY d;

接下来,我将创建一个函数来提取当前的英国时间:

Create Function dbo.fnGetUKTime()
Returns DateTime
As Begin
    Declare @London DateTime = GetUTCDate()

    Declare @Offset Int = 0

    Select  @Offset = Case When @London Between UTC_DST_Start And UTC_DST_End Then 1 Else 0 End
    From    dbo.TZCalendar
    Where   Year = Year(@London)

    Set @London = DateAdd(Hour, @Offset, @London)

    Return @London
End
Go

然后,您可以在查询中引用它:

select *
from table
where blah blah
and DatePart(Hour, dbo.fnGetUKTime()) > 14
2021-06-07