一 PL/SQL简介
1 SQL:结构化的查询语句
2 PL/SQL优点与特性:
提高运行效率==>>提高运行效率的其他方式(存储过程,分页,缓存,索引)
模块化设计
允许定义标识符(变量,游标,常量,异常等)
过程化(融入了第三代语言的特点,具有过程化)
兼容性好(可在oracle提供的应用工具中使用)
可处理错误(提高程序健壮性,避免异常问题,简化错误处理)
3 语言基础:
支持:select语句,dml(数据操作语句),事务控制语句
不支持:ddl(数据定义语句) 如:创建表,字段,存储过程,数据库等
4 块
分类:无名块,匿名块,有名块(将块放在存储过程/函数中)
定义无名块:
declare 定义:变量/常量/游标/例解等 begin 执行:PL/SQL,SQL语句 [exception 异常处理:处理运行错误](可选部分) end;
5 Oracle中定义标识符
常量:c_name;
变量:v_name; 变量赋值:(v_name varchar2(30) :='张三')(:=)
游标:cus_name;
异常:e_name;
6 数据类型
标量类型(矢量):int,binary_double,binary_float,binary_integer, float,integer,numric,number,char,character,long, long raw,nchar,rowid,string,varchar,varchar2,bollean,date,timestamp(定义日期和时间数据)
属性类型(存储更多的数据):%type,%rowtype(行类型),record(自定义记录类型),table(表类型),varray(动态数组类型)
实例:record自定义记录类型
declare type r_name is record( v_name dept. dname%type, v_loc dept.loc%type ); rec_v r_name; select dname,loc into rec_v.v_name,rec_v.v_loc from dept where deptno=10 ; end;
参数类型:ref cursor,ref object_type
复合类型:befile,blog,clob,nclob
7 控制结构
条件分支语句:
语法:
if 条件 then 处理 elsif 条件 then 处理 else 处理 end if;
实例:
declare v_name varchar2(20); begin select scott.emp.ename into v_name from scott.emp where scott.emp.empno=7369; if v_name='SMITH' then dbms_output.put_line('SMITH'); else dbms_output.put_line('员工姓名:'||v_name); end if; end;
case语句:执行多重条件分支操作
语法:
case 条件 when 表达式 then 处理 when 表达式 then 处理 when 表达式 then 处理 else 处理--==>>default end case;
实例:
declare v_no scott.emp.deptno%type; begin v_no :=&deptno; case v_no when 10 then update scott.emp set scott.emp.comm=100 where scott.emp.deptno=v_no; when 20 then update scott.emp set scott.emp.comm=80 where scott.emp.deptno=v_no; when 30 then update scott.emp set scott.emp.comm=60 where scott.emp.deptno=v_no; else dbms_output.put_line('该部门不存在'); end case; end;
实例2:使用多重条件
declare v_sal scott.emp.sal%type; v_name scott.emp.ename%type; begin select scott.emp.ename,scott.emp.sal into v_name,v_sal from scott.emp where scott.emp.empno=&empno; case when v_sal<2000 then update scott.emp set scott.emp.comm=100 where scott.emp.ename=v_name; when v_sal<3000 then update scott.emp set scott.emp.comm=80 where scott.emp.ename=v_name; when v_sal<4000 then update scott.emp set scott.emp.comm=50 where scott.emp.ename=v_name; end case; end;