hi Please check below query
Create PROCEDURE [dbo].[tblProductSelectByCatalogid] (
@StrSortBy varchar(50)='Coumn name',
@StrSortOrder varchar(50)='ASC/DESC',
@intPageNum int=1,
@intPageSize int=10,
)
AS
SET NOCOUNT ON
declare @SQL nvarchar(max)
Declare @Condition nvarchar(max)
DECLARE @strSQLCount VARCHAR(MAX)
DECLARE @strFinalSQL VARCHAR(MAX)
SET @Condition = ''
set @SQL ='
SELECT * FROM [tablename] WHERE Condition'
SET @SQL = @SQL + @Condition
IF @intPageSize <> 0
BEGIN
SET @strFinalSQL = ' SELECT * FROM ('
SET @strFinalSQL = @strFinalSQL + ' Select Row_Number() OVER (Order by ' + @StrSortBy + ' ' + @StrSortOrder + ') As RowNum,* From( '
SET @strFinalSQL = @strFinalSQL + @SQL
SET @strFinalSQL = @strFinalSQL + ' )T )T1 '
SET @strFinalSQL = @strFinalSQL + ' Where RowNum BETWEEN ' + Cast((@intPageNum - 1) * @intPageSize + 1 as varchar(5)) + ' AND ' + Cast(@intPageNum * @intPageSize as varchar(5))
END
ELSE
BEGIN
SET @strFinalSQL = ' Select Row_Number() OVER (Order by ' + @StrSortBy + ' ' + @StrSortOrder + ') As RowNum,* From( '
SET @strFinalSQL = @strFinalSQL + @SQL
SET @strFinalSQL = @strFinalSQL + ' )T'
END
EXEC (@strFinalSQL)
print(@strFinalSQL)
SET @strSQLCount = ' Select Count(*) as intTotalRecords From( '
SET @strSQLCount = @strSQLCount + @SQL
SET @strSQLCount = @strSQLCount + ' )T'
Exec (@strSQLCount)
in above query you can see that we pass the page no and page size
if we pass page no 1 and size equal to 10 then first it will take 10 record
next time we will increase page no to 2 then procedure will return 11-20 record like wise.
you can provide you combination by setting the Pagesize and page no.
Hope this will help :)