As I try to join tables together on a value that's represented in different data types, I get really odd errors. Please consider the following:
I have two tables; let's say one is in database "CoffeeWarehouse," and the other is in database "CoffeeAnalytics":
Table 1: CoffeeWarehouse.dbo.BeanInfo
Table 2: CoffeeAnalytics.dbo.BeanOrderRecord
Now, both tables have a field called OrderNumber
(although in table 2, it's spelled as[order number]
); in Table 1, it's represented as a string
, and in Table 2, it's represented as a float
.
I proceed to join the tables together:
SELECT ordernumber,
bor.*
FROM CoffeeWarehouse.dbo.BeanInfo AS bni
LEFT JOIN CoffeeAnalytics.dbo.BeanOrderRecord AS bor ON bor.[order number] = bni.ordernumber;
If I specify the order numbers I'd like by adding the following:
WHERE bni.ordernumber = '48911'
then I see the complete table I'd like- all the fields from the table I've joined are populated properly.
If I add more order numbers, it works too:
WHERE bni.ordernumber IN ('48911', '83716', '98811', ...)
Now for the problem:
Suppose I want to select everything in the table where another field, i.e. CountryOfOrigin
, is not null. I'm not going to enter several thousand order numbers- I just want to use a where
clause to weed out the rows with incomplete data.
So I add the following to my original query:
WHERE bor.CountryOfOrigin IS NOT NULL
When I execute, I get this error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.
I get the same error if I even simply use this as a where clause:
WHERE bni.ordernumber IS NOT NULL
Why is this the case? When I specify the ordernumber, the join works well- when I want to select many ordernumbers, I get a conversion error.
Any help/insight?
SELECT MAX(CAST(OrderNumber AS FLOAT)) FROM BeanInfo
and you may find that you have strings that just don't convert to floats. Or perhapsSELECT TOP(1000) OrderNumber FROM BeanInfo ORDER BY OrderNumber DESC
orSELECT * FROM BeanInfo WHERE IsNumeric(OrderNumber) = 0
to see if there are any in there? Then, either correct those values, or revert to explicit casting...ON CAST(bor.[order number] AS NVARCHAR(32)) = bni.ordernumber