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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....