CTE returning error

前端 未结 1 2089
别跟我提以往
别跟我提以往 2020-12-17 05:05

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
         


        
相关标签:
1条回答
  • 2020-12-17 05:46

    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:

    1. FROM
    2. ON
    3. JOIN
    4. WHERE
    5. GROUP BY
    6. WITH CUBE or WITH ROLLUP
    7. HAVING
    8. SELECT
    9. DISTINCT
    10. ORDER BY
    11. TOP

    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
    
    0 讨论(0)
提交回复
热议问题