gpt4 book ai didi

sql - 如何将一个字段的日期与另一字段的时间合并 - MS SQL Server

转载 作者:行者123 更新时间:2023-12-01 16:28:57 25 4
gpt4 key购买 nike

在我正在处理的摘录中,我有 2 个日期时间列。一列存储日期,另一列存储时间,如图所示。

如何查询表以将这两个字段合并为 datetime 类型的 1 列?

日期

2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000

时间

1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000

最佳答案

您只需将两者相加即可。

  • 如果日期列的时间部分始终为零
  • 并且时间列的日期部分也始终为零(基准日期:1900 年 1 月 1 日)

添加它们会返回正确的结果。

SELECT Combined = MyDate + MyTime FROM MyTable

基本原理(感谢 ErikE/dnolan)

It works like this due to the way the date is stored as two 4-byte Integers with the left 4-bytes being the date and the right 4-bytes being the time. Its like doing $0001 0000 + $0000 0001 =
$0001 0001

有关新 SQL Server 2008 类型的编辑

DateTimeSQL Server 2008 中引入的类型。如果坚持添加,可以使用Combined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)

Edit2 关于 SQL Server 2008 及更高版本中精度损失的问题(感谢 Martin Smith)

看看How to combine date and time to datetime2 in SQL Server?以防止使用 SQL Server 2008 及更高版本时出现精度损失。

关于sql - 如何将一个字段的日期与另一字段的时间合并 - MS SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/700619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com