简体   繁体   中英

CONVERT or CAST field in SQL Query

I have a TimeStamp field in a MySQL database that I'm trying to pull data from. I'm trying to get it as a string, so I've been using the following query:

select CONVERT(VARCHAR, date_created, 120) from junk;

It throws the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR, date_modified, 120) from junk limit 10' at line 1

Can someone please tell me what I'm doing wrong?

CONVERT() in MySQL is used to convert between different character sets, you need DATE_FORMAT() :

SELECT DATE_FORMAT(date_created, '%Y%m%d %H%i%S')
FROM Junk

Update: Originally had CAST() incorrectly using VARCHAR() , but CAST() will also work:

SELECT CAST(date_created AS CHAR(10))
FROM Junk

DATE_FORMAT() options

如果你想明确格式化为yyyymmdd(sql server中的样式120)

Select DATE_FORMAT(somedate, '%Y%m%d') From SomeTable

In MySql, the CONVERT() function is used to convert existing string types (like varchar) between character sets (like utf-8 or ascii). To format a TimeStamp column, use the FROM_UNIXTIME() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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