Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active December 18, 2015 11:09
Show Gist options
  • Select an option

  • Save ichiroku11/5773839 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/5773839 to your computer and use it in GitHub Desktop.
offsetとfetchでページング
if object_id('Sequence') is not null
drop table Sequence;
-- シーケンスのソース(共通テーブル式を使って1~50までの連番生成)
with Source(Value) as(
select 1
union all
select Value + 1
from Source
)
select top 50 *
into Sequence
from Source;
select *
from Sequence
order by Value;
go
-- 20までスキップして、21から30までの10個を取得
select *
from Sequence
order by Value
offset 20 rows -- 20個スキップして
fetch next 10 rows only; -- 10個取得
go
-- 46から10個を取得
select *
from Sequence
order by Value
offset 45 rows
fetch next 10 rows only;
go
-- 50から10個を取得
select *
from Sequence
order by Value
offset 50 rows
fetch next 10 rows only;
go
-- OFFSET 句に負の値を指定するとエラー
select *
from Sequence
order by Value
offset -1 rows
fetch next 2 rows only;
go
-- FETCH 句に0以下の値を指定するとエラー
select *
from Sequence
order by Value
offset 0 rows
fetch next 0 rows only;
go
-- FETCH 句は省略できる
select *
from Sequence
order by Value
offset 45 rows
go
@ichiroku11

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment