Convert date in text format to datetime format in T-SQL

送分小仙女□ 提交于 2019-12-11 13:39:59

问题


I have a client supplied file that is loaded in to our SQL Server database. This file contains text based date values i.e. (05102010) and I need to read them from a db column and convert them to a normal date time value = '2010-05-10 00:00:00.000' as part of a clean-up process.

Any guidance would be greatly appreciated.


回答1:


one way by using

CONVERT(datetime,RIGHT(Column,4) + left(Column,4))

example

declare @s char(8)
select  @s = '05102010'
select CONVERT(datetime,RIGHT(@s,4) + left(@s,4))



回答2:


Try:

SELECT 
    CONVERT(datetime,  RIGHT(YourColumn,4)
                       +LEFT(YourColumn,4)
           ) AS ProperDateTime
    FROM...

working example:

DECLARE @YourTable table (StringDate char(8))
INSERT @YourTable VALUES ('05102010')
INSERT @YourTable VALUES ('03182010')

SELECT 
    CONVERT(datetime,  RIGHT(StringDate,4)
                       +LEFT(StringDate,4)
           ) AS ProperDateTime
    FROM @YourTable

OUTPUT:

ProperDateTime
-----------------------
2010-05-10 00:00:00.000
2010-03-18 00:00:00.000

(2 row(s) affected)



回答3:


Quick and dirty:

SELECT
    CONVERT(DATETIME,
        SUBSTRING(col, 1, 2)
        + '/' + SUBSTRING(col, 3, 2)
        + '/' + SUBSTRING(col, 5, 4))


来源:https://stackoverflow.com/questions/2805512/convert-date-in-text-format-to-datetime-format-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!