当前位置: 代码迷 >> SQL >> PL/SQL的特征
  详细解决方案

PL/SQL的特征

热度:59   发布时间:2016-05-05 14:44:27.0
PL/SQL的特性
块结构,变量与常量,循环结构以及游标是PL/SQL最重要的部分

1:块结构
   块结构是PL/SQL程序的基本可执行单元,所有的PL/SQL都是由块结构组成的,每个块完成程序中的部分工作.这样就可以将程序分成多个块!
   块得基本机构如下
declare  --块得定义部分,这里可以定义变量,自定义类型,游标和局部子程序  --这是可选的部分begin  --块的执行部分,这里放置一些可执行的SQL或PL/SQL  --这是最重要的部分也是必须有的部分  --这里至少要包含一条可执行的语句  exception  --异常处理部分,放置对错误进行处理的语句  --这是可选的部分end;


2:变量和常量
   基本的变量定义类型如下
declare   v_name varchar2;   v_age  number;

   这个Oracle预定义的类型,PL/SQL支持复杂的变量类型的,如下所示:
declare  type au_Record is record(       author_code char(6),       name varchar2(10),       sex number(1)  )  oneau au_Record;

   另外,Oracle还有一种数组的定义方式,下面是真实项目一个小事例
declare   type org_collect is table of hrm_position_id%type;  rec_org org_collect;begin  --......  select position_id bulk collect  into rec_org  from hrm_position hp  start with hp.position_id = '1001';  connect by prior hp.parent_position_id = hp.position_id;  --改代码意思是层次化查询出员工上级列表,并保存进数组(rec_org)中end;


3:循环结构
  PL/SQL支持的循环结构有很多种,这里我猎取两种最常用的
drop table table_a;create table table_a(       num_col     number,       char_col    varchar2(60));--第一种declare       v_loopCounter  number := 1;begin       loop           insert into table_a(num_col) values(v_loopCounter);           v_loopCounter := v_loopCounter+1;           exit when v_loopCounter >100;       end loop;end;--第二种declare        v_loopCounter  number := 1;begin       for v_loopCounter in 1..50 loop             dbms_output.put_line(v_loopCounter);       end loop;end;select * from table_a;


4:游标(呵呵,直接粘代码算了,很好理解的!)
create table auths(       v_name varchar2(10),       v_salary number(8,2))insert into auths values('zhangsan',23.23);insert into auths values('lis',22.23);insert into auths values('wangwu',20.23);insert into auths values('zhaoliu',29.23);insert into auths values('sunqi',25.23);commit;select * from auths;declare         v_name varchar2(10);        v_salary number(8,2);        cursor cu_auths is          select v_name,v_salary from auths;begin        open cu_auths;                loop             fetch cu_auths into v_name,v_salary;             dbms_output.put_line(v_name);             exit when cu_auths%notfound;        end loop;                close cu_auths;end;
  相关解决方案