SQL Server 中的 DateTime2 与 DateTime
哪一个:
是推荐的方式在 SQL Server 2008+ 中存储日期和时间?
我知道精度(可能还有存储空间)方面的差异,但现在忽略这些差异,是否有关于何时使用什么的最佳实践文档,或者也许我们应该只使用 datetime2
?
Which one:
is the recommended way to store date and time in SQL Server 2008+?
I'm aware of differences in precision (and storage space probably), but ignoring those for now, is there a best practice document on when to use what, or maybe we should just use datetime2
only?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
datetime 的 MSDN 文档建议使用 日期时间2。这是他们的建议:
datetime2 具有更大的日期范围、更大的默认小数精度和可选的用户指定精度。此外,根据用户指定的精度,它可能会使用更少的存储空间。
The MSDN documentation for datetime recommends using datetime2. Here is their recommendation:
datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage.
DATETIME2
的日期范围为“0001 / 01 / 01”到“9999 / 12 / 31”,而DATETIME
类型仅支持年份 1753-9999。另外,如果您需要,
DATETIME2
在时间方面可以更精确;DATETIME
限制为 3 1/3 毫秒,而DATETIME2
可以精确到 100ns。这两种类型都映射到 .NET 中的 System.DateTime - 没有区别。
如果您可以选择,我建议尽可能使用
DATETIME2
。我没有看到使用 DATETIME 的任何好处(除了向后兼容性) - 你会遇到更少的麻烦(日期超出范围和类似的麻烦)。另外:如果您只需要日期(没有时间部分),请使用
DATE
- 它与DATETIME2
一样好,而且还可以节省空间! :-) 同样仅适用于时间 - 使用TIME
。这就是这些类型的用途!DATETIME2
has a date range of "0001 / 01 / 01" through "9999 / 12 / 31" while theDATETIME
type only supports year 1753-9999.Also, if you need to,
DATETIME2
can be more precise in terms of time;DATETIME
is limited to 3 1/3 milliseconds, whileDATETIME2
can be accurate down to 100ns.Both types map to
System.DateTime
in .NET - no difference there.If you have the choice, I would recommend using
DATETIME2
whenever possible. I don't see any benefits usingDATETIME
(except for backward compatibility) - you'll have less trouble (with dates being out of range and hassle like that).Plus: if you only need the date (without time part), use
DATE
- it's just as good asDATETIME2
and saves you space, too! :-) Same goes for time only - useTIME
. That's what these types are there for!datetime2 在大多数方面都获胜,除了(旧应用程序兼容性)
请注意以下几点
图片来源:
MCTS 自定进度培训套件(考试 70-432):Microsoft® SQL Server® 2008 - 实施和维护
第 3 章:表格 ->第 1 课:创建表 ->第66页
datetime2 wins in most aspects except (old apps Compatibility)
please note the following points
image source :
MCTS Self-Paced Training Kit (Exam 70-432): Microsoft® SQL Server® 2008 - Implementation and Maintenance
Chapter 3:Tables -> Lesson 1: Creating Tables -> page 66
我同意 @marc_s 和 @Adam_Poward —— DateTime2 是前进的首选方法。它具有更广泛的日期范围、更高的精度,并且使用相同或更少的存储空间(取决于精度)。
但是,讨论忽略了一件事......
@Marc_s 指出:
两种类型都映射到 .NET 中的 System.DateTime - 没有区别
。这是正确的,但是,反之则不然...并且在进行日期范围搜索时很重要(例如“查找 2010 年 5 月 5 日修改的所有记录”)。.NET 版本的
Datetime
与DateTime2
具有相似的范围和精度。将 .netDatetime
映射到旧 SQLDateTime
时,会发生隐式舍入。旧的 SQLDateTime
精确到 3 毫秒。这意味着11:59:59.997
已经接近一天结束的时间了。任何更高的值都会四舍五入到第二天。试试这个:
避免这种隐式舍入是转向 DateTime2 的重要原因。日期的隐式舍入显然会导致混乱:
I concur with @marc_s and @Adam_Poward -- DateTime2 is the preferred method moving forward. It has a wider range of dates, higher precision, and uses equal or less storage (depending on precision).
One thing the discussion missed, however...
@Marc_s states:
Both types map to System.DateTime in .NET - no difference there
. This is correct, however, the inverse is not true...and it matters when doing date range searches (e.g. "find me all records modified on 5/5/2010")..NET's version of
Datetime
has similar range and precision toDateTime2
. When mapping a .netDatetime
down to the old SQLDateTime
an implicit rounding occurs. The old SQLDateTime
is accurate to 3 milliseconds. This means that11:59:59.997
is as close as you can get to the end of the day. Anything higher is rounded up to the following day.Try this :
Avoiding this implicit rounding is a significant reason to move to DateTime2. Implicit rounding of dates clearly causes confusion:
几乎所有的答案和评论都侧重于优点,而较少关注缺点。这是迄今为止所有优点和缺点的回顾,以及一些我只见过一次或根本没有提到过的关键缺点(在下面的#2中)。
1.1。更符合 ISO 标准(ISO 8601)(尽管我不知道这在实践中如何发挥作用)。
1.2.更多范围(1/1/0001 到 12/31/9999 与 1/1/1753-12/31/9999)(尽管额外的范围,所有早于 1753 年的,可能不会被使用,除了 ex.,在历史、天文、地质等应用程序中)。
1.3.与 .NET 的
DateTime
类型范围完全匹配(尽管如果值在目标类型的范围和精度范围内,则两者都可以来回转换,无需特殊编码,但下面的 Con # 2.1 除外,否则会发生错误/舍入)。1.4.更精确(100 纳秒又名 0.000,000,1 秒 vs. 3.33 毫秒又名 0.003,33 秒)(尽管除了工程/科学应用程序之外,可能不会使用额外的精度)。
1.5.当配置为与
DateTime
类似的(如 1 毫秒,而不是 Iman Abidi 声称的“相同”(如 3.33 毫秒))精度时,使用的空间更少(7 比 10)。 8 个字节),但是当然,您会失去精度优势,这可能是最受吹捧的两个优势之一(另一个是范围),尽管可能是不需要的优势)。2.1。将参数传递给 .NET
SqlCommand
时,如果您可能要传递 SQL ServerDateTime< 之外的值,则必须指定
System.Data.SqlDbType.DateTime2
/code> 的范围和/或精度,因为它默认为System.Data.SqlDbType.DateTime
。2.2.无法隐式/轻松转换为浮点数值(自最小日期时间以来的天数)值,以使用数值和运算符在 SQL Server 表达式中执行以下操作:
2.2.1。添加或减去天数或部分天数。注意:当您需要考虑日期时间的多个部分(如果不是全部部分)时,使用
DateAdd
函数作为解决方法并非易事。2.2.2.取两个日期时间之间的差值来计算“年龄”。注意:您不能简单地使用 SQL Server 的
DateDiff
函数,因为如果两个日期时间碰巧跨越日历,它不会像大多数人期望的那样计算age
/clock 指定单位的日期时间边界,即使对于该单位的一小部分,它也会返回该单位的 1 与 0 的差异。例如,DateDiff
中>Day 两个日期时间仅相隔 1 毫秒,如果这些日期时间位于不同的日历日(即“1999-12-31 23:59:59.9999999”),则将返回 1 与 0(天)和“2000-01-01 00:00:00.0000000”)。如果移动相同的 1 毫秒差异日期时间以便它们不会跨越日历日,则将在Day
中返回 0(天)的“DateDiff”。2.2.3.通过简单地先转换为“Float”,然后再转换回
DateTime
,即可获取日期时间的Avg
(在聚合查询中)。注意:要将
DateTime2
转换为数字,您必须执行类似以下公式的操作,该公式仍然假设您的值不小于 1970 年(这意味着您将失去所有额外范围加上注意:您可能无法简单地调整公式以允许额外的范围,因为您可能会遇到数字溢出问题。 , @Time) + DATEPART(纳秒, @Time) / 1.0E + 9) / 86400.0 – 来源:“ https://siderite.dev/blog/how-to-translate-t-sql-datetime2-to.html “
当然,你可以还首先将
Cast
转换为DateTime
(如果有必要,再次返回DateTime2
),但是您会丢失精度和范围(全部在年份之前) [第 1753 章]隐式/简单转换为浮点数字(天数)以进行加法/减法/“年龄”(与年龄)DateDiff
) /Avg
计算的好处,根据我的经验,这是一个很大的好处。顺便说一句,日期时间的
Avg
是(或者至少应该)一个重要的用例。 a)除了在使用日期时间(自公共基准日期时间)表示持续时间(常见做法)时获取平均持续时间之外,b)获取有关平均日期的仪表板类型统计数据也很有用时间位于行范围/组的日期时间列中。 c) 用于监视/排除列中可能永远/不再有效和/或可能需要弃用的值的标准(或至少应该标准)即席查询是列出每个值的出现次数以及与该值关联的Min
、Avg
和Max
日期时间戳(如果有)。Almost all the Answers and Comments have been heavy on the Pros and light on the Cons. Here's a recap of all Pros and Cons so far plus some crucial Cons (in #2 below) I've only seen mentioned once or not at all.
1.1. More ISO compliant (ISO 8601) (although I don’t know how this comes into play in practice).
1.2. More range (1/1/0001 to 12/31/9999 vs. 1/1/1753-12/31/9999) (although the extra range, all prior to year 1753, will likely not be used except for ex., in historical, astronomical, geologic, etc. apps).
1.3. Exactly matches the range of .NET’s
DateTime
Type’s range (although both convert back and forth with no special coding if values are within the target type’s range and precision except for Con # 2.1 below else error / rounding will occur).1.4. More precision (100 nanosecond aka 0.000,000,1 sec. vs. 3.33 millisecond aka 0.003,33 sec.) (although the extra precision will likely not be used except for ex., in engineering / scientific apps).
1.5. When configured for similar (as in 1 millisec not "same" (as in 3.33 millisec) as Iman Abidi has claimed) precision as
DateTime
, uses less space (7 vs. 8 bytes), but then of course, you’d be losing the precision benefit which is likely one of the two (the other being range) most touted albeit likely unneeded benefits).2.1. When passing a Parameter to a .NET
SqlCommand
, you must specifySystem.Data.SqlDbType.DateTime2
if you may be passing a value outside the SQL ServerDateTime
’s range and/or precision, because it defaults toSystem.Data.SqlDbType.DateTime
.2.2. Cannot be implicitly / easily converted to a floating-point numeric (# of days since min date-time) value to do the following to / with it in SQL Server expressions using numeric values and operators:
2.2.1. add or subtract # of days or partial days. Note: Using
DateAdd
Function as a workaround is not trivial when you're needing to consider multiple if not all parts of the date-time.2.2.2. take the difference between two date-times for purposes of “age” calculation. Note: You cannot simply use SQL Server’s
DateDiff
Function instead, because it does not computeage
as most people would expect in that if the two date-times happens to cross a calendar / clock date-time boundary of the units specified if even for a tiny fraction of that unit, it’ll return the difference as 1 of that unit vs. 0. For example, theDateDiff
inDay
’s of two date-times only 1 millisecond apart will return 1 vs. 0 (days) if those date-times are on different calendar days (i.e. “1999-12-31 23:59:59.9999999” and “2000-01-01 00:00:00.0000000”). The same 1 millisecond difference date-times if moved so that they don’t cross a calendar day, will return a “DateDiff” inDay
’s of 0 (days).2.2.3. take the
Avg
of date-times (in an Aggregate Query) by simply converting to “Float” first and then back again toDateTime
.NOTE: To convert
DateTime2
to a numeric, you have to do something like the following formula which still assumes your values are not less than the year 1970 (which means you’re losing all of the extra range plus another 217 years. Note: You may not be able to simply adjust the formula to allow for extra range because you may run into numeric overflow issues.25567 + (DATEDIFF(SECOND, {d '1970-01-01'}, @Time) + DATEPART(nanosecond, @Time) / 1.0E + 9) / 86400.0
– Source: “ https://siderite.dev/blog/how-to-translate-t-sql-datetime2-to.html “Of course, you could also
Cast
toDateTime
first (and if necessary back again toDateTime2
), but you'd lose the precision and range (all prior to year 1753) benefits ofDateTime2
vs.DateTime
which are prolly the 2 biggest and also at the same time prolly the 2 least likely needed which begs the question why use it when you lose the implicit / easy conversions to floating-point numeric (# of days) for addition / subtraction / "age" (vs.DateDiff
) /Avg
calcs benefit which is a big one in my experience.Btw, the
Avg
of date-times is (or at least should be) an important use case. a) Besides use in getting average duration when date-times (since a common base date-time) are used to represent duration (a common practice), b) it’s also useful to get a dashboard-type statistic on what the average date-time is in the date-time column of a range / group of Rows. c) A standard (or at least should be standard) ad-hoc Query to monitor / troubleshoot values in a Column that may not be valid ever / any longer and / or may need to be deprecated is to list for each value the occurrence count and (if available) theMin
,Avg
andMax
date-time stamps associated with that value.这是一个示例,将向您展示smalldatetime、datetime、datetime2(0) 和datetime2(7) 之间存储大小(字节)和精度的差异:
返回
如果我想将信息存储到秒,则 So - 但不是精确到毫秒 - 如果我使用 datetime2(0) 而不是 datetime 或 datetime2(7),则每个字节可以节省 2 个字节。
Here is an example that will show you the differences in storage size (bytes) and precision between smalldatetime, datetime, datetime2(0), and datetime2(7):
which returns
So if I want to store information down to the second - but not to the millisecond - I can save 2 bytes each if I use datetime2(0) instead of datetime or datetime2(7).
如果您是一名 Access 开发人员,试图将 Now() 写入相关字段,则 DateTime2 会造成严重破坏。刚刚做了一个访问 -> SQL 2008 R2 迁移,它将所有日期时间字段放入 DateTime2。使用 Now() 附加一条记录作为被炸毁的值。 1/1/2012 2:53:04 PM 可以,但 1/10/2012 2:53:04 PM 不行。
一旦性格产生了影响。希望它对某人有帮助。
DateTime2 wreaks havoc if you are an Access developer trying to write Now() to the field in question. Just did an Access -> SQL 2008 R2 migration and it put all the datetime fields in as DateTime2. Appending a record with Now() as the value bombed out. It was okay on 1/1/2012 2:53:04 PM, but not on 1/10/2012 2:53:04 PM.
Once character made the difference. Hope it helps somebody.
老问题...但我想添加一些这里没有人说过的东西...(注意:这是我自己的观察,所以不要要求任何参考)
Datetime2 在过滤条件中使用时速度更快。
TLDR:
在 SQL 2016 中,我有一个包含数十万行的表和一个日期时间列 ENTRY_TIME,因为它需要存储最多以秒为单位的精确时间。在执行具有许多联接和子查询的复杂查询时,当我使用 where 子句时:
当有数百行时,查询最初很好,但是当行数增加时,查询开始给出此错误:
我删除了where 子句,出乎意料的是,查询在 1 秒内运行,尽管现在已获取所有日期的所有行。我使用 where 子句运行内部查询,花了 85 秒,没有 where 子句则花了 0.01 秒。
我在这里遇到了许多关于此问题的线程 日期时间过滤性能
我稍微优化了查询。但我获得的真正速度是通过将日期时间列更改为 datetime2 来实现的。
现在,之前超时的同一查询只需要不到一秒的时间。
干杯
Old Question... But I want to add something not already stated by anyone here... (Note: This is my own observation, so don't ask for any reference)
Datetime2 is faster when used in filter criteria.
TLDR:
In SQL 2016 I had a table with hundred thousand rows and a datetime column ENTRY_TIME because it was required to store the exact time up to seconds. While executing a complex query with many joins and a sub query, when I used where clause as:
The query was fine initially when there were hundreds of rows, but when number of rows increased, the query started to give this error:
I removed the where clause, and unexpectedly, the query was run in 1 sec, although now ALL rows for all dates were fetched. I run the inner query with where clause, and it took 85 seconds, and without where clause it took 0.01 secs.
I came across many threads here for this issue as datetime filtering performance
I optimized query a bit. But the real speed I got was by changing the datetime column to datetime2.
Now the same query that timed out previously takes less than a second.
cheers
使用非美国
DATEFORMAT
设置时,将日期字符串解释为datetime
和datetime2
也可能不同。例如,对于
日期时间
,返回2013-05-06
(即5月6日),对于2013-06-05
(即6月5日)代码>日期时间2。但是,将dateformat
设置为mdy
时,@d
和@d2
都会返回2013-06- 05
。datetime
行为似乎与 SET DATEFORMAT 的“noreferrer">MSDN 文档其中指出:某些字符串格式(例如 ISO 8601)的解释与 DATEFORMAT 设置无关。显然不是真的!在我被这个问题困扰之前,我一直认为无论语言/区域设置如何,
yyyy-mm-dd
日期都会得到正确处理。Interpretation of date strings into
datetime
anddatetime2
can be different too, when using non-USDATEFORMAT
settings. E.g.This returns
2013-05-06
(i.e. May 6) fordatetime
, and2013-06-05
(i.e. June 5) fordatetime2
. However, withdateformat
set tomdy
, both@d
and@d2
return2013-06-05
.The
datetime
behavior seems at odds with the MSDN documentation ofSET DATEFORMAT
which states: Some character strings formats, for example ISO 8601, are interpreted independently of the DATEFORMAT setting. Obviously not true!Until I was bitten by this, I'd always thought that
yyyy-mm-dd
dates would just be handled right, regardless of the language / locale settings.虽然 datetime2 提高了精度,某些客户端不支持 date、time 或 datetime2,并强制您转换为字符串文字。具体来说,Microsoft 提到了这些数据类型的“下层”ODBC、OLE DB、JDBC 和 SqlClient 问题,并有一个 图表显示每种类型如何映射。
如果重视兼容性而不是精度,请使用日期时间
while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal. Specifically Microsoft mentions "down level" ODBC, OLE DB, JDBC, and SqlClient issues with these data types and has a chart showing how each can map the type.
If value compatability over precision, use datetime
根据 这篇文章,如果您想使用 DateTime2 获得与 DateTime 相同的精度,则只需使用 DateTime2(3) 即可。这应该为您提供相同的精度,占用更少的字节,并提供扩展的范围。
According to this article, if you would like to have the same precision of DateTime using DateTime2 you simply have to use DateTime2(3). This should give you the same precision, take up one fewer bytes, and provide an expanded range.
我刚刚偶然发现了
DATETIME2
的另一个优点:它避免了 Pythonadodbapi
模块中的一个错误,如果标准库datetime
值会导致该错误传递的 DATETIME 列具有非零微秒,但如果该列定义为 DATETIME2 则工作正常。I just stumbled across one more advantage for
DATETIME2
: it avoids a bug in the Pythonadodbapi
module, which blows up if a standard librarydatetime
value is passed which has non-zero microseconds for aDATETIME
column but works fine if the column is defined asDATETIME2
.正如其他答案所示,由于尺寸更小且精度更高,建议使用
datetime2
,但这里有一些关于 为什么不使用 Nikola Ilic 的 datetime2:GETDATE()+ 1
DATEADD
或DATEDIFF
进行比较时,您都将完成与datetime
As the other answers show
datetime2
is recommended due to smaller size and more precision, but here are some thoughts on why NOT to use datetime2 from Nikola Ilic:GETDATE()+1
DATEADD
orDATEDIFF
, you will finish with implicit data conversion todatetime
我认为
DATETIME2
是存储date
的更好方法,因为它比日期时间
。在SQL Server 2008
中,您可以使用DATETIME2
,它存储日期和时间,需要6-8字节
来存储,精度为<代码>100纳秒。因此,任何需要更高时间精度的人都会需要DATETIME2
。I think
DATETIME2
is the better way to store thedate
, because it has more efficiency thanthe
DATETIME
. InSQL Server 2008
you can useDATETIME2
, it stores a date and time, takes 6-8bytes
to store and has a precision of100 nanoseconds
. So anyone who needs greater time precision will wantDATETIME2
.接受的答案很好,只需知道如果您将 DateTime2 发送到前端 - 它会四舍五入到正常的 DateTime 等效值。
这给我带来了一个问题,因为在我的解决方案中,我必须在重新提交时将发送的内容与数据库上的内容进行比较,而我的简单比较“==”不允许舍入。所以必须添加它。
Accepted answer is great, just know that if you are sending a DateTime2 to the frontend - it gets rounded to the normal DateTime equivalent.
This caused a problem for me because in a solution of mine I had to compare what was sent with what was on the database when resubmitted, and my simple comparison '==' didn't allow for rounding. So it had to be added.
datetime2 更好
日期时间范围:1753-01-01 到 9999-12-31,datetime2 范围:0001-01-01 到 9999-12-31
datetime 精度:0.00333 秒,datetime2 精度:100 纳秒
datetime 获取 8 个字节,datetime2 获取 6 到 8 个字节取决于精度
(精度小于 3 时需要 6 个字节,精度 3 或 4 时需要 7 个字节,其他精度需要 8 个字节,请点击查看下图)
datetime2 is better
datetime range : 1753-01-01 through 9999-12-31 , datetime2 range : 0001-01-01 through 9999-12-31
datetime Accuracy : 0.00333 second , datetime2 Accuracy : 100 nanoseconds
datetime get 8 bytes , datetime2 get 6 to 8 bytes depends on precisions
(6 bytes for precision less than 3 , 7 bytes for precision 3 or 4 , All other precision require 8 bytes, Click and Look at the below picture)
上述 SQL 不适用于 DateTime2 字段。
它返回并错误“操作数类型冲突:datetime2 与 int 不兼容”
多年来,开发人员一直在对日期进行加 1 以获得第二天。现在微软有一个超级新的 datetime2 字段,无法处理这个简单的功能。
“我们就用这种比旧的还差的新类型吧”,我不这么认为!
The above SQL won't work with a DateTime2 field.
It returns and error "Operand type clash: datetime2 is incompatible with int"
Adding 1 to get the next day is something developers have been doing with dates for years. Now Microsoft have a super new datetime2 field that cannot handle this simple functionality.
"Let's use this new type that is worse than the old one", I don't think so!