Search This Blog

Conversion failed when converting the varchar value to data type int or any other Datatype in SQL

Conversion failed when converting the varchar value to data type int or any other Datatype in SQL.

The Reason for this error is you are converting a varchar value to Int or Numeric or any Other datatype let us take a simple example 

select CAST('abc' as int)

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'abc' to data type int.

what we are doing in above query is changing the nvarchar value to int which is not possible that why it throw the error.

While working with TSQL Coding if you are adding some string value with alphanumeric field  you could face the above problem if you have not written your query properly.
Take an Example where you want to show empid\Empsalary from employee table
for this we will create a table below 

create table Employee1_error1
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee1_error1  values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000')

select * from Employee1_error1 

now we want to display employee empid\Empsalary in same format \we are concatenating the slash in between empid\Empsalary 

like  we want our result like 

EmpId\Empsalary
 1\5000
 2\6000 and so on ..........
             
now run the below query 

select cast(empid+'\'+empsalary as varchar) from Employee1_error1

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '\' to data type int.

we are adding backslash sign between empid and empsalary and coverting the whole into varchar but why it's throwing error
The  Reason is empid is a int field empsalary is a float field and we are doing a complete conversion of all values to varchar that's why it is throwing error 
In order to fix this error Cast Empid Seperately to varchar and same with Empsalary as varchar than added them to backslash.

select cast(empid as varchar)+'\'+ cast(empsalary as varchar) as 'Empid\Empsalary' from Employee1_error1

Output

Empid\Empsalary
1\5000
2\6000
3\8000
4\9000
5\10000


7 comments:

  1. Hi what about -0.065? it can be converted to float?

    ReplyDelete
  2. However, machine data analytics is just in its inception stage, which makes it all the more exciting!Data Analytics Courses

    ReplyDelete
  3. How do we resolve this:

    select CAST('5.00' as int)

    Msg 245, Level 16, State 1, Line 1
    Conversion failed when converting the varchar value '5.00' to data type int.

    ReplyDelete
  4. Machine learning that deals with algorithms and data to advance the machine by using the past
    data to formulate a possible and advanced outcome of a possible future, months in advance.
    artificial intelligence classes in pune

    ReplyDelete