I am trying to add sorting feature of my pagination stored procedure.
How can I do this, so far I created this one. It works fine but when pass the @sort
parameter, it didn't work.
ALTER PROCEDURE [dbo].[sp_Mk]
@page INT,
@size INT,
@sort nvarchar(50) ,
@totalrow INT OUTPUT
AS
BEGIN
DECLARE @offset INT
DECLARE @newsize INT
IF(@page=0)
begin
SET @offset = @page;
SET @newsize = @size
end
ELSE
begin
SET @offset = @page+1;
SET @newsize = @size-1
end
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
WITH OrderedSet AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY @sort DESC) AS 'Index'
FROM [dbo].[Mk]
)
SELECT *
FROM OrderedSet
WHERE [Index] BETWEEN @offset AND (@offset + @newsize)
SET @totalrow = (SELECT COUNT(*) FROM [dbo].[Mk])
END
Try use this:
This way:
I found this link and it works pretty well. Does not use string / dynamic sql. Instead it uses CASE statement
http://www.codeproject.com/Articles/590341/Stored-Procedure-with-Sorting-Paging-and-Filtering
Try using dynamic SQL to fix this.
Assuming
@sort
is thecolumn name
. try like thisinstead of providing @sort variable put
column name based on @sort
. Hope this will work.I'm adding an answer since so many of the other answers suggest dynamic SQL, which is not a best practice. You can add pagination using an
OFFSET-FETCH
clause, which provides you with an option to fetch only a window or page of results from a result set.Note:
OFFSET-FETCH
can be used only with theORDER BY
clause.Example: