当前位置:文档之家› 学习笔记708oracle

学习笔记708oracle

===============================
1. 拆分 复杂功能
2. 把重点放在 重要代码上.
=============================
rownum 不能用 = . 但
select * from (
select rownum n,a.* from tab1 a) tem
where tem.n= 5;
//子查询(select rownum)如同一张临时表.
// 而temp.n等于temp表中的一个字段, 赋了rownum值. 不再是rownum
//因此可以用等于==
======================== 游标 =======================================
同 ResultSet , next(), getXX()
------简单的显式游标-----------
声明, 打开, 移动, 关闭
//如同在ResultSet 中提取数据:
declare
cursor cur1 is select * from tab1; //声明ResultSet + SQL
begin
open cur1; //如同 rs = st.executeQuery(). 执行并获得数据
loop
fetch cur1 into lr; // 同next() + object.set(rs.getxx())+set()...
exit when cur1%notfound;
dbms_output.put_line(lr.id||lr...);
end loop;
close cur1; //同rs.close();
end;
/
//exit when 语句 必须放在fetch之下. 否则语句偏差
//fetch..into 先把指针移向下一条记录, 然后将值赋给变量
//游标的指针有三种情况:
1. 在fetch前, 此时 %found,%notfound都为false
2. 所有记录fetch完之前
3. fetch完后又fetch一次. 此时.....%found,%notfound和第一个一样. 好像都是false.
----------注意-----------------------------------------
游标对应的sql语句,
只能是select ,
且只能select * from . 而不能select 字段。!!
因此必须使用 lr tab1%rowtype;
//你想要查询字段好办啊: 应用lr.column 就可以了。
--------形参游标--------------------
1. cursor cur1 is select * from tab1 where condition;
2. cursor cur1(para number) is select * from tab1 where id > para;
begin
open cur1(1001); //打开时, 加入实参
//oracle中, 所有形参都不能加长度 (para number).
---------------------------------------
//局部变量 : l+var : lid, lname
//参数变量: p+var : pid, pname

--------for 循环游标----------------------
declare
cursor cur1 is xxxx;
begin
for lr in cur1 //不是 1 .. cur1了. lr同%rowtype. 里面包含了一整条记录.
loop
dbms_xxx
end loop;
end;
/
//不需要打开, 关闭, fetch提取游标. 退出循环
//没有了open,close, fetch,exit
-------游标 4 属性--------------------------
cur1%notfound //当前 没有记录时 true, '否则'false
cur1%found //当前有记录时 true, '否则'false
%rowcount //当前已经提取了几条记录. 不是还剩多少.
%isopen
//found和notfound 不会同存, 但有两者都不没有的情况.
//在open和 fetch之间, cur1%found和cur1%notfound 都是假 false .
plsql 中的 boolean 值 为: true, false, 和 null. 当空时既不为真也不为假, 不参与运算。
-------修改游标----------------------------------
游标中的内容, 实质上是提取了一份

表内容.
//当表内容改变时, 表内容与游标内容会不一致.
//使用游标记录来update 表记录时, 表记录改变了, 而游标记录仍然是以前的..
当要修改游标中的记录时, 才需要这功能'修改游标'.
否则不需要, 如: 游标中记录来自tab1, 但修改tab2. 游标不需修改.
//oracle内部使用了rowid
-- --修改cur1-
declare
cursor cur1 is select * from tab1 for update; //for update 表示当前游标是可以修改的
begin
for lr in cur1
loop
update tab1 set id=id+1 where current of cur1; //只修改表中当前记录, 不是全部
end loop;
end;
/
=============隐式游标=============================
insert ,update,delete, select..into 操作都会打开隐式游标.
所有隐式游标都叫 :sql
游标不需声明
begin
insert into xxx;
delete from tab1;
dbms_output.put_line(sql%rowcount);
//被操作了几条记录. 不会相加. 只等于最接近的一条dml
end;
/

相关主题
文本预览
相关文档 最新文档