Dynamic Sorting within SQL Stored Procedures

Yeah, it’s a pain, and the way you’re doing it looks similar to what I do:

order by
case when @SortExpr="CustomerName" and @SortDir="ASC" 
    then CustomerName end asc, 
case when @SortExpr="CustomerName" and @SortDir="DESC" 
    then CustomerName end desc,
...

This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs.

What I do from code is refactor the paging and sorting so I at least don’t have a lot of repetition there with populating values for @SortExpr and @SortDir.

As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it’s at least neat and recognizable when you go in to make changes.

Leave a Comment