Click here to Skip to main content
14,545,215 members
Rate this:
Please Sign up or sign in to vote.
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

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:

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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
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
   
Comments
Maciej Los 19-May-20 15:10pm
   
5ed!
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   
Comments
Maciej Los 19-May-20 15:10pm
   
5ed!
Rate this:
Please Sign up or sign in to vote.

Solution 3

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[^]
   
Comments
MadMyche 19-May-20 18:00pm
   
+5
Maciej Los 20-May-20 0:22am
   
Thank you.
Rate this:
Please Sign up or sign in to vote.

Solution 4

You can also perform it like the following query :

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

FROM   Production.Product   
   ,   Sales.SalesTerritory 

WHERE  Sales.Sales.CountryRegionCode 
    =  Production.Product.ProductID 
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100