DotNetStudent
DotNetStudent

Reputation: 899

T-SQL: ORDER BY 'Expression'

All stored procedures which return data to the presentation layer of the webservice I am currently developing take as parameters two integers, @StartingRow and @MaximumRows, so that I can paginate results without retrieving the whole result list everytime. Now I would like to introduce sorting in these procedures, but from what I see everyone uses dynamic SQL to do the ordering:

EXEC ( 'WITH [Results] AS 
        ( SELECT * , 
             ROW_NUMBER() OVER ( ORDER BY ' + @SortExpression + @Direction + ')  AS 'RowNumber' 
          FROM [SomeTable] ) 
        SELECT [Column1] , [Column2] 
        WHERE ( [RowNumber] BETWEEN ' + @StartingRow + 
                          ' AND ( ' + @StartingRow + ' + ' + @MaximumRows + ' - 1) )' )

The problem with this approach is that I can't use dynamic SQL due to customer's demand, so that I can't specify the column according to which the results should be sorted. What are my options, then?

Upvotes: 0

Views: 1061

Answers (1)

Andomar
Andomar

Reputation: 238126

You could use a case. This example sorts on Col1 when @SortParameterequals 1. For parameter 5, it sorts by Col2 in descending order.

order by
        case 
        when @SortParameter = 1 then Col1
        when @SortParameter = 2 then Col2
        ...
        end
,       case 
        when @SortParameter = 4 then Col1
        when @SortParameter = 5 then Col2
        ...
        end DESC

SQL Server cannot use indexes with this approach. Which is the prime reason for using dynamic SQL instead.

Upvotes: 2

Related Questions