2014-07-23 72 views
1

我有一個表定義爲:tbl01(data),data is 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 

的顯示塞是如何頁面的這個表,因爲數量每行的行數是可變的?

+0

在txt文件中尋呼?我不確定我是否理解這個問題。 – JodyT

+0

我需要在文本文件中添加頁眉和頁腳。但我需要頁面查詢結果第一對不對? – GLP

+0

我想我可以猜測...但你能告訴我們所需的查詢輸出嗎? – DMason

回答

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 
+0

@GLP,爲你做了這項工作? – DMason

相關問題