微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net – 从SQL 2005 Server访问TimeZoneInfo

.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

原文地址:https://www.jb51.cc/aspnet/251664.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐