Order of SQL Server statements execution

前端 未结 2 1030
一生所求
一生所求 2021-01-27 02:27

I have SQL server 2008 R2, windows 7 OS.

Within the server, I have a table con1 which was created by following SQL statement.

CREATE TABLE [         


        
相关标签:
2条回答
  • 2021-01-27 02:51

    I can't explain the behavior, but the following would get you what you want:

    SELECT t1.digit FROM
    (
    select CAST(digit_str as int) as digit 
      from con1 
     where RIGHT(digit_str,1) <> '.' 
       AND digit_str <> '1'
    ) as t1
    

    I'm not sure why the final where clause is causing that conversion to be executed since it looks to me like it should be already filtered out of the result set of t1.

    0 讨论(0)
  • 2021-01-27 02:58

    This is a known "feature" of SQL Server. Don't ever assume that the WHERE clause executes before the SELECT clause.

    See: SQL Server should not raise illogical errors

    There are actually good reasons for doing that sometimes. Consider joining two tables, with A being much smaller than B.

    select CAST(A.col1 as int), A.col2, B.col3
    from A join B ...
    where ... isnumeric(A.col1) = 1
    

    If you inspect the query plan generated, rightly or wrongly, SQL server will stream the data from A as the leading rows to join against B. While doing that, it knows that it only needs to pull col2 and function on col1. It could bring col1 through just to run the function later, or for something as trivial as CAST, SQL Server might as well transform the data during the streaming process.

    One thing's for sure, this strategy does make SQL Server one little bit faster in certain queries. But on a purely logical perspective, I would call it a bug.

    0 讨论(0)
提交回复
热议问题