Convert varchar to datetime in sql which is having millisec

前端 未结 5 1067
广开言路
广开言路 2021-01-03 08:04

I have a column abc varchar(100) with data like 2011-09-26 16:36:57.810000

I want to convert this column to DATETIME...

<
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 09:00

    Assuming we have the following string variables:

    DECLARE @d VARCHAR(100)  = '2020-04-06T04:35:07.9490051Z' -- 7 digits nanoseconds
    DECLARE @d1 VARCHAR(100) = '2020-04-05T15:00:00Z'         -- simple: without nanoseconds
    

    I came up to the solution using CAST operator:

    SELECT CAST(LEFT(@d,19) + 'Z' AS DATETIME)  -- outputs: 2020-04-06 04:35:07.000
    SELECT CAST(LEFT(@d1,19) + 'Z' AS DATETIME) -- outputs: 2020-04-05 15:00:00.000
    

提交回复
热议问题