Cast int to varchar
Yes
SELECT id || '' FROM some_table;
or SELECT id::text FROM some_table;
is postgresql, but mySql doesn't allow that!
short cut in mySql:
SELECT concat(id, '') FROM some_table;
You're getting that because VARCHAR
is not a valid type to cast into. According to the MySQL docs (http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_cast) you can only cast to:
- BINARY[(N)]
- CHAR[(N)]
- DATE
- DATETIME
- DECIMAL[(M[,D])]
- SIGNED
- [INTEGER]
- TIME
- UNSIGNED [INTEGER]
I think your best-bet is to use CHAR
.
I don't have MySQL, but there are RDBMS (Postgres, among others) in which you can use the hack
SELECT id || '' FROM some_table;
The concatenate does an implicit conversion.
You will need to cast
or convert
as a CHAR
datatype, there is no varchar
datatype that you can cast/convert data to:
select CAST(id as CHAR(50)) as col1
from t9;
select CONVERT(id, CHAR(50)) as colI1
from t9;
See the following SQL — in action — over at SQL Fiddle:
/*! Build Schema */
create table t9 (id INT, name VARCHAR(55));
insert into t9 (id, name) values (2, 'bob');
/*! SQL Queries */
select CAST(id as CHAR(50)) as col1 from t9;
select CONVERT(id, CHAR(50)) as colI1 from t9;
Besides the fact that you were trying to convert to an incorrect datatype, the syntax that you were using for convert
was incorrect. The convert
function uses the following where expr
is your column or value:
CONVERT(expr,type)
or
CONVERT(expr USING transcoding_name)
Your original query had the syntax backwards.