Oracle --存儲過程基本語法

1、存儲過程的理解sql

  1. create or replace procedure 存儲過程名數據庫

  2. asoracle

  3. begin函數

  4. nulloop

  5. endspa

行1:create or replace procedure 是一個SQL語句,通知oracle數據庫去建立一個叫作skeleton儲存過程,若是存在就覆蓋它。io

行2:as關鍵詞代表後面將跟隨一個pl/sql體。for循環

行3:begin關鍵詞代表pl/sql體的開始。test

行4:null 代表pl/sql語句什麼事情都不作,這句不能刪除,由於pl/sql體中至少須要有一句。變量

行5:end關鍵詞代表pl/sql體的結束。

2、存儲過程建立語法

create or replace procedure 存儲過程名 (param1 in type,para2 out type)

as

變量1 類型(值範圍); eg: vs_msg VARCHAR2(20);

變量2 類型(值範圍);

begin

        select  count(*)  into  變量1  from  表A  where  列名 = param1;

        if (判斷條件) then

            select  列名  into  變量2  from  表A  where  列名=param1;

            dbms_output.put_line('打印信息');

        elseif (判斷條件) then

            dbms_output.putline('打印信息');

         else

             raise  異常名 (no_data_found);

         end if;

         exception

              when others then

                   rollback;

end

對如上理解:

  1. 存儲過程參數不帶取值範圍,in表示傳入,out表示輸出。類型可使用任意oracle中的合法類型。                                            

  2. 變量帶取值範圍,後面接分號

  3. 在判斷語句以前最好先用count(*)函數判斷是否存在該條操做記錄

  4. 用select ... into ...給變量賦值

  5. 在代碼中拋異經常使用 raise+異常名


3、

create or replace procedure 存儲過程名

{

--定義參數

param1 in char(6),

param2 out number,

}

as

--定義變量

param3 varchar2(10);

param4 varchar2(16);

begin

--用輸入參數給變量賦值

end


4、oracle存儲過程語法

1.判斷語句  

if 比較式 then begin end;end if

create or replace procedure test(x in number)

as  //本例子不須要定義變量,因此as後面沒有變量

begin 

     if x > 0 then

     begin

          x: = -x;

     end;

     end if;

     if x = 0 then

        begin

        x: = 1;

        end;

     end if;

end test;

2.for循環語句

for ... in ... loop

--執行語句

end loop;

(1)循環遍歷遊標

create or replace procedure test() //這裏沒有輸入參數

as 

Cursor cursor is select name from student;

name varchar2(16);

begin

    for name in cursor loop

         begin

            dbms_output.putline(name); //輸出表student中字段爲name的全部的數據

         end;

     end loop;

end test;

(2)while循環

while 條件語句 loop

begin

end;

endloop;

//舉個例子

create or replace procedure test(i in number)

as

begin

while i < 10 loop

    begin

        i:=i+1;

    end;

    end loop;

end test;

3.遊標的使用

oracle 中的cursor很是有用,用於遍歷臨時表中的查詢結果。其相關方法和屬性不少,下面介紹一-二。

3-1 Cursor型遊標 (注意:遊標不能用於參數傳遞)

create or replace procedure test()

as

cursor1 Cursor is select name from studentTable where ...;//遊標的使用方式1

cursor2 Cursor; 

begin

select name into cursor2 from studentTable where...;//遊標的使用方式2

可使用 for x in cursor loop ...end loop;來實現對cursor的遍歷。

end test;

相關文章
相關標籤/搜索