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?
You could use a
case. This example sorts onCol1when@SortParameterequals 1. For parameter 5, it sorts byCol2in descending order.SQL Server cannot use indexes with this approach. Which is the prime reason for using dynamic SQL instead.