PL/SQL 编程

PL/SQL 程序结构:

declare

    声明部分(声明变量、类型、游标以及布局的存储过程及函数)

begin

   执行部分(过程及SQL语句,程序的主要部分,是必须的)

end;eg(基表为course):

declare

  v_cno varchar(20) :='001';

begin

  select * from course where cno=v_cno;

  delete * from course where cno=v_cno;

end;

------查询course表中cno=‘001’的数据

------删除course表中cno=‘001’的数据

 

returning的使用

在需要返回DML语句执行后的信息时使用,讲个例子加以说明

本例基表为student(sno, sname, classno)

declare

    s_no varchar2(20);

    s_name varchar2(40);

begin

   insert into student values('20110001','张三','051')  returning sno,sname into s_no, s_name;

  dbms_output.put_line(s_no);

  dbms_output.put_line(s_name);

end

------将插入的信息之中的sno、sname对应的赋值给s_no,s_name

 

type、%type的使用

type 用于定义类,具体用例子说明

基表为course(cno,cname,credit)

declare
      type c_rec is record(
          c_cno char(10):=&no,
          c_cname char(40)

);
      rec_course c_rec;              -------rec_course 的类型为c_rec类
      begin
          select cno,cname into rec_course from course where cno=rec_course.c_cno;
          dbms_output.put_line(rec_course.c_cno||'     '||rec_course.c_cname);
      end;

%type可以使定义的变量引用相关字段的数据类型、格式等,例如:

declare

      type c_rec is record(

          c_cno course.cno%type:=&no,              --c_cno引用了course表中的cno的数据类型和宽度

          c_cname course.cname%type);           --c_cname引用了course表中cname的数据类型和宽度

       rec_course c_rec;

begin

       select cno,cname into rec_course from course where cno=rec_course.c_cno ;

       bdms_output.put_line(rec_course.c_cno||'    '||rec_course.c_cname);

end;

上例中的‘&no’表示用户自行输入的数据作为c_cno的默认值

%rowtype返回一个记录类型,例如:

declare

      c_cno course.cno%type:=&no;

      rec_course course%rowtype;                

begin

      select * into rec_course from course where cno=c_cno;   

                                                                  ----rec_course中引用了course表中满足条件的一行数据

      dbms_output.put_line(‘课程名:’||rec_course.cname||'  课程号: '||rec_course.cno);

end;

表类型

declare

  type table_type_name is table of  table_name%rowtype index by binary_integer;

  .......

begin

  .......

end;

其中:table_type_name 是表类型的名称,table_name 是参照表的名称,is table 表示该类型为表类型

eg:

declare
  type sc_table is table of sc%rowtype index by binary_integer;
  w_sc sc_table;
begin
  select sno,cno,grade into w_sc(1).sno,w_sc(1).cno,w_sc(1).grade  from sc where sno='20110002' ;
  dbms_output.put_line(w_sc(1).sno||' '||w_sc(1).cno||' '||w_sc(1).grade);
end;

 注意:表类型的赋值不能直接赋值给表对象,即 select  *  into  w_sc  from sc where sno='20110001'; 这样复制是错误的,应该使用下标,如以上的示例

posted @ 2018-12-06 22:16  吾名王道长  阅读(152)  评论(0编辑  收藏  举报