PDA

View Full Version : Cursor Phan Trang Trong Sql



savianh
13-04-2005, 10:14
De phan trang trong SQL thi co nhieu cach lam, minh co cach nay cung thay hay hay gioi thieu de ban thu nha, do la dung CURSOR de lay du lieu

Trước tiên thì phải tìm hiểu xem cursor là gì.

Cursor là một object database giúp truy cập và xử lý dữ liệu theo hàng trong result set được lấy từ câu truy vấn SELECT với điều kiện WHERE.

Cấu trúc của một CURSOR như sau: DECLARE [cursor_name] [INSENSITIVE| SCROLL] CURSOR

FOR {select query | repared_query}

FOR{READ | ONLY | UPDATE}

Ví dụ: declare test_cursor SCROLL CURSOR for select * from solutions where group_id = 1

Để lấy một row bất kỳ từ CURSOR đã có dùng cấu trúc:

FETCH [NEXT| PRIOR | FIRST | LAST | ABSOLUTE n | RELATIVE n] FROM cursor_name

Ví dụ: FETCH ABSOLUTE 30 from test_cursor -- lấy ra hàng thứ 30 from CURSOR

Sau đây là một ví dụ:

Tôi sẽ tạo ra một procedure để lấy 20 rows cho một trang được truyền từ trên xuống với điều kiện thuộc một group nào đó

create proc proc_20solutions_forgroup_inallgroups @curpage int,@group_id int
as
if @curpage < 0
set @curpage=0
-- check num of page
declare @numrowperpage int
declare @condition int
declare @from int
-- test detail
declare @id int
DECLARE test_cursor SCROll CURSOR
FOR SELECT isolution_id FROM solutions where igroup_id=@group_id
OPEN test_cursor -- mở cursor lên để bắt đầu có thể xử lý trên cursor

-- check page:
-- if( @@CURSOR_ROWS % @numrowperpage > 0)
-- check numrows again
if(@curpage * @numrowperpage > @@CURSOR_ROWS) -- lay ve so hang nhan duoc
set @curpage = @curpage - 1
set @numrowperpage = 20
set @from = @numrowperpage * @curpage
if @from = 0
set @from = 1
--while(@@FETCH_STATUS = 0)
--begin
FETCH ABSOLUTE @from FROM test_cursor INTO @id -- gan id vao mot bien @id
set @condition = @id
--end
CLOSE test_cursor -- đóng cursor , kết thúc xử lý
DEALLOCATE test_cursor
--print @condition

-- bay giờ thì có thể lấy được chính xác 20 rows từ bảng solutions rồi
select top 20 * from solutions where isolution_id <=@condition and igroup_id=@group_id


theo : http://www.itgatevn.com/exchange.aspx?u=la&qid=12