如何在SQL Server中获得完整的毫秒数?

时间:2018-01-29 11:52:07

标签: sql-server datepart datetime2

DECLARE @Now DATETIME2(7) = SYSDATETIME();

SELECT
    [Datetime2(1)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(1))),
    [Datetime2(2)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(2))),
    [Datetime2(3)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(3))),
    [Datetime2(4)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(4))),
    [Datetime2(5)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(5))),
    [Datetime2(6)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(6))),
    [Datetime2(7)] = DATEPART(MILLISECOND,CAST(@Now AS DATETIME2(7)))

执行该操作将返回以下示例值:

300 260 265 264 264 264 264

如何获得更高的精确度?

1 个答案:

答案 0 :(得分:1)

没关系,函数返回一个int,这不是我的预期。我应该使用NANOSECOND,并将其分开。

DECLARE @Now DATETIME2(7) = SYSDATETIME();

SELECT
    [Datetime2(1)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(1)))/1000000.0,
    [Datetime2(2)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(2)))/1000000.0,
    [Datetime2(3)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(3)))/1000000.0,
    [Datetime2(4)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(4)))/1000000.0,
    [Datetime2(5)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(5)))/1000000.0,
    [Datetime2(6)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(6)))/1000000.0,
    [Datetime2(7)] = DATEPART(NANOSECOND,CAST(@Now AS DATETIME2(7)))/1000000.0