PostgreSQL游標(biāo)
步驟:
1腰涧、定義一個游標(biāo):declare 游標(biāo)名 cursor
2碑宴、打開一個游標(biāo)
3、從結(jié)果集抓取行到游標(biāo)
4潘悼、檢查是否還有行需要抓取齐唆,如果是返回第三步執(zhí)行抓取嗤栓,如果不是,執(zhí)行第五條
5箍邮、關(guān)閉游標(biāo)
語法:
一茉帅、定義游標(biāo):
declare 游標(biāo)名 cursor [for sql語句];
for sql語句表示該游標(biāo)是否和sql語句進(jìn)行綁定,如果沒有for關(guān)鍵字指定媒殉,則表明該游標(biāo)是未綁定狀態(tài)
舉例1:
declare
mycursor1 cursor;
mycursor2 cursor for select * from film;
mycursor3 cursor(year integer) for select * from film where release_year=year;
(year integer)表示參數(shù)
二、打開游標(biāo):
(1)摔敛、打開未綁定的游標(biāo):
open mycursor1 for select * from film;
或:
query:= 'select * from film order by $1;'
open mycursor1 for execute query using release_year; [release_year為替換query排序的列名變量$1]
(2)廷蓉、打開已綁定的游標(biāo):
因?yàn)榻壎ǖ挠螛?biāo)已經(jīng)聲明了查詢,所以再打開查詢時,如果有參數(shù)桃犬,只需要將參數(shù)傳遞即可刹悴。
open mycursor2;
open mycursor3(year:=2005)
三、游標(biāo)的使用:
游標(biāo)抓取行:
fetch [option from] 游標(biāo)名 into 變量名;
fetch語句從游標(biāo)獲取下一行并分配給'變量名'攒暇,它可以是一條記錄土匀、一個行變量或一個逗號分隔的變量列表。如果沒有找到更多的行形用,'變量名'被設(shè)置為NULL(s)
默認(rèn)情況下就轧,如果不顯示指定方向,光標(biāo)將獲取下一行,option有如下值:
next
last
prior
first
absolute count
relative count
forward
backward
【注】:forward和backward僅適用于使用滾動選項聲明的游標(biāo)田度。
舉例:
fetch mycursor2 into row_film;
fetch next from mycursor3 into row_film;
四妒御、移動游標(biāo):
如果指向移動光標(biāo)而不想檢索任何行,可以使用move來移動游標(biāo)镇饺,而達(dá)到從某個位置再開始抓取行
move [option from] 游標(biāo)名;
option有如下值:
next
last
prior
first
absolute count
relative count
forward
backward
【注】:forward和backward僅適用于使用滾動選項聲明的游標(biāo)乎莉。
move mycursor1;
move next from mycursor2;
move relative -1 from mycursor3;
move forward 3 from mycursor3;
五、刪除或更新行:
可以通過游標(biāo)刪除或更新行
舉例:
update table_name set 列名='值' where current of 游標(biāo)名;
delete from table_name where current of 游標(biāo)名;
六奸笤、關(guān)閉游標(biāo):
close 游標(biāo)名;
close 關(guān)閉游標(biāo)后惋啃,允許使用open再次打開游標(biāo)。
舉例:
create or replace function get_film_titles(p_year integer)
returns text as $$
declare
titles text default '';
res_film record;
mycursor cursor(p_year integer) for select title,release_year from film where release_year=p_year; --定義游標(biāo)并綁定sql語句
begin
open mycursor(p_year); --打開游標(biāo)
loop --定義一個loop循環(huán)监右,來循環(huán)的抓取游標(biāo)的行
fetch mycursor into res_film;
exit when not found; --當(dāng)循環(huán)抓取帶最后一行之后边灭,抓取的為空即退出循環(huán)
if res_film.title like '%ful%' then
titles := titles||','||res_film.title||':'||res_film.release_year;
end if;
end loop;
close mycursor;
return titles;
end; $$
language plpgsql;
select get_film_titles(2006);
結(jié)果:
,Grosse Wonderful:2006,Day Unfaithful:2006,Reap Unfaithful:2006,Unfaithful Kill:2006,Wonderful Drop:2006
film源表.png