Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I get this error message '
'Conversion failed when converting the nvarchar value 'US' to data type int.'


When I try to join two tables using the code below

SQL
select p.[ProductID], s.[CountryRegionCode]
FROM [Production].[Product] as p, [Sales].[SalesTerritory] as s
where s.CountryRegionCode = p.ProductID


Can anyone see why

What I have tried:

SQL
select p.[ProductID], s.[CountryRegionCode]
FROM [Production].[Product] as p, [Sales].[SalesTerritory] as s
where s.CountryRegionCode = p.ProductID
Posted
Updated 20-May-20 19:18pm
v2

The error is self-explanatory; you are trying to compare 2 values that are different data types, the first is a character string and the second is an integer.

The problem is most likely in your WHERE clause as outlined below.
SQL
SELECT p.ProductID
     , s.CountryRegionCode

FROM   Production.Product   as p
   ,   Sales.SalesTerritory as s

WHERE  s.CountryRegionCode   -- Most likely 2 letters 'US'
    =  p.ProductID           -- Most likely a number
 
Share this answer
 
Comments
Maciej Los 19-May-20 15:10pm    
5ed!
Your problem is because the s.CountryRegionCode is a nvarchar datatype and you are trying to compare it p.ProductID which is an int.

You are trying to compare a string to a number which cannot be done, SQL attempted to implicitly convert 'US' to a int but failed because it is not a integer number.

I have to wonder how a product id actually relates to a country code which to me seems nonsensical.
 
Share this answer
 
Comments
Maciej Los 19-May-20 15:10pm    
5ed!
The error message is quite obvious...

I suspect that
s.CountryRegionCode is type of nvarchar ('US')
p.ProductID is type of int (1, 2, ...)
which causes that these data are uncomparable!

So, to be able to join data, you have to use fields with the same type of data.

BTW: you have use Joins[^], instead of WHERE statement! For further details, please see: Visual Representation of SQL Joins[^]
 
Share this answer
 
Comments
MadMyche 19-May-20 18:00pm    
+5
Maciej Los 20-May-20 0:22am    
Thank you.
You can also perform it like the following query :

SQL
SELECT Production.Product.ProductID
     , Sales.SalesTerritory.CountryRegionCode

FROM   Production.Product   
   ,   Sales.SalesTerritory 

WHERE  Sales.Sales.CountryRegionCode 
    =  Production.Product.ProductID 
 
Share this answer
 
Comments
Maciej Los 21-May-20 2:05am    
No, he don't!
Please, read carefully an erorr message posted by OP.

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