将记录分成页面

时间:2018-03-26 19:20:58

标签: sql sql-server

我使用SQL Server 2014中的下面的存储过程将表中的结果分解为每个240,000条记录的页面或文件。我从@PageNumber = 1开始,然后运行并调用此过程的集成服务包文件(.dtsx)并将记录导出到包含240,000条记录的.csv文件中。然后我更改@PageNumber = 2,再次运行.dtsx文件,导出下一个.csv文件。我重复这个过程,直到我用完了几百万的记录。有没有人有任何关于如何做到这一点的想法,而无需更改@PageNumber值并多次运行.dtsx包?感谢

DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 1
SET @RowspPage = 240000

SELECT  [SSN]
        ,[DOB]
        ,[LastName]
        ,[FirstName]
        ,[CustomerRecordID]
        ,[ADDate]
        ,[MiddleName] FROM (
         SELECT ROW_NUMBER() OVER(ORDER BY ID) AS NUMBER,
                 [SSN]
                ,[DOB]
                ,[LastName]
                ,[FirstName]
                ,[CustomerRecordID]
                ,[ADDate]
                ,[MiddleName]
        FROM [dbo].[All Borrowers 20180222]
               ) AS TBL
        WHERE 
            NUMBER BETWEEN ((@PageNumber - 1) * @RowspPage + 1) AND 
       (@PageNumber * @RowspPage)
        ORDER BY 
            NUMBER

2 个答案:

答案 0 :(得分:0)

DECLARE @PageNumber AS INT
declare @RowspPage AS INT
SET @PageNumber = 1
SET @RowspPage = 100

declare @more int = 1
while  (@more=1)
begin

SELECT  [SSN]
        ,[DOB]
        ,[LastName]
        ,[FirstName]
        ,[CustomerRecordID]
        ,[ADDate]
        ,[MiddleName] FROM (
         SELECT ROW_NUMBER() OVER(ORDER BY ID) AS NUMBER,
                 [SSN]
                ,[DOB]
                ,[LastName]
                ,[FirstName]
                ,[CustomerRecordID]
                ,[ADDate]
                ,[MiddleName]
        FROM [dbo].[All Borrowers 20180222]
               ) AS TBL
        WHERE 
            NUMBER BETWEEN ((@PageNumber - 1) * @RowspPage + 1) AND 
       (@PageNumber * @RowspPage)
        ORDER BY 
            NUMBER

            if @@rowcount = 0
                break
        set @pagenumber += 1
    end

     This will loop through and stop when you run out of rows (@@rownumber = 0). I am assuming that there always some rows.

答案 1 :(得分:0)

使用以下内容循环遍历每组240000:

DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 1
SET @RowspPage = 240000

while @PageNumber<=(select count(*) from [dbo].[All Borrowers 20180222])/cast(240000 as float)
begin

SELECT  [SSN]
        ,[DOB]
        ,[LastName]
        ,[FirstName]
        ,[CustomerRecordID]
        ,[ADDate]
        ,[MiddleName] FROM (
         SELECT ROW_NUMBER() OVER(ORDER BY ID) AS NUMBER,
                 [SSN]
                ,[DOB]
                ,[LastName]
                ,[FirstName]
                ,[CustomerRecordID]
                ,[ADDate]
                ,[MiddleName]
        FROM [dbo].[All Borrowers 20180222]
               ) AS TBL
        WHERE 
            NUMBER BETWEEN ((@PageNumber - 1) * @RowspPage + 1) AND 
       (@PageNumber * @RowspPage)
        ORDER BY 
            NUMBER


            set pagenumber=@pagenumber+1
            end