I wrote a CTE to remove non numeric values from a data set, then get a count of numeric values within a range.
WITH dtr
AS ( SELECT resultlevel r
In SQL Server
there is Logical Processing Order of the SELECT statement, which determines when the objects defined in one step are made available to the clauses in subsequent steps:
This is how your query is going to be proccesed and your query looks perfectly fine. But sometimes, the SQL Server
decides not to follow this order in order to optimize your query.
In your case, the SQL Server
might be simplyfing/transforming your query into another and performing the convert
function, before applying the where isnumeric
filtering.
If we made your query a little more complex (but still giving the same results), the SQL Server
is executing the code correctly this time:
;with isnum AS (
SELECT result
FROM #temp
WHERE ISNUMERIC(result) = 1
GROUP BY result
HAVING MAX(result) = result
)
SELECT
result,
ISNUMERIC(result)
FROM isnum
WHERE CONVERT(INT,result) > 1;
In your case (and this is what I am doing in such situations when different types are stored in one column), you can simply use TRY_CONVERT function:
;with isnum AS (
SELECT result
FROM #temp
WHERE ISNUMERIC(result) = 1)
SELECT
result,
ISNUMERIC(result)
FROM isnum
WHERE TRY_CONVERT(INT, result) > 1