Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

sql - MySQL CAST as DATE

I'm trying to understand what casting a value to the DATE type in MySQL does. Here are some things I have tried:

SELECT CAST('3' AS DATE);
-- null

SELECT CAST(3 AS DATE);
-- null

SELECT CAST('2014-07-01 19:00:01' AS DATE);
-- 2014-07-01

SELECT DATE('2014-07-01 19:00:01');
-- 2014-07-01

SELECT CAST('2014-07-01' AS DATE);
-- 2014-07-01

SELECT DATE('2014-07-01');
-- 2014-07-01

SELECT CAST('2014-07-50' AS DATE);
-- null

SELECT DATE('2014-07-50');
-- null

SELECT DATE(''), CAST('' AS DATE), DATE(0), CAST(0 AS DATE);
-- null, null, 0000-00-00, 0000-00-00

Everything I've tried seems to either convert it to null if it's invalid or return the date portion of the string if it's a valid date. I've even tried dates with slashes and other formats, same results.

What's the difference between using the DATE(expr) function and the CAST(expr AS DATE)?

DATE(expr): Extracts the date part of the date or datetime expression expr.

CAST(expr AS type): The CAST() function takes an expression of any type and produces a result value of a specified type, similar to CONVERT()

Similarly, the same question can be asked about times with TIME(expr) and CAST(expr AS TIME).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Checking the source code of MySQL 5.6 CAST() and CONVERT() calls to the same internal function Item_date_typecast, DATE() calls to Item_date_typecast too.

In conclusion there is no difference between DATE(expr) function and the CAST(expr AS DATE).

Refs:

https://github.com/mysql/mysql-server/blob/5.6/sql/sql_yacc.yy

https://github.com/mysql/mysql-server/blob/5.6/sql/item_create.cc


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...