I have an odd problem in SQL Server. Basically we have a generic type object with two columns, Description 1
and Description 2
. We check if Description2
is a number and if it is, check the value/use it. However I am getting the following error when attempting to run the query.
Conversion failed when converting nvarchar value 'Test Other' to data type int.
Now normally I would simply assume that it was attempting to join on improper values/etc, but the varchar
it's saying in the error should not be valid from the ISNUMERIC
.
Here is a sample of my query:
SELECT *
FROM base_table
JOIN org_type o ON o.id = base_table.org_id
LEFT JOIN generic_object go ON go.id = base_table.org_id AND ISNUMERIC(description2)
WHERE description2 = @orgId
AND base_table.id = @baseId
What is strange to me, when I remove the last line from the query, I do not receive an error.
答案 0 :(得分:2)
使用内联视图仅返回数字说明2记录。这样,它必须首先解析仅包含数值的数据集。
SELECT *
FROM base_table
JOIN org_type o ON o.id = base_table.org_id
LEFT JOIN (SELECT *
FROM generic_object
WHERE isNumeric(description2)) go ON go.id = base_table.org_id
WHERE description2 = @orgId
AND base_table.id = @baseId
答案 1 :(得分:2)
我还没有见过这种加入......但我认为这会让你获得理想的结果。首先从连接中删除ISNUMERIC。我基本上只将变量description2
与numeric
进行比较,如果它不是,那么只需将它与自身进行比较,这总是正确的。
WHERE ISNULL(@orgId,'') = case when ISNUMERIC(description2) = 1 then description2 else ISNULL(@orgId,'') end
答案 2 :(得分:0)
To me it looks like the description2 = @orgId
is the problem. If you are checking for ISNUMERIC(description2)
on the JOIN, the other results you are getting will not be Numeric for that column. So the Where clause is giving you the error. Try moving the ISNUMERIC(description2) = 1
to the Where clause.