加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 从SQL 2005 Server访问TimeZoneInfo

发布时间:2020-12-16 00:11:48 所属栏目:asp.Net 来源:网络整理
导读:.NET TimeZoneInfo类非常棒,我认为它可以解决我在SQL 2005数据库中记录来自多个时区的数据的所有问题. 要将数据库中的UTC日期时间转换为任何其他时区,我只需使用TimeZoneInfo.FindSystemTimeZoneById()将时区转换为TimeZoneInfo类,然后调用TimeZoneInfo.Conv
.NET TimeZoneInfo类非常棒,我认为它可以解决我在SQL 2005数据库中记录来自多个时区的数据的所有问题.

要将数据库中的UTC日期时间转换为任何其他时区,我只需使用TimeZoneInfo.FindSystemTimeZoneById()将时区转换为TimeZoneInfo类,然后调用TimeZoneInfo.ConvertTimeFromUtc().辉煌!我只是从SQL .NET CLR中调用它!

但是…… TimeZoneInfo的主机保护属性为MayLeakOnAbort.

当我使用VS 2008创建SQL函数或存储过程时,我甚至看不到system.TimeZoneInfo类永远不会使用它.我还假设即使我可以以某种方式引用TimeZoneInfo类,如果我尝试在SQL Sever 2005中注册程序集,我可能会得到某种安全性异常.

帮帮我!有没有办法从SQL Server 2005访问TimeZoneInfo类及其所有的财富?

注意:我刚刚在第一个答案后添加了这个警告:

我们在世界各地都有网站.我们需要在数据库中存储本地时间和UTC时间,以防止可能需要在站点级别进行趋势分析的事件.趋势可能包含一年超过52,000个数据点,因此,为了提高效率,我不能只在数据库中存储UTC时间并转换客户端上的每个数据点.因此,我需要能够在DB内将任何时区的本地时间转换为UTC时间和从UTC时间转换.

解决方法

我刚刚在SQL 2008数据库上完成了这个.

首先,我必须将数据库设置为值得信任并验证所有者是否正确.

use [myDB]
go
alter database [myDB] set trustworthy on
go

exec sp_changedbowner 'sa'
go

接下来,我创建了一个.NET解决方案

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.Collections.ObjectModel
Imports System.Runtime.InteropServices

Partial Public Class StoredProcedures
    <Microsoft.SqlServer.Server.SqlProcedure()> _
    Public Shared Sub sp_ConvertTime(ByVal UTCTime As DateTime,ByVal ZoneID As String,<Out()> ByRef Output As DateTime)
    Dim sp As SqlPipe = SqlContext.Pipe

    Dim ConvertedTime As DateTime
    Dim tzUTC = TimeZoneInfo.FindSystemTimeZoneById("UTC")
    Dim tzNew = TimeZoneInfo.FindSystemTimeZoneById(ZoneID)

    ConvertedTime = TimeZoneInfo.ConvertTime(UTCTime,tzUTC,tzNew)

    Output = ConvertedTime
    sp.Send(ConvertedTime)

    ConvertedTime = Nothing
    tzUTC = Nothing
    tzNew = Nothing
    sp = Nothing

End Sub
End Class

在部署之前,我将权限级别设置为“不安全”.

接下来我部署了它,我检查了输出窗口中的构建错误并更正了这些错误.

这是SQL测试

DECLARE @UTCTime datetime
DECLARE @ZoneID varchar(21)
DECLARE @NewTime datetime

SET @UTCTime = GETUTCDATE()
SET @ZoneID = 'Central Standard Time'

exec sp_ConvertTime @UTCTime,@ZoneID,@NewTime OUTPUT
select @NewTime AS NewTime

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读