首页 > 解决方案 > 使用 T-SQL 转换 AD 时间戳

问题描述

如何将 Windows NT 时间从 SQL 查询提取转换为可读格式?我正在对用户帐户进行 AD 提取,并且我想将 Windows AD 时间戳转换或转换为更好的可读格式。问题是我在进行拉动时进行转换时遇到问题。

询问:

SELECT
  CASE
    WHEN CHARINDEX('@', userPrincipalName) > 7
      THEN SUBSTRING(userPrincipalName, 1, (CHARINDEX('@', userPrincipalName)) - 1)
    ELSE ''
  END AS edipi
 ,UPPER(samaccountname) AS samaccountname
 ,givenName AS firstName
 ,sn AS lastName
 ,initials
 ,UPPER(mail) AS email
 ,userAccountControl
 ,telephoneNumber
 ,title
 ,accountExpires
FROM
  OPENQUERY
    (ADSI
     ,'select 
          givenName, 
          samaccountName, 
          userPrincipalName, 
          sn, 
          initials, 
          mail, 
          userAccountControl, 
          telephoneNumber, 
          title, 
          accountExpires
        from ''LDAP PATH''
        where objectcategory=''person'' and objectclass = ''user'' and name=''*'' '
    );

我的查询在 Windows NT 时间返回 accountExpires 字段,但我希望它是这样的:

2020-02-09 15:23:36.367

而不是这个:

132257354163700000

我想出了一个简单的解决方案,逐个进行转换,但我希望它在拉取时执行 CAST,而不是必须为每个用户执行此操作

DECLARE @accountExpired BIGINT
SET @accountExpired = 132257354163700000; --This is a random time pulled from a user from the above select statement.

SELECT CAST((@accountExpired / 864000000000.0 - 109207) AS DATETIME);

标签: sqlsql-servertsql

解决方案


这对我来说适用于 AD 中的每个用户。

CAST((convert(bigint, lastlogontimestamp) / 864000000000.0 - 109207) AS DATETIME) as lastLogonTimestamp,

-- 为了克服日期时间转换为大或小为空的限制,当 convert(bigint, accountexpires) = 0 then null when convert(bigint, accountexpires) > 2650467743999999716 then null else CAST((convert(bigint, accountexpires) / 864000000000.0 - 109207) AS DATETIME) end as accountexpires


推荐阅读