sql-serverdatepartdatetime2

How can I get the full milliseconds in SQL server?


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)))

Executing that returns the following example values:

300 260 265 264 264 264 264

How can I get more precision?


Solution

  • Never mind, the function returns an int, which is not what I expected. I'm supposed to use NANOSECOND, and divide it.

    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