简体   繁体   English

如何将VARCHAR日期时间转换为DATETIME类型以填充表

[英]How to convert VARCHAR datetime to DATETIME type to populate table

I have a table with a VARCHAR() column with values in this format: 我有一个带有VARCHAR()列的表,该表的值具有以下格式:

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. 我需要将此数据放入另一个表中,该表的字段的数据类型为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. 从字符串转换日期和/或时间时转换失败。

This will do: SELECT CONVERT(DATETIME,LEFT(fieldtimestamp,19),126) 它将执行以下操作: SELECT CONVERT(DATETIME,LEFT(fieldtimestamp,19),126)

No need for replacing the 'T' . 无需替换'T'

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 在SQL Server 2012下

If you're using MS SQL Server 2008, you can use DATETIMEOFFSET instead of DATETIME and it will work. 如果您使用的是MS SQL Server 2008,则可以使用DATETIMEOFFSET代替DATETIME,它将起作用。

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

SELECT thedate, CAST( LEFT( REPLACE( thedate, 'T', ' ' ) , 21 ) AS DATETIME ) FROM MyTbl1 从MyTbl1中选择日期CAST(左(替换(thedate,'T',''),21)AS DATETIME)

If you want the seconds you will need to take 21 letters, 如果您想要秒数,则需要输入21个字母,

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 MySQL中工作正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM