--2 建立函數,不帶 for update 屬性
CREATE or replace FUNCTION fun_employee() RETURNS INTEGER AS $$
DECLARE
update_flag INTEGER ;
rec refcursor;
BEGIN
update_flag :=0;
for rec in (select * from employee ) loop
update employee set dep_no = 3;
update_flag:=update_flag+1;
RAISE NOTICE ' The update_flag is %', update_flag;
end loop;
return 0;
END;
$$ LANGUAGE 'plpgsql';
--3 建立函數,加上 for update 屬性
CREATE or replace FUNCTION fun_employee_for_update() RETURNS INTEGER AS $$
DECLARE
update_flag INTEGER ;
rec refcursor;
BEGIN
update_flag :=0;
for rec in (select * from employee for update ) loop
update employee set dep_no = 3;
update_flag:=update_flag+1;
RAISE NOTICE ' The update_flag is %', update_flag;
end loop;
return 0;
END;
$$ LANGUAGE 'plpgsql';
--4 測試 fun_employee()
skytf=> select fun_employee();
NOTICE: The update_flag is 1
NOTICE: The update_flag is 2
NOTICE: The update_flag is 3
NOTICE: The update_flag is 4
NOTICE: The update_flag is 5
NOTICE: The update_flag is 6
NOTICE: The update_flag is 7
NOTICE: The update_flag is 8
NOTICE: The update_flag is 9
NOTICE: The update_flag is 10
fun_employee
--------------
0
(1 row)
--5 測試 fun_employee_for_update()
skytf=> select fun_employee_for_update();
NOTICE: The update_flag is 1
NOTICE: The update_flag is 2
NOTICE: The update_flag is 3
NOTICE: The update_flag is 4
NOTICE: The update_flag is 5
NOTICE: The update_flag is 6
NOTICE: The update_flag is 7
NOTICE: The update_flag is 8
NOTICE: The update_flag is 9
NOTICE: The update_flag is 10
fun_employee_for_update
-------------------------
0
(1 row)
備忘:根據測試結果輸出,兩個函數都執行了 10 次 update 語句。
--6
把什麼的函數改為如下聲明的cursor,只執行一次
CREATE or replace FUNCTION fun_employee_for_update() RETURNS INTEGER AS $$
DECLARE
update_flag INTEGER;
cur cursor is select * from employee for update;
rec employee%rowtype;
BEGIN
update_flag :=0;
for rec in cur loop
update employee set dep_no = 3;
update_flag:=update_flag+1;
RAISE NOTICE ' The update_flag is %', update_flag;
end loop;
return 0;
END;
$$ LANGUAGE 'plpgsql';