原因别名在ORDER BY中有效,但在WHERE中无效

时间:2018-01-31 13:28:48

标签: tsql sql-server-2008-r2

我理解I can't reference an alias in the WHERE clause,但为什么会这样?是否有不同的解释?

这样的事情会产生错误:

declare @myTable table 
(
    num numeric(5,2),
    den numeric(5,2)
)
insert into @mytable 
select 1, 2
union
select 1, 3
union
select 2, 3
union
select 2, 4
union
select 2, 5
union
select null, 1

select num/den as 'calc' from @myTable
where calc is not null
order by calc

但这会返回行:

declare @myTable table 
(
    num numeric(5,2),
    den numeric(5,2)
)
insert into @mytable 
select 1, 2
union
select 1, 3
union
select 2, 3
union
select 2, 4
union
select 2, 5
union
select null, 1

select num/den as 'calc' from @myTable
--where calc is not null
order by calc

1 个答案:

答案 0 :(得分:0)

正如Cannot use Alias name in WHERE clause but can in ORDER BY中所述,由于自然查询处理顺序而导致:

  1. @Configuration // @Import(Imprt.class) --> removed this public class Impl extends Abs {} @Configuration public abstract class Abs{ @Bean public ImportantBean importantBean(){ return new ImportantBean();} } @Configuration @Import(Impl.class) // ---> added new import here public class Imprt{ @Autowired private ImportantBean importantBean; }
  2. FROM
  3. ON
  4. OUTER
  5. WHERE
  6. GROUP BY | CUBE
  7. ROLLUP
  8. HAVING
  9. SELECT
  10. DISTINCT
  11. ORDER BY