如何根据其数据分页选择查询的结果

时间:2014-07-23 20:09:12

标签: sql-server

我有一个表定义如下:tbl01(数据),数据是varchar(max)。数据填充有可变数量的固定长度的字符串。例如(这只是示例,而不是真实数据),

insert into tbl01 values(replicate(‘a’, 5)+char(13)+char(10)+ replicate(‘b’, 5))
insert into tbl01 values(replicate(‘b’, 5))
insert into tbl01 values(replicate(‘c’, 5)+char(13)+char(10)+space(5)+char(13)+char(10)+ replicate(‘d’, 5))

表格如下:

aaaaabbbbb
bbbbb
ccccc     ddddd

当我将表导出到txt文件时,将有6行。

aaaaa
bbbbb
bbbbb
ccccc

ddddd

现在我需要分页数据,例如每页两行,并添加页眉和页脚,例如

Page 1 header
aaaaa
bbbbb
Page 1 footer
Page 2 header
bbbbb
ccccc
Page 2 footer
Page 3 header

ddddd
Page 3 footer

show stop是如何分页这个表,因为每行的行数是可变的?

1 个答案:

答案 0 :(得分:0)

这似乎有效(在SQL 2012中测试过)。我假设PK值递增。

CREATE TABLE #Tbl01 (
    ID INT IDENTITY PRIMARY KEY,
    SomeData VARCHAR(MAX)
)
GO

insert into #Tbl01 values(replicate('a', 5)+char(13)+char(10)+ replicate('b', 5))
insert into #Tbl01 values(replicate('b', 5))
insert into #Tbl01 values(replicate('c', 5)+char(13)+char(10)+space(5)+char(13)+char(10)+ replicate('d', 5))
GO

--This CTE displays the original rows that were inserted, plus the "lines" in each row broken out into separate rows.
;WITH RawData AS
(
    SELECT ID AS RowId, SomeData, CHARINDEX(CHAR(13) + CHAR(10), SomeData, 1) NewLinePos, 1 StringNumber
    FROM #Tbl01
    UNION ALL
    SELECT RowId, RIGHT(SomeData, DATALENGTH(SomeData) - NewLinePos - 1), 
        CHARINDEX(CHAR(13) + CHAR(10), RIGHT(SomeData, DATALENGTH(SomeData) - NewLinePos - 1), 1), StringNumber + 1
    FROM RawData
    WHERE NewLinePos > 0
    UNION ALL
    SELECT RowId, LEFT(SomeData, CHARINDEX(CHAR(13) + CHAR(10), SomeData, 1)), 0, StringNumber
    FROM RawData
    WHERE NewLinePos > 0
),

--This CTE shows just the "lines" broken out into separate rows with grouping info.
DataLines AS
(
    SELECT SomeData,
        ROW_NUMBER() OVER(ORDER BY RowId, StringNumber) RowNum, 
        (ROW_NUMBER() OVER(ORDER BY RowId, StringNumber) + 1) / 2 GroupNum, 2 GroupItemOrder
    FROM RawData
    WHERE NewLinePos = 0
),

--This CTE creates the output rows for paging.
OutputLines AS
(
    SELECT *
    FROM DataLines
    UNION ALL
    SELECT 
        CASE 
            WHEN RowNum % 2 = 1 THEN 'Page ' + CAST(GroupNum AS VARCHAR(MAX)) + ' header'
            ELSE 'Page ' + CAST(GroupNum AS VARCHAR(MAX)) + ' footer'
        END,
        RowNum, GroupNum,
        CASE 
            WHEN RowNum % 2 = 1 THEN 1
            ELSE 3
        END

    FROM OutputLines 
    WHERE GroupItemOrder = 2
)
--Final query is the output rows for paging in the correct order.
SELECT SomeData
FROM OutputLines
ORDER BY GroupNum, GroupItemOrder

--Cleanup as needed
--DROP TABLE #Tbl01