类似存储的SQL

declare 
  cursor c_Dep is 
      select dno,dname from dep ;
      
  p_dNo DEP.DNO%type;
  p_dName DEP.DNAME%type;
  
  cursor c_SC(courseName varchar2,departmentNo number) is
      select grade from sc where cno = (select cno from course where cname = courseName ) and sno in (select sno from student where dno = departmentNo);
  p_grade sc.grade%type;
  
  final_courseName varchar(20) := '大学物理';
  avg_po number;
  cnt1 number;cnt2 number;cnt3 number;
  
  begin
      DELETE FROM MSG;
      open c_Dep;
        loop 
          fetch c_Dep into p_dNo,p_dName;
          exit when c_Dep%notFound;
          
           --先看各系的平均成绩
          select avg(grade) into avg_po from sc where cno = (select cno from course where cname = final_courseName ) and sno in (select sno from student where dno = p_dNo);
          cnt1 := 1;cnt2 :=2;cnt3 :=3;
          
          open c_SC(final_courseName,p_dNo);
             loop 
                fetch c_SC into p_grade;
                exit when c_SC%notFound;
                
                 
                 if p_grade < 60 then cnt1 := cnt1 + 1;
                   elsif p_grade>=60 and p_grade<85 then cnt2:=cnt2+1;
                   else cnt3 := cnt3 + 1;
                 end if;
            
             end loop;             
          close c_SC;          
          insert into msg(pcoursename,pdname,cou1,cou2,cou3,avg4) values (final_courseName,p_dName,cnt1,cnt2,cnt3,avg_po);
        end loop;
      close c_Dep;  
  end;

    SQL 习练体会:

    1.不练习不会清楚能走到哪一步,本人遇到问题:

          不知道一个变量的出现,首先带上类型,不论游标参数或者是开始声明的变量

          不初始化的变量不会参与到计算中,如上面的 cnt1,cnt2,cnt3

          记住 elsif 这个写法,还有 dbms_output.put_line();

     程序如果没有看到结果,就不应该相信自己会做出来。而这个 SQL Developer 平台,可以良好展示自己的SQL 技术。

猜你喜欢

转载自liudingning.iteye.com/blog/2111260