While asking another question , I found that SQL Server (both in 2005 and 2008) seems to have strange inconsistent behavior when working with CASE statements in window function articles. The following code gives an error:
declare @t table (SortColumn int) insert @t values (1), (2), (3) declare @asc bit set @asc = 0 select row_number() over (order by case when 1=1 then SortColumn end asc, case when 1=0 then SortColumn end desc) RowNumber , * from @t
Error Terminal functions do not support constants in ORDER BY clause expressions. I assume this is because the CASE statement can evaluate to NULL , which is a constant. As you might expect, this code gives the same error:
declare @t table (SortColumn int) insert @t values (1), (2), (3) declare @asc bit set @asc = 0 select row_number() over (order by NULL asc, NULL desc) RowNumber , * from @t
... presumably for the same reason. However, this code does not give an error:
declare @t table (SortColumn int) insert @t values (1), (2), (3) declare @asc bit set @asc = 0 select row_number() over (order by case when @asc=1 then SortColumn end asc, case when @asc=0 then SortColumn end desc) RowNumber , * from @t
The only difference here from the first code block is that I transferred one of the conditional operands of the CASE statements to the @asc variable. Now it works great. But why? CASE statements can still evaluate to NULL , which is a constant, so it shouldn't work ... but it does. Is it consistent in some way, or is it a special case of Microsoft's behavior?
All of this can be verified with this query .
Update: This restriction does not only apply to OVER clauses (although they give a different error) - this applies to all ORDER BY clauses with SQL Server 2005. Here is a query that also shows a constraint with a regular SELECT ORDER BY .