问题
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