2013-06-18 16 views
0

我们有一个表,其中包含一个DateTime2(7)列,我们试图从该列中取值,并将它们插入到其各自的列数据类型为DateTimeOffset的另一个表中。来源日期是这个样子:不确定如何转换为DateTimeOffset正确

2013-02-28 00:15:49.8270000 
2013-03-11 00:26:38.1270000 

我们希望他们转换成这个样子(假设东部标准时间 - 时间提前一小时就移动3月10日)

2013-02-28 00:15:49.8270000 -05:00 
2013-03-11 00:26:38.1270000 -04:00 

我不是确定如何告诉SQL Server采用源日期,并根据该日期和时间,使用EST时区将其转换为在该日期和时间有效的适当的DateTimeOffset。

我知道ToDateTimeOffset函数,但是,如果我理解正确,我必须提供该函数的偏移值。我希望SQL Server根据我提供的时区(例如,EST)计算出来。

+0

我不认为有什么内置的。你可能不得不求助于SQLCLR。 –

+0

@RichardDeeming - 是的,我很害怕这个。 –

回答

1

对于SQLCLR,这应该相当简单。假设时区总是EST,这样的东西应该工作:

using System; 
using Microsoft.SqlServer.Server; 

namespace SqlUtilities 
{ 
    public static class Dates 
    { 
     private static readonly TimeZoneInfo EST = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); 

     [SqlFunction(
     Name = "ToDateTimeOffset", 
     DataAccess = DataAccessKind.None, 
     IsDeterministic = true, 
     IsPrecise = true 
    )] 
     public static DateTimeOffset? ToDateTimeOffset(DateTime? value) 
     { 
     if (value == null) return null; 

     var source = value.Value; 
     var offset = EST.GetUtcOffset(source); 
     return new DateTimeOffset(source, offset); 
     } 
    } 
}