如何在 T-SQL 中将 DATETIME 值转换为 FILETIME 值?
我需要在 T-SQL SELECT 语句(在 SQL Server 2000 上)中将 SQL Server DATETIME 值转换为 FILETIME。有内置函数可以做到这一点吗?如果没有,有人可以帮我弄清楚如何将此转换例程实现为 UDF(或只是简单的 Transact-SQL)吗?这是我所知道的:
- FILETIME 是 64 位值,表示自 100 纳秒间隔以来的数量 1601 年 1 月 1 日(UTC)(根据 MSDN:FILETIME 结构)。
- SQL Server 基准时间从 1900-01-01 00:00:00 开始(根据 SELECT CAST(0 as DATETIME))。
我找到了几个示例,展示了如何将 FILETIME 值转换为 T-SQL DATETIME(不过,我不能 100% 确定它们是准确的),但找不到任何有关反向转换的信息。即使是一般的想法(或算法)也会有帮助。
I need to convert a SQL Server DATETIME value to FILETIME in a T-SQL SELECT statement (on SQL Server 2000). Is there a built-in function to do this? If not, can someone help me figure out how to implement this conversion routine as a UDF (or just plain Transact-SQL)? Here is what I know:
- FILETIME is 64-bit value representing the number of 100-nanosecond intervals since
January 1, 1601 (UTC) (per MSDN: FILETIME Structure). - SQL Server base time starts on 1900-01-01 00:00:00 (per SELECT CAST(0 as DATETIME)).
I found several examples showing how to convert FILETIME values to T-SQL DATETIME (I'm not 100% sure they are accurate, though), but could not find anything about reverse conversion. Even the general idea (or algorithm) would help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,我想我自己能够实现这个。这是函数:
它似乎准确到 1 秒,这对我来说没问题(由于数据溢出,我无法使其更准确)。我使用 TimeAndDate Web 工具 来计算日期之间的持续时间。
你怎么认为?
Okay, I think I was able to implement this myself. Here is the function:
It seems to be accurate up to 1 second, which is okay with me (I could not make it more accurate due to data overflow). I used the TimeAndDate web tool to calculate the durations between dates.
What do you think?
不,这是基准日期,日期时间从 1753 开始
运行此
输出
1780-01-22 00:00:00.000
但这仍然小于文件时间,所以你需要添加它......但是请记住公历和儒略历(也日期时间从 1753 开始的原因)
No, that is the base date, datetime starts at 1753
run this
output
1780-01-22 00:00:00.000
But this is still less than filetime so you need to add that...however remember the gregorian and Julian calendars (also the reason that datetime starts at 1753)
接受的答案效果很好,但在 2038 年 1 月 19 日以上的日期会崩溃。要么使用
如果您使用的是 SQL Server 2016 或更高版本,请使用 DATEDIFF_BIG 而不是 DATEDIFF,或者使用以下更正
The accepted answer work well, but will crash for date above 19 January 2038. Either use
DATEDIFF_BIG instead of DATEDIFF if you are on SQL Server 2016 or above, or use the following correction