Curious inconsistent behaviour from SQL Server in windowed function clauses?

后端 未结 2 1053
时光说笑
时光说笑 2021-01-12 10:27

Whilst asking another question, I discovered that SQL Server (happens both in 2005 and 2008) seems to have strange inconsistent behaviour when dealing with CASE

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 11:21

    Books online indicates that "A sort column can include an expression, but when the database is in SQL Server (90) compatibility mode, the expression cannot resolve to a constant." however it does not define "constant".

    From thinking about it and some experimentation it seems clear that this means an expression for which a literal constant value can successfully be calculated at compile time.

    /*Works - Constant at run time but SQL Server doesn't do variable sniffing*/
    DECLARE @Foo int
    SELECT ROW_NUMBER() OVER (ORDER BY @Foo) 
    FROM master..spt_values 
    
    /*Works - Constant folding not done for divide by zero*/
    SELECT ROW_NUMBER() OVER (ORDER BY $/0) 
    FROM master..spt_values 
    
    /*Fails - Windowed functions do not support 
       constants as ORDER BY clause expressions.*/
    SELECT ROW_NUMBER() OVER (ORDER BY $/1) 
    FROM master..spt_values 
    

提交回复
热议问题