创建用于在SQL Server中转换时区的函数

时间:2015-02-24 09:42:09

标签: sql sql-server sql-server-2008-r2

这是我的代码,它的工作正常

CREATE FUNCTION [dbo].[udf_ConvertfromUTCtoCET]
    (@UTCDate AS DATETIME2(7))
RETURNS DATETIME2(7)
AS
BEGIN
    DECLARE @DstStart datetime2(7)
    DECLARE @DstEnd datetime2(7)
    DECLARE @CetDate datetime2(7)

    SELECT 
        @DstStart = DATEADD(hour, 1,DATEADD(day, DATEDIFF(day, 0, '31/Mar' + CAST(YEAR(@UTCDate) AS varchar)) - 
        (DATEDIFF(day, 6, '31/Mar' + CAST(YEAR(@UTCDate) AS varchar)) % 7), 0)),
        @DstEnd = DATEADD(hour, 1,DATEADD(day, DATEDIFF(day, 0, '31/Oct' + CAST(YEAR(@UTCDate) AS varchar)) - 
        (DATEDIFF(day, 6, '31/Oct' + CAST(YEAR(@UTCDate) AS varchar)) % 7), 0))

    SELECT 
       @CetDate = CASE 
                     WHEN @UTCDate <= @DstEnd AND @UTCDate >= @DstStart
                       THEN DATEADD(hour, +2, @UTCDate)
                       ELSE DATEADD(hour, +1, @UTCDate) 
                  END

    RETURN @CetDate
END


select 
    [DateTime] AS UTC,
    [dbo].[udf_ConvertfromUTCtoCET] ([DateTime]) AS CET 
from 
    WarehouseMgmt.DimTime

现在我想在函数中添加另一个参数,如

CREATE FUNCTION [dbo].[udf_ConvertfromUTCtoCET] 
   (@UTCDate AS DATETIME2(7), @TimeZone nvarchar(5))

我不仅仅是从UTC到CET,但如果我想要,我会在@TimeZone参数中加入例如&#39; BST&#39; (英国夏令时)或其他时区,我的UTC时间将在该区域转换

0 个答案:

没有答案