Mario Mario - 1 year ago 135
SQL Question

Cast int to varchar

I have below query and need to cast



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.

Answer Source

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 SQL Fiddle with Demo.

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 USING transcoding_name)

Your original query had the syntax backwards.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download