How to convert VARCHAR datetime to DATETIME type to populate table

丶灬走出姿态 提交于 2020-01-06 11:35:17

问题


I have a table with a VARCHAR() column with values in this format:

2012-10-05T11:14:00-04:00

I need to put this data into another table where the data type of the field is DATETIME.

How would I go about converting

2012-10-05T11:14:00-04:00

to

2012-10-05 11:14:00

?

I tried:

CAST(LEFT(REPLACE(fieldtimestamp, 'T', ' '), 19) AS DATETIME)

But it keeps giving me the error:

Conversion failed when converting date and/or time from character string.


回答1:


select CAST(LEFT(REPLACE('2012-10-05T11:14:00-04:00', 'T', ' '), 19) AS DATETIME)

works for me giving

2012-10-05 11:14:00.000

under sql server 2012




回答2:


This will do: SELECT CONVERT(DATETIME,LEFT(fieldtimestamp,19),126)

No need for replacing the 'T'.




回答3:


If you're using MS SQL Server 2008, you can use DATETIMEOFFSET instead of DATETIME and it will work.

BEGIN
DECLARE @d DATETIMEOFFSET
SELECT @d = '2012-10-05 11:14:00-04:00'
END



回答4:


SELECT thedate, CAST( LEFT( REPLACE( thedate, 'T', ' ' ) , 21 ) AS DATETIME ) FROM MyTbl1

If you want the seconds you will need to take 21 letters,

thedate                     DATETIME
2012-10-05T11:14:00-04:00   2012-10-05 11:14:00
2012-10-05T11:14:00-05:00   2012-10-05 11:14:00

Worked fine in mysql



来源:https://stackoverflow.com/questions/14611407/how-to-convert-varchar-datetime-to-datetime-type-to-populate-table

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