Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

casting

mysql

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:

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?

like image 482
aarona Avatar asked Jun 13 '09 00:06

aarona


People also ask

How do I CAST a query in MySQL?

The CAST() function in MySQL is used to convert a value from one data type to another data type specified in the expression. It is mostly used with WHERE, HAVING, and JOIN clauses. This function is similar to the CONVERT() function in MySQL. It converts the value into DATE datatype in the "YYYY-MM-DD" format.

What is CAST () in MySQL?

The MySQL CAST() function is used for converting a value from one datatype to another specific datatype. The CAST() function accepts two parameters which are the value to be converted and the datatype to which the value needs to be converted.

Can we use CAST in where clause?

You can cast data into BINARY, CHAR, DATE, DATETIME, TIME, DECIMAL, SIGNED, UNSIGNED data types. mysql> select cast(1 as char) from sales; You can also use MySQL CAST in WHERE clause.


1 Answers

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

SELECT CAST(my_table.DateColumn AS CHAR(10)) as TextColumn FROM my_table;
like image 128
great_llama Avatar answered Nov 08 '22 18:11

great_llama