如何在 MySql SELECT 语句中正确使用 CAST 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/989643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:29:41  来源:igfitidea点击:

How to use the CAST function correctly in a MySql SELECT statement?

mysqlcasting

提问by aarona

I'm converting an MSSQL DB to MySQL DB and I have a stored procedure that is using a cast function to convert from a datetime datatype to a varchar datatype. Whether or not this matters in php/mysql since php isn't strongly typed (and I dont know if it would matter or not) I really want to keep the SP a close to the orginal as possible so I can maintain the same expected functionality. The problem is that I can't get the cast function to work right in mysql. Here is a test I tried that got me an error:

我正在将 MSSQL DB 转换为 MySQL DB,并且我有一个使用强制转换函数将日期时间数据类型转换为 varchar 数据类型的存储过程。这在 php/mysql 中是否重要,因为 php 不是强类型的(我不知道这是否重要)我真的想让 SP 尽可能接近原始版本,以便我可以保持相同的预期功能. 问题是我无法让 cast 函数在 mysql 中正常工作。这是我尝试过的测试,但出现错误:

DELIMITER ;//

DROP PROCEDURE IF EXISTS `test`;//
CREATE PROCEDURE `test`()
BEGIN
  SELECT CAST(my_table.DateColumn AS VARCHAR(10)) as TextColumn
    FROM my_table;
END;//

What am I doing wrong?

我究竟做错了什么?

回答by great_llama

VARCHAR isn't a valid type for the CAST function, but CHAR is.

VARCHAR 不是 CAST 函数的有效类型,但 CHAR 是.

SELECT CAST(my_table.DateColumn AS CHAR(10)) as TextColumn FROM my_table;