Sortable MVC Tables with Stored Procedure

Kmcnet 966 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.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,785 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,485 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,690 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 117.2K Reputation points MVP
    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 29,786 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 3,796 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.