Convert varchar to datetime in sql which is having millisec

前端 未结 5 1086
广开言路
广开言路 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

    You can use style 121 but you can have only 3 digits for milliseconds (i.e yyyy-mm-dd hh:mi:ss.mmm(24h)) format.

    declare @abc varchar(100)='2011-09-26 16:36:57.810' 
    select convert(datetime,@abc,121)
    

    So you can sort it out by limiting the varchar field to 23 characters before converting as:

    declare @abc varchar(100)='2011-09-26 16:36:57.810000' 
    select convert(datetime,convert(varchar(23),@abc),121)
    

    Or use the Left() function to get first 23 characters as:

    select convert(datetime,left(@abc,23),121)
    

    Try to avoid storing date as string.

提交回复
热议问题