IF @STRWHERE IS NOT NULL AND @STRWHERE != ''
BEGIN
SET @STRFILTER = ' WHERE ' + @STRWHERE + ' '
END
ELSE
BEGIN
SET @STRWHERE = '1=1'
SET @STRFILTER = ''
END
SET @SQL='SELECT @ROWTOTAL=COUNT(0) FROM '+@TBLNAME + @STRFILTER
EXEC SP_EXECUTESQL @SQL,N'@ROWTOTAL INT OUT',@ROWTOTAL OUT
BEGIN
IF(@ORDERTYPE=1)
SET @SORDER = @PRIMARYCOLUMNS + ' DESC '
ELSE
SET @SORDER=@PRIMARYCOLUMNS+' ASC '
IF @PAGEINDEX < 1
SET @PAGEINDEX = 1
BEGIN
DECLARE @START_ID VARCHAR(50)
DECLARE @END_ID VARCHAR(50)
SET @START_ID = CONVERT(VARCHAR(50),(@PAGEINDEX - 1) * @PAGESIZE + 1)
SET @END_ID = CONVERT(VARCHAR(50),@PAGEINDEX * @PAGESIZE)
SET @SQL = ' SELECT '+'*'+ 'FROM (SELECT ROW_NUMBER() OVER(ORDER BY '+@SORDER+') AS ROWNUM,'+'*'
+ 'FROM '+@TBLNAME+') AS D
WHERE ROWNUM BETWEEN '+@START_ID+' AND '
+@END_ID +' AND '+ @STRWHERE
+' ORDER BY '+@SORDER
END
END
SET @SQL=' SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY '+@SORDER+') AS ROWNUM,*'
SET @SQL=@SQL+ ' FROM( SELECT TOP(100) PERCENT * FROM '+@TBLNAME
+' WHERE '+@STRWHERE+' ORDER BY '+@SORDER+')TM1)TM '
SET @SQL=@SQL+' WHERE ROWNUM BETWEEN '+@START_ID+' AND ' +@END_ID