cur_data CURSORFOR SELECT column1, column2 FROM your_table; BEGIN OPEN cur_data; -- 打开游标 -- 循环遍历游标中的每一行 LOOP -- 从游标中提取一行数据 FETCH cur_data INTO v_column1, v_column2; -- 检查是否已到达游标末尾 EXIT WHENNOT FOUND; -- 处理提取的数据 END LOOP; -- 关闭游标 CLOSE cur_data; END;
注意:
1 动态游标用r_cur refcursor;
2表得行变量用record类型;
3 可以用move移动游标:Move next 1 from cursor_name;
例子
CREATEOR REPLACE FUNCTION calculate_department_salary_total() RETURNSTABLE (department_id INTEGER, total_salary NUMERIC) AS $$ DECLARE dept_cursor CURSORFOR SELECTDISTINCT department_id FROM employees; dept_id INTEGER; total NUMERIC :=0; BEGIN OPEN dept_cursor; LOOP FETCH dept_cursor INTO dept_id; EXIT WHENNOT FOUND; total :=0; FOR emp_salary IN (SELECT salary FROM employees WHERE department_id = dept_id) LOOP total := total + emp_salary; END LOOP; RETURN QUERY SELECT dept_id, total; END LOOP; CLOSE dept_cursor; END; $$ LANGUAGE plpgsql;