声明游标: declare cursor cursor_name(游标名) is select_statement(查询语句);
打开游标: open cursor_name;
读取游标中数据:fetch cursor_name into record变量
关闭游标: close cursor_name;
案列1:
declare
--定义游标
cursorcur_xsjbxx is
select* from stuinfo order by stuid;
--定义记录变量
ls_curinfo cur_xsjbxx%rowtype;
begin
opencur_xsjbxx;--打开游标
loop
FETCH cur_xsjbxx
INTO ls_curinfo;--获取记录值
EXIT WHEN cur_xsjbxx %NOTFOUND;
dbms_output.put_line('学号:'|| ls_curinfo.stuid || ',姓名:'|| ls_curinfo.STUNAME);
end loop;
close cur_xsjbxx;--关闭游标
end;
案列2:
CREATE OR REPLACE TRIGGER EMP_INFO
AFTER INSERT OR UPDATE OR DELETE ON EMP
DECLARE
CURSOR CUR_EMP IS
SELECT DEPTNO, COUNT(EMPNO) AS TOTAL_EMP, SUM(SAL) AS TOTAL_SAL FROM EMP GROUP BY DEPTNO;
BEGIN
DELETE DEPT_SAL; --触发时首先删除映射表信息
FOR V_EMP IN CUR_EMP LOOP
--DBMS_OUTPUT.PUT_LINE(V_EMP.DEPTNO || V_EMP.TOTAL_EMP || V_EMP.TOTAL_SAL);
--插入数据
INSERT INTO DEPT_SAL
VALUES
(V_EMP.DEPTNO, V_EMP.TOTAL_EMP, V_EMP.TOTAL_SAL);
END LOOP;
END;