Curious inconsistent behaviour from SQL Server in windowed function clauses?

后端 未结 2 1024
时光说笑
时光说笑 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 10:59

    The evaluations in your first example will never change.

    You are comparing a constant to a constant which will constantly result in a constant.

    1=1 will always be TRUE.
    1=0 will always be FALSE.

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