码迷,mamicode.com
首页 > 数据库 > 详细

PL/SQL - 03

时间:2015-04-27 00:37:06      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:number   update   where   

使用嵌套块

在PL/SQL块中可以嵌套子块,嵌套的块既可以放在外部块的执行部分,也可以放在异常处理部分,但是不能放在外部块声明部分
内部嵌套块可以访问外部嵌套块声明的变量,但是外部声明块不能访问内部声明块中的变量


declare
v_deptno number(2) := 50 ;
v_dname varchar2(12) ;

begin
       begin
       select dname  into v_dname from scott.dept where deptno = v_deptno ;
       dbms_output.put_line(‘您好查找的部门是: ‘|| v_dname);
       end ;
declare
  v_loc varchar2(10) := ‘深圳南山‘;
  begin
  update SCOTT.DEPT set loc = v_loc where deptno = v_deptno ;
    dbms_output.put_line(‘在内嵌块中成功更新部门资料! ‘);
  end ;
exception when no_data_found
         then begin
         insert into scott.dept values(v_deptno,‘信息部‘,‘深圳‘) ;
         dbms_output.put_line(‘在异常处理模块成功恢复资料!‘);
exception when others
         then
         dbms_output.put_line(‘未知异常!‘);
         end;
end;

此段程序共有三个begin--end结构。
第一组begin-end 结构是引导整个程序块,所以是主结构;
第二个 是用来查询部门信息的
       begin
       select dname  into v_dname from scott.dept where deptno = v_deptno ;
       dbms_output.put_line(‘您好查找的部门是: ‘|| v_dname);
       end ;
其实这个begin-end 结构可以去掉,并不影响程序执行

第三个是用来更新部门信息的 ,其完整代码如下

declare
  v_loc varchar2(10) := ‘深圳南山‘;
  begin
  update SCOTT.DEPT set loc = v_loc where deptno = v_deptno ;
    dbms_output.put_line(‘在内嵌块中成功更新部门资料! ‘);
  end ;

这里的begin-end 结构是不可以去掉的 ,因为在后续语句执行之前 进行了变量定义,
即:declare
  v_loc varchar2(10) := ‘深圳南山‘;
在一个单一的begin-end结构中是不能再重新定义变量的,除非此时已经决定此变量不属于此begin-end结构,所以这里的begin-end不能删除。


附:使用命名嵌套块


<<外部块>>
declare
v_deptno number(2) := 50 ;
v_dname varchar2(12) ;

begin
       <<查询员工名称块>>
       begin
       select dname  into v_dname from scott.dept where deptno = v_deptno ;
       dbms_output.put_line(‘您好查找的部门是: ‘|| v_dname);
       end ;
 <<更新员工部门块>>
declare
  v_loc varchar2(10) := ‘深圳南山‘;
  begin
  update SCOTT.DEPT set loc = v_loc where deptno = v_deptno ;
    dbms_output.put_line(‘在内嵌块中成功更新部门资料! ‘);
  end ;
exception when no_data_found
         then begin
         insert into scott.dept values(v_deptno,‘信息部‘,‘深圳‘) ;
         dbms_output.put_line(‘在异常处理模块成功恢复资料!‘);
exception when others
         then
         dbms_output.put_line(‘未知异常!‘);
         end;
end;

PL/SQL - 03

标签:number   update   where   

原文地址:http://wyhstar460.blog.51cto.com/2972581/1638875

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!