Scott Mitchell and Greg Hamilton posted an excellent example for a stored procedure to support paging on web sites in this article: http://www.4guysfromrolla.com/webtech/041206-1.shtml. Here, I have taken their best example one step further and added support for sorting as well. The program can now pass the column to sort by to the stored procedure (along with ASC or DESC if desired. The only complex piece to this was that in having a dynamic sort column, the bulk of the SQL to execute must be dynamic. Note that I was unable to use the optimal stored proc by Greg as a starting point because the user could choose to sort on any column which could include rows with null values, and that would throw off the results.
PROCEDURE [dbo].[usp_PagedResults_New_Rowcount_Sortable]
@maxRow int
@maxRow = (@startRowIndex + @maximumRows) – 1
ROWCOUNT @maxRow
(‘
+ @sortingColumn + ‘
+ @maximumRows + ‘
+ @startRowIndex)
ROWCOUNT 0
Be carful. The above code will open the SP to SQL injection.Regards,Richard
Of course any stored proc risks SQL injection if a string is passed in; and it is used as part of a dynamic SQL. My development always uses ADO.Net now, and ADO.Net does a really good job of preventing SQL Injection; especially when ado.net parameters are used. 🙂