Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I got an error "Conversion failed when converting the varchar value 'Id' to data type int"....

What I have tried:

SELECT *
FROM History
INNER JOIN Header
ON History.Id = Header.docId
Posted
Updated 8-Feb-17 23:48pm

The error is giving you all the information you need to troubleshoot this. In one table, you've got an ID column that contains a numeric value, an integer. In the other table, the ID column is a string of characters. You cannot JOIN on the two different data types.

You COULD put an implicit conversion on the varchar column to match the integer on the other column but since the conversion has to be applied to every value in the varchar ID column, the JOIN operation is going to be pretty slow. On top of that, what if the ID column has a NULL in it or a value that cannot be converted to an integer value? Oops.
 
Share this answer
 
v2
check this

SQL
 declare @History table (Id varchar(50),Name varchar(50))
declare @Header table (docId int,Name varchar(50))
insert into @History(id,name)values( 'id', 'a')
insert into @History(id,name)values( '2', 'a')

insert into @Header(docId,name)values( '2', 'a1')
insert into @Header(docId,name)values( '2', 'b1')

 
 select * from (  (SELECT * FROM @History where ISNUMERIC(id) =1 ) hi   INNER JOIN @Header he ON  hi.id = he.docId )


use ISNUMERIC (Transact-SQL)[^] to check the value is a valid number or not
 
Share this answer
 
v2
Comments
Richard Deeming 9-Feb-17 6:40am    
ISNUMERIC considers many non-numeric strings to be numeric - for example, ',', '.', '-', etc.

For SQL 2012 or higher, it would be better to use TRY_PARSE[^]:
SELECT * FROM @History hi INNER JOIN @Header he ON he.docId = TRY_PARSE(hi.id As int)

For older versions, a simple NOT LIKE comparison is more robust for basic integers:
WHERE Id NOT LIKE '%[^0-9]%'
Karthik_Mahalingam 9-Feb-17 7:05am    
Thanks for the info Richard

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900