Oracle游标总结
Posted 代码改变生活
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Oracle游标总结相关的知识,希望对你有一定的参考价值。
1.声明游标
declare teacher_id number(5); teacher_name varchar2(5); teacher_title varchar2(50); teacher_sex char(1); cursor teacher_cur is select tid,tiname,title,sex from teachers where tid<117;
2.打开游标
open 游标名;
declare teacher_id number(5); teacher_name varchar2(5); teacher_title varchar2(50); teacher_sex char(1); cursor teacher_cur is select tid,tiname,title,sex from teachers where tid<117; open teacher_cur;
3.提取游标
fetch 游标名 into 变量列表
declare teacher_id number(5); teacher_name varchar2(5); teacher_title varchar2(50); teacher_sex char(1); cursor teacher_cur is select tid,tiname,title,sex from teachers where tid<117; open teacher_cur; fetch teacher_cur into tid,tinme,title,sex;
4.关闭游标
close 游标名
declare teacher_id number(5); teacher_name varchar2(5); teacher_title varchar2(50); teacher_sex char(1); cursor teacher_cur is select tid,tiname,title,sex from teachers where tid<117; open teacher_cur; fetch teacher_cur into tid,tinme,title,sex; Loop EXIT WHEN NOT teacher_cur%FUND; IF teaher_sex = ‘M‘ THEN INSERT INTO MALE_TEACHERS(TID,TNAME,TITLE) VALUES(); ELSE INSERT INTO FEMALE_TEACHERS(TID,TNAME,TITLE) VALUES(teacher_id,teacher_name,teacher_title); END IF; FETCH teacher_cur INTO teacher_id,teacher_name,teacher_title,teacher_sex; END LOOP; CLOSE teacher_cur; END;
使用显示游标:
1):使用前用游标名%ISOPEN检查打开状态,只有值为TRUE是才可使用
2):使用游标每次都要用%NOTFUND,%FUND确认是否返回成功
3):提取游标时对应变量个数一致
4):必须关闭游标释放资源
1.%fund是否找到有效行,是则为true 否则是false
open teacher_cur; fetch teacher_cur into teacher_id,teacher_name,teacher_title,teacher sex; loop exit when not teacher_cur%found; end loop
SQL%fund
delete from teachers where tid=teacher_id; if SQL%found then insert into success values(tid); else insert into fail values(tid); end if;
2.%NOTFOUND
OPEN teacher_cur; FETCH teacher_cur INTO teacher_id,teacher_name,teacher_title,teacher_sex; LOOP EXIT WHEN teacher_cur%NOTFOUND; END LOOP
SQL%NOTFOUND
DELETE FROM TEACHERS WHERE TID = teacher_id; IF SQL%NOTFOUND THEN INSERT INTO FALL VALUES(TID); ELSE INSERT INTO SUCCESS VALUES(TID); END IF;
3.%ROWCOUNT
该属性记录了游标抽取过的记录行数,也可以理解为当前游标所在的行号,这个属性在循环判断中有效
LOOP FETCH teacher_our INTO teacher_id,teacher_name,teacher_title,teacher_sex; EXIT WHEN teacher_cur%ROWCOUNT=10;--只抽取10条记录 ... END LOOP;
用FOR语句控制游标的循环,系统隐含的定义了一个数据类型为%ROWCOUNT的记录,作为循环计数器,并将隐士的打开和关闭游标
FOR teacher_record in teacher_cur LOOP --teacher_record作为记录名,隐含的代开游标teacher_cur INSERT INTO TEMP TEACHERS(TID,TNAME,TITLE,SEX) VALUES(teacher_record,tid,teacher_record,tname,teacher_record,title,teacher_record.sex); END LOOP
4.%ISOPEN
... ...
5.参数话游标:
DECLARE --定义游标是带上参数CURSOR_ID CURSOR teacher_cur(CURSOR_id NUMBER) IS SELECT TNAME,TITLE,SEX FROM TEACHERS WHERE TID=CURSOR_id;--使用参数 BEGIN OPEN teacher_cur(my_tid);--带上参数 LOOP FETCH teacher_cur INTO teacher_name,teacher_title,teacher_sex; EXIT WHEN teacher_cur%NOTFOUND; ... END LOOP; CLOSE teacher_cur; END;
以上是关于Oracle游标总结的主要内容,如果未能解决你的问题,请参考以下文章