PLSQL学习(一) 基础知识
很久以前自己整理的PLSQL一些基础知识,翻出来看看都是比较基础的内容,还是放上来好了。
参考的资料是《PL/SQL用户指南与参考》中译版,觉得这是一部很不错的入门书,感谢把这本书翻译出来的网友。
1、乘方的不同应用:
在SQL中乘方只能使用函数Power(a,b)来计算
但在PLSQL中可直接使用a**b表示
2、赋值语句Returning:
insert into t1 values(90,'SERVICE','BEIJING')
Returning rowid,name into row_id,info;
注:只限insert、update、delete一条记录时进行赋值
3、自定义参数——&:
可SQL和PLSQL中均可使用自定义参数,即需要自己输入值的参数
select * from ldcom where comcode=&a andname=&b;
PLSQL:
declare i int := &a; n int := &b;
4、绑定变量的使用:
可使用绑定变量的办法提高SQL效率
SQL> variable x number ;
SQL> exec :x := 8600 ;
SQL> select * from ldcom where comcode= :x ;
注:PLSQL中的declare即隐士绑定,无需再申明
可用Print查看绑定变量 SQL> print x;
也可使用查询SQL> select :x from dual;
实际的简单应用:
variable x number;
declare
v_date date;
begin
for i in1.. 10loop
:x := i;
select sysdate+:x into v_date from dual;
dbms_output.put_line(v_date);
end loop;
end;
/
在execute immediate中的应用:
declare
v_x t1.num%type;
begin
execute immediate'update t1 set num=8888 where id=:a returning num into :b'
using2returning into v_x;
dbms_output.put_line(v_x);
end;
注意returning的返回值在动态SQL中的操作格式
5、%TYPE和%ROWTYPE的区别:
%TYPE针对某一字段类型(数组也是单一的类型)
%ROWTYPE针对某一整表的类型(游标也是整表)
6、计数循环的逆序法:
for i in reverse10.. 100loop
注意reverse的位置不要记错
7、一般的游标使用法:
1、游标的正常使用需要四步
①定义游标
cursor c2(dept_no number default10) is----注意定义dept_no的方法
select name,agentcode from laagent where rownum <= dept_no;
②打开游标
open c3(dept_no =>20); ----可以重新定义dept_no
③提取游标数据
fetch c2 into dept_name,dept_loc;----字符类型、个数相等
fetch c3 into deptrec;----deptrec为rowtype
exit when c3%notfound;
④关闭游标
CLOSE c3;
⑤游标属性
%FOUND--布尔型属性,当最近一次读记录时成功返回,则值为TRUE;
%NOTFOUND--布尔型属性,与%FOUND相反;
%ISOPEN--布尔型属性,当游标已打开时返回TRUE;
%ROWCOUNT--数字型属性,返回已从游标中读取的记录数。
2、使用for自动打开、提取、关闭游标
FOR c1_rec IN c1 LOOP
FOR c1_rec IN(SELECT dname, loc FROM dept) LOOP
3、注:单一的SQL语句都是一个隐式的游标,属性为
SQL%FOUND--布尔型属性,当最近一次读记录时成功返回,则值为TRUE;
SQL%NOTFOUND--布尔型属性,与%FOUND相反;
SQL%ISOPEN--布尔型属性,当游标已打开时返回TRUE;
SQL%ROWCOUNT--数字型属性,返回已从游标中读取的记录数。
例如:DELETEFROM emp WHERE deptno=v_deptno;
IF SQL%NOTFOUND THEN ...
8、For Update锁定数据:
CURSOR emp_cursor is select empno,sal
from emp where deptno=v_deptno for update of sal nowait;
注意:其中的of sal,for update可以精确到某一个或几个字段
在使用了For Update之后可以在delete和update语句中使用current of cursor_name子句
for emp_record in emp_cursor loop
if emp_record.sal < 1500then
update emp set sal=1500where current of emp_cursor;
end if;
end loop;
但需注意:只能针对for update的表进行修改。
9、Package中的子程序可以重载
即函数名相同,参数个数不同
10、PL/SQL的执行顺序
在同一Package中,若要使用自身定义的Function或Procedure,则必须是之前定义过的。
同理,即便使用参数,也必须在前面定义过。
也就是说:一般最终的执行程序,会放在Package的最后,除非将所有部分都申明成Public。