1. 程式人生 > >運用瀑布模型完成PL/SQL程式設計

運用瀑布模型完成PL/SQL程式設計

    在通常的軟體開發或者程式開發中都會運用到很多種模型,瀑布模型就是其中的一種。

    瀑布模型是將軟體生命週期的各項活動規定為固定順序的若干個階段工作,最終得到軟體產品。其核心思想就是化繁為簡,採用結構化的分析設計方法實現邏輯。

     相對於軟體開發,一般的程式開發涉及的開發階段就簡化了很多,但可以幫助我們迅速找準邏輯,快速完成程式設計。可以簡化其設計階段為:

     1.需求分析    分析程式的設計目的

     2.設計     包括概要設計和詳細設計。概要設計指的是從程式的架構上描述程式的邏輯。詳細設計則指的是具體到程式的具體功能。

     3.編碼(coding)    

     4.測試(test)

     5.上線

    在程式設計的過程中,最忌諱的就是上來就編碼,我們應該在編碼之前完成程式的邏輯設計和具體的分析。在編寫一個PL/SQL程式時,首先應該想到的是要用到哪一個SQL語句和程式設計中所需要的變數,變數的初始值是多少,變數的最終值如何得到。完成這樣的一個步驟,在接下來的編碼中就能夠做到不出錯,快速完成。

    案例1:統計每年入職的員工人數

/*
SQL語句
select to_char(hiredate,'yyyy') from emp;
-->查詢的結果集,用到游標-->迴圈-->退出條件:notfound

變數:1初始值 2.如何得到
每年的入職員工人數
count80 number:=0;
count81 number:=0;
count82 number:=0;
count87 number:=0;
*/
set serveroutput on
declare
    -- 定義游標 
    cursor cemp is select to_char(hiredate,'yyyy') from emp; 
    phiredate varchar2(4);
    -- 每年入職的員工人數 
    count80 number:=0; 
    count81 number:=0; 
    count82 number:=0; 
    count87 number:=0;
begin
   open cemp;
        loop
          -- 取出員工的入職年份 
          fetch cemp into phiredate; 
          exit when cemp%notfound;
          
          -- 判斷入職年份
          if phiredate='1980' then count80:= count80+1;
             elsif phiredate='1981' then count81:=count81+1;
             elsif phiredate='1982' then count82:=count82+1;
             else count87:=count87+1;
          end if;
        end loop;
   close cemp;
   
   --輸出結果
   dbms_output.put_line('Total:'||(count80+count81+count82+count87));
   dbms_output.put_line('1980:'||count80);
   dbms_output.put_line('1981:'||count81); 
   dbms_output.put_line('1982:'||count82); 
   dbms_output.put_line('1987:'||count87);
end;
/                                 
    案例2: 漲工資問題,從工資最低的工作人員開始,沒人漲10%,工資總額不能超過5w,返回漲工資的人數和漲後的工資總額
/*
SQL語句:
select empno,sal from emp order by sal;
-->游標——迴圈——退出條件:1.工資總額>5w 2.%notfound

變數:1.初始值 2.如何得到
漲工資的人數:
countemp number:=0;

漲後的工資總額:
total_sal number
1.select sum(sal) into total_sal from emp;
2.漲後的工資總額=漲前的工資總額+sal*0.1;
*/
declare
 cursor cemp is select sal,empno from emp order by sal;
 pempno emp.empno%type;
 psal emp.sal%type:=0;
 countemp number:=0;
 total_sal number;
 
begin 
 --得到總工資額
 select sum(sal) into total_sal from emp;

 --開啟游標
 open cemp;
 loop
 
 exit when total_sal>50000;
 fetch cemp into psal,pempno;
 
 exit when cemp%notfound;
 update emp set sal=sal*(1+0.1) where empno=pempno;
 total_sal:=total_sal+psal*0.1;
 countemp:=countemp+1;
 --修正
 if total_sal>50000 then
    total_sal:=total_sal-psal*0.1;
    update emp set sal=sal/1.1 where empno=pempno;
    countemp:=countemp-1;
 end if;
 
 end loop;
 
 --關閉游標
 close cemp;
 
 commit;
 dbms_output.put_line('漲工資的人數:'||countemp);
 dbms_output.put_line('工資總額:'||total_sal);
end;
/