简体   繁体   中英

Getting SQL results in parts

I know i can limit the count of received results using the TOP keyword, but is there a way to receive the next let say 1000 results using something like <give me the next 1000 results> which gives me each time the next cached 1000 ones?

So assume my query has 100000 and the first run i get 1-1000 i would like to receive the 1000-2000 and so on.

When the data is changing between queries, rownum/between solutions will give you approximations of the next chunk of data.

If you need to get a specific chunk of data from a fixed result, insert all of the results into a table and then consume the data as needed. The results will stay fixed until you refresh the data in the table again.

This works well when you must get the exact next set (forward or backward). This might be useful, depending on your situation.

You could use ROW_NUMBER()

SELECT 
    col1, 
    col2 
FROM 
(
     SELECT 
         col1, 
         col2, 
         ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
     FROM 
        MyTable
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN @startRow AND @endRow

Use the ROW_NUMBER function to order your data as desired in a subquery or CTE . Then select from that subquery/CTE with the desired values (eg, WHERE RowNum > 1000 AND RowNum <= 2000 ).

Suppose there is following table

create table #temp
(
    ID int Identity(1,1) ,
    name varchar(1000)
)

Suppose there are following records in the table

select * from #temp

总记录

We starts with declaring following variables

Declare @PageIndex INT //indicates the start index that means your page number

Declare @PageSize INT //the total amount of records you want to display in a page

Set @PageIndex = 1
Set @PageSize = 10

I am setting the page size = 10 because I have only 15 records in my table. But you can replace this number by 1000 or even greater than this number.

SELECT * FROM 
(
        SELECT ROW_NUMBER() OVER (ORDER BY ID)
        AS Row, * FROM #temp
)T WHERE Row between 
(@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize

If you execute the below query it will give you following records in the screen shot.

查询结果

While moving to second page using below query.

Declare @PageIndex INT
Declare @PageSize INT

set @PageIndex = 2
set @PageSize = 10

SELECT * FROM 
(
   SELECT ROW_NUMBER() OVER (ORDER BY ID)
   AS Row, * FROM #temp
)T WHERE Row between 
(@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize

The result will be below in the screen shot.

在此处输入图像描述

So similarly you can check with 1000 records.

Hope this will help you.

Let me know in case of any confusion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM