簡體   English   中英

檢索SQL Server查詢中的特定行數

[英]Retrieve specific number of rows in a SQL Server query

行:

1  Test1
2  Test2
3  Test3
12 Test4
5  Test1
6  Test2
7  Test1
8  Test2

我試圖從ssis包中導出xml數據文件。

一個例子:我需要為每個文件創建2行。 如果SSIS循環容器中的查詢,sql命令可以確保每次返回正確的2行。

嘗試這個。

Create table Temp (id smallint, Col1 varchar(25))
insert into Temp select 1, 'Test1'
insert into Temp select 2,  'Test2'
insert into Temp select 3,  'Test3'
insert into Temp select 12, 'Test4'
insert into Temp select 5,  'Test1'
insert into Temp select 6,  'Test2'
insert into Temp select 7,  'Test1'
insert into Temp select 8,  'Test2'
insert into Temp select 10, 'Test1'


declare @i int = (select Max(RowNum) from (select ROW_NUMBER() over(order by id) as RowNum,id,Col1 from Temp) as temp)

declare @countnum int = 1
declare @NoOfRows int = 100

while(@countnum <= @i)
begin 

select * from (select ROW_NUMBER() over(order by (select 0)) as RowNum,id,Col1 from Temp) as temp where RowNum >= @countnum and RowNum < @countnum + @NoOfRows

set @countnum = @countnum + @NoOfRows
end

drop table Temp

如果您使用的是SQL Server 2012或更高版本,則可以在T-SQL中使用SQL分頁增強功能

請檢查以下查詢,以查看是否有幫助。請注意,@ n參數應視為循環號

/*
create table tbl (id smallint, txt varchar(25))
insert into tbl select 1, 'Test1'
insert into tbl select 2,  'Test2'
insert into tbl select 3,  'Test3'
insert into tbl select 12, 'Test4'
insert into tbl select 5,  'Test1'
insert into tbl select 6,  'Test2'
insert into tbl select 7,  'Test1'
insert into tbl select 8,  'Test2'
insert into tbl select 9,  'Test1'
delete tbl where id = 9
*/

declare @rowsperpage int = 2
declare @x int = @rowsperpage
declare @n int = 1

while @x = @rowsperpage
begin

SELECT *
FROM tbl
ORDER BY id
OFFSET (@n-1)*@rowsperpage ROWS
FETCH NEXT @rowsperpage ROWS ONLY

select @x = @@ROWCOUNT
set @n = @n + 1

end

您可以在引用的教程中找到有關使用offset和fetch的SQL分頁的更多詳細信息

我希望它有所幫助

我建議您先准備結果集,識別對(兩行),然后迭代此結果集並從變量創建XML輸出。 我不知道您要准備的XML的復雜性,但至少可以在下面找到的查詢可以幫助您准備對識別器,如果您需要獲取更復雜的數據,可以使用它們。

根據您的數據:

0)准備變量:data - object,id int,name varchar(20)

1)返回結果集作為對象 - 查詢下面准備具有相同id的對(row_group列)

2)在此對象上使用Foreach Ado net枚舉器進行迭代,將數據插入變量中

3)在Foreach內部使用基於row_group的動態文件名准備數據流任務

with 
data
as
(
select *, row_number() over(order by id) as row
from test_data
  )
,
pairs
as
(
select * ,
case when row%2=0 then row-1 else row end  as row_group
from data
 )

select id, name, row_group
from pairs
order by row_group

使用LIMIT從查詢中獲取正確的記錄子集:

SELECT * FROM Orders LIMIT 10, 2

從記錄11開始將從訂單中檢索兩個記錄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM