问题
How can we do fetching first 100 records next 100 records then next and so on in SQl Server from a table
回答1:
Use CTE and OFFSET:
@RecordIndex=Start Row No
@PageSize=No of Rows to fetch
;WITH CTE_Results
AS (
SELECT
ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) AS ROWNUM,
Count(*) over () AS TotalCount,
*
FROM TableName
)
Select * from CTE_Results
ORDER BY ROWNUM
OFFSET (@RecordIndex) ROWS
FETCH NEXT @PageSize ROWS ONLY;
回答2:
Here is the procedure that will give you pagination based on the page number and the record count. By default the procedure will return first 100 records from your table.
Create the below procedure in your database. Make sure you have mention the name of your table and ordering column.
CREATE PROCEDURE [dbo].[Fetchdata] @pageno INT=1, @pagesize INT=100 AS BEGIN SET NOCOUNT ON; DECLARE @sql VARCHAR(MAX)= ' SELECT * FROM YOURTABLE ORDER BY [YOURCOLUMN] OFFSET ('+CONVERT(VARCHAR(50),@pageno)+' - 1) * '+CONVERT(VARCHAR(50),@pagesize) +' ROWS FETCH NEXT '+CONVERT(VARCHAR(50),@pagesize)+' ROWS ONLY;' EXEC (@sql) ENDuse the below script to execute the procedure,with page number and page size as input.
EXEC [FetchData] @pageno=2 ,@pagesize=100
回答3:
Using row_number...
;with cte
as
(
select *,row_number() over (order by someuniquekey) as paging
)
select * from where paging between 1 and 100
you could also use Offset and Fetch like below,,
select
* from table
order by someuniquekey
offset 0 rows fetch next 100 rows only
Parameterized version of above ..
-- parameterized
DECLARE
@pagenum AS INT = 2,
@pagesize AS INT = 100;
SELECT *
FROM table
ORDER BY someuniquekey
OFFSET (@pagenum - 1) * @pagesize ROWS FETCH NEXT @pagesize ROWS ONLY;
Further reading..
http://sqlmag.com/blog/sql-server-2012-t-sql-glance-offsetfetch
回答4:
You can refer this page for your reference, it is same question related to paginatin
How to do pagination in SQL Server 2008
来源:https://stackoverflow.com/questions/39076858/how-can-we-do-pagination-in-fetching-the-value-with-100-records-each-in-sql