Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in SQL by (20.3k points)

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.

1 Answer

0 votes
by (40.7k points)

You have cast or convert as a CHAR datatype, there's 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;

It seems like you were trying to convert to an incorrect datatype i.e. the syntax that you were using to convert was incorrect. 

The convert function takes expr as your column or value:

 CONVERT(expr,type)

or

 CONVERT(expr USING transcoding_name)

However, your original query had the syntax backward.

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Aug 7, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Oct 7, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer

Browse Categories

...