从SQL Server获取时区键名的最佳方法


8

以下是我拼凑而成的内容,但我想看看还有哪些其他可用的方法。

SET NOCOUNT ON;
GO
DECLARE @tz VARCHAR(50)
EXEC [master].[dbo].[xp_regread]
    'HKEY_LOCAL_MACHINE'
    ,'SYSTEM\CurrentControlSet\Control\TimeZoneInformation'
    ,'TimeZoneKeyName'
    ,@tz OUT;

SELECT 
    GETDATE()
    ,'(' + LEFT(PARSENAME(REPLACE(@tz, ' ','.'),3),1) 
    + '' + LEFT(PARSENAME(REPLACE(@tz, ' ','.'),2),1) 
    + '' + LEFT(PARSENAME(REPLACE(@tz, ' ','.'),1),1) +')'

输出:2014-10-14 16:22:21.037(CST)


您的目标是获取服务器的时区?
Erik

Answers:


4

用此或SQLCLR读取reg键是我知道的唯一正确方法(我个人将创建一个更新表的作业,而不是启用xp_regread。)。

该powershell脚本是如何使用此信息更新配置表的示例。

$timeZone = (get-itemproperty 'HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\').TimeZoneKeyName

$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server=.;database=myDatabase;trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = "
        MERGE ConfigTable AS target
        USING (SELECT 'TimeZone', @timeZone) AS source (ConfigKey, ConfigValue)
        ON (target.ConfigKey = source.ConfigKey)
        WHEN MATCHED THEN UPDATE SET ConfigValue = source.ConfigValue
        WHEN NOT MATCHED THEN INSERT (ConfigKey, ConfigValue) VALUES (source.ConfigKey, source.ConfigValue)" 
$command.Parameters.AddWithValue("@timeZone", $timeZone)
$Command.ExecuteNonQuery()
$Connection.Close()

具有偏移量等的所有其他系统给出的结果都不正确。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.