Orcle数据库编程:一

1.PL/SQL是一种块结构的语言,一个PL/SQL程序包含了一个或者多个逻辑块,逻辑块中可以声明变量,变量在使用之前必须先声明。

declare
mstu student%ROWTYPE;--定义参数,只能在一条记录下使用
begin
  select * into mstu from student where sid=10003;--查询语句
  dbms_output.put_line('姓名为'||mstu.sname||',性别为'||mstu.ssex);--打印结果。
  end;
--打印张三和李四年龄和年龄之和
declare 
 age1 student.sage%TYPE;--定义参数age设置类型为student表age字段的类型
 age2 student.sage%TYPE;
 total  int:=1000; 
 fage total%type;
begin
  select sage into age1  from student where sname in('李宁');
   select sage into age2  from student where sname in('李四');
    fage:=age1+age2;
   dbms_output.put_line(age1||age2||fage);
end;

2.PL/SQL中的IF 语法

if 条件1 then
--条件1成立结构体
elsif 条件2 then
--条件2成立结构体
else
--以上条件都不成立结构体
end if;
--根据张三的均分给出评判如果大于90输出a 80b  70 c
declare
avgsc  mark.cmark%type;
begin
select avg(cmark) into avgsc from mark  where sid=(select sid from  student where sname='张三') ;
  if avgsc>=90 then
      dbms_output.put_line('a');
    elsif avgsc>=80 then
       dbms_output.put_line('b');
           elsif avgsc>=70 then
       dbms_output.put_line('c');
       else 
           dbms_output.put_line('d');
           end if;
  end;

3.游标

/*游标的使用方法:
第一步:声明游标
第二步:打开游标
第三步:使用游标进行循环操作
第四步:关闭游标*/
 
--普通游标,游标本身就是一个变量
declare     
     --下面的这行代码声明了一个游标
     cursor mycur is select * from emp where deptno = 20;
     emprow emp%rowtype;
begin
     open mycur; --打开游标
     loop
         fetch mycur into emprow; --把游标所指的纪录放到变量中
         exit  when (mycur%notfound); --当游标没有指向行时退出循环
         dbms_output.put_line('名字:' || emprow.ename || '薪水:' || emprow.sal);
     end loop;
     close mycur;  --关闭游标
end;
/**隐式开启游标*/
  declare 
cursor csr is 
select  sid ,ssex||'同学:'||sname||',今年'||to_char(sage)||'' sinfo from student;
begin
  --隐含打开游标
  for v_stu in csr loop
    --隐含执行一个fetch语句
    dbms_output.put_line(to_char(v_stu.sid)||'的个人信息为:'||v_stu.sinfo);
    --隐含检测c_sal%notfound
    end loop;
    --隐含关闭游标
    end;

 

posted @ 2016-09-08 18:05  HuTiger  阅读(827)  评论(0编辑  收藏  举报