在日期时间列中强制执行精度

Enforce the precision in datetime column

如何在 datetime SQL 列中设置精度,以便存储的值始终是 yyyy-MM-dd HH:mm:ss,即没有任何小数秒?

我正在使用 .NET 和 Dapper 来插入值,虽然我知道在 .NET 中没有小数秒,但我在数据库中看到的值有小数秒。

如果你有 datetime2(0) 则没有毫秒

例子

Select NoMS   = convert(datetime2(0),getDate())
      ,WithMS = convert(datetime2(3),getDate())

Returns

NoMS                   WithMS
2020-06-18 20:06:21    2020-06-18 20:06:21.337

编辑:请注意:

datetime2() 会四舍五入

例如

Select NoMS   = convert(datetime2(0),'2020-06-19 07:33:57.500')
      ,WithMS = convert(datetime2(4),'2020-06-19 07:33:57.500')

Returns

NoMS                 WithMS
2020-06-19 07:33:58  2020-06-19 07:33:57.5000

通知 58 秒 vs 57.5000