Pagination with the stored procedure
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 the ORDER BY
clause.
Example:
SELECT First Name + ' ' + Last Name FROM Employees
ORDER BY First Name
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;
One way (possibly not the best) to do it is to use dynamic SQL
CREATE PROCEDURE [sp_Mk]
@page INT,
@size INT,
@sort nvarchar(50) ,
@totalrow INT OUTPUT
AS
BEGIN
DECLARE @offset INT
DECLARE @newsize INT
DECLARE @sql NVARCHAR(MAX)
IF(@page=0)
BEGIN
SET @offset = @page
SET @newsize = @size
END
ELSE
BEGIN
SET @offset = @page*@size
SET @newsize = @size-1
END
SET NOCOUNT ON
SET @sql = '
WITH OrderedSet AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY ' + @sort + ') AS ''Index''
FROM [dbo].[Mk]
)
SELECT * FROM OrderedSet WHERE [Index] BETWEEN ' + CONVERT(NVARCHAR(12), @offset) + ' AND ' + CONVERT(NVARCHAR(12), (@offset + @newsize))
EXECUTE (@sql)
SET @totalrow = (SELECT COUNT(*) FROM [Mk])
END
Here is SQLFiddle demo
Assuming@sort
is the column name
. try like this
WITH OrderedSet AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY (CASE @sort WHEN 'column_name'
THEN column_name END ) DESC)
AS 'Index'
FROM [dbo].[Mk]
)
instead of providing @sort variable put column name based on @sort
. Hope this will work.