The way that SQL server seems to be optimising a query is causing it to break. This is illustrated with the two examples below:
SELECT distinct ET.ElementName, ET.Shared, CONVERT(float,ED.Value), ED.SheetSetVersionID, ED.SheetDataID
FROM tElementData ED
INNER JOIN tElementTemplate ET
ON ED.ElementTemplateID = ET.ElementTemplateID
AND ET.ElementName like 'RPODCQRated'
The above query works fine but is not the query I need to run.
SELECT distinct ET.ElementName, ET.Shared, CONVERT(float,ED.Value), ED.SheetSetVersionID, ED.SheetDataID
FROM tElementData ED
INNER JOIN tElementTemplate ET
ON ED.ElementTemplateID = ET.ElementTemplateID
AND ET.ElementName like 'RPODCQRated'
AND CONVERT(float,ED.Value) = 0.006388
The above query throws an exception saying that it cannot convert an nvarchar value to a float. tElementData.Value is an nvarchar(500) field and some records do have none numeric values but all values where tElementTemplate = 'RPODCQRated' can be converted to a float, as the top query proves. It seems that SQL server in its wisdom is applying the CONVERT(float,ED.Value) before it tries the join. I need the second query to work somehow, I can rewrite it but there are limitations on what I can do without rewriting the entire data layer of an existing application.
Things i have tried that don't help: moving the last criteria into a where clause rather that the join, making the first query into a CTE and applying the where clause to the CTE, creating a scalar function that calls IsNumeric on the data before trying to do a convert.
The only thin i could get to work was to insert all the data in a temporary table then apply a where clause to the temporary table. Unfortunately to implement this as a solution would involve extensive refactoring of the data layer of an application in order to solve an obscure bug when searching for certain records.
Any ideas?