Sortable MVC Tables with Stored Procedure

Kmcnet 1,066 Reputation points
2025-02-06T18:27:54.7366667+00:00

Hello everyone and thanks for the help in advance. I am developing a MVC application that requires a sortable table. The issue is that the tables utilize queries that are best suited for stored procedures. While researching, I cam across older articles such as: https://stackoverflow.com/questions/15621609/t-sql-conditional-order-by, using either dynamic SQL or some type of CASE structure, but wondered if there were better ways to approach this problem. New example seem to rely on creating conditional LINQ queries within the controller, but I don't think that would be optimal. Any help would be appreciated.

Developer technologies ASP.NET ASP.NET Core
Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2025-02-06T22:17:49.1166667+00:00

    using either dynamic SQL or some type of CASE structure

    Yes, these are typically the solution. The solution with CASE breaks down quite quickly if you want to sort by more than one column, since you need keep different data types in different CASE expressions.

    The other alternative is to sort in the client.


2 additional answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2025-02-06T20:03:33.97+00:00

    T-SQL has OFFEST and FETCH NEXT

    SELECT SomeColumns 
    FROM MyTable
    WHERE aColumn = 'aValue'
    ORDER BY Id
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY;
    

  2. SurferOnWww 4,631 Reputation points
    2025-02-07T00:18:33.88+00:00

    I suggest that you consider use of Linq to entities which will be much easier and more practical for the ASP.NET Core MVC app if you do not have concrete reason to use stored procedure. Please see the following Microsoft tutorial:

    Tutorial: Add sorting, filtering, and paging - ASP.NET MVC with EF Core

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.