So, this is not your average “conditional view” on the question ... I have a rather complicated problem here. :-) I want my stored procedure to offer a conditional sort order for the results. This can usually be done as follows:
SELECT * INTO #ResultsBeforeSubset FROM MyTable ORDER BY CASE WHEN @SortAscending=1 THEN 'SortColumn' END ASC, CASE WHEN @SortAscending=0 THEN 'SortColumn' END DESC
I would like to make a CASE statement around the actual ASC / DESC , but that will not work. The reason this method works is because when @SortAscending not equal to the given value, the SQL server translates the CASE statement to the NULL constant. So, if @SortAscending is 0, you actually have:
ORDER BY NULL ASC, SortColumn DESC
Then the first sort expression just does nothing. This works because in a SELECT regular expression you can use a constant in an ORDER BY .
The problem is that the time that I sort in my saved proc is during a SELECT that contains the window function ROW_NUMBER() . So I want to put the CASE statement in its OVER clause, for example:
SELECT * INTO #ResultsBeforeSubset FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY CASE WHEN @SortAscending=1 THEN rowValues.[SortColumn] END ASC, CASE WHEN @SortAscending=0 THEN rowValues.[SortColumn] END DESC ) AS RowNumber, * FROM ( -- UNIONed SELECTs returning rows go here... ) rowValues ) rowValuesWithRowNum
Unfortunately, this causes the following error when starting the stored procedure:
Windowed functions do not support constants as ORDER BY clause expressions.
Since this is a window function clause, converting a CASE statement to a NULL constant is not valid.
Can anyone think that I can conditionally change the UNION ed SELECT s sort order and assign line numbers to each row resulting from these sorted results? I know that I can resort to building the entire query as a string and execute it as fully dynamic SQL, but I would rather avoid this if possible.
UPDATE: It seems that the problem is not caused by the CASE statement as such, but by the fact that I used only constant values in the CASE conditional clause. I started a new question about this curious behavior here .