Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast int to varchar

I have below query and need to cast id to varchar

Schema

create table t9 (id int, name varchar (55)); insert into t9( id, name)values(2, 'bob'); 

What I tried

select CAST(id as VARCHAR(50)) as col1 from t9;  select CONVERT(VARCHAR(50),id) as colI1 from t9; 

but they don't work. Please suggest.

like image 789
Mario Avatar asked Mar 12 '13 18:03

Mario


People also ask

Can we convert int to varchar?

Converting int to string/varchar using Cast() So, in the above example, we have declared a variable of integer data type and assigned a value to the variable. After this, we are using the Cast() function to convert the variable to the varchar data type of length 10.

What is CAST function in SQL?

SQL Server CAST() Function The CAST() function converts a value (of any type) into a specified datatype. Tip: Also look at the CONVERT() function.

Can you convert varchar to numeric in SQL?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.


2 Answers

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.

like image 67
Taryn Avatar answered Sep 29 '22 08:09

Taryn


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.

like image 41
Aaron Avatar answered Sep 29 '22 07:09

Aaron