Oracle存儲過程基礎與案例

通過對Oracle存儲過程的學習與研究,並記錄了下來,後面會有例子。
首先還是先看看基礎語法吧:

                        Oracle存儲過程
 一:oracle 存儲過程的基本語法
1.基本結構 
CREATE OR REPLACE PROCEDURE 存儲過程名字
(
    參數1 IN NUMBER,
    參數2 IN NUMBER
) IS
變量1 INTEGER :=0;
變量2 DATE;
BEGIN
--xxx
END 存儲過程名字

【注意:】如果沒有or replace語句,則僅僅是新建一個存儲過程。如果系統存在該存儲過程,則會報錯。Create or replace procedure 如果系統中沒有此存儲過程就新建一個,如果系統中有此存儲過程則把原來刪除掉,重新創建一個存儲過程。 
參數的數據類型只需要指明類型名即可,不需要指定寬度。 
參數的寬度由外部調用者決定。
過程可以有參數,也可以沒有參數 
變量聲明塊:緊跟着的as (is )關鍵字,可以理解爲pl/sqldeclare關鍵字,用於聲明變量。 
變量聲明塊用於聲明該存儲過程需要用到的變量,它的作用域爲該存儲過程。另外這裏聲明的變量必須指定寬度。遵循PL/SQL的變量聲明規範。 
過程語句塊:從begin 關鍵字開始爲過程的語句塊。存儲過程的具體邏輯在這裏來實現。 
異常處理塊:關鍵字爲exception ,爲處理語句產生的異常。該部分爲可選 
結束塊:由end關鍵字結果。
2.SELECT INTO STATEMENT
  將select查詢的結果存入到變量中,可以同時將多個列存儲多個變量中,必須有一條
  記錄,否則拋出異常(如果沒有記錄拋出NO_DATA_FOUND)
  例子: 
  BEGIN
  SELECT col1,col2 into 變量1,變量2 FROM typestruct where xxx;
  EXCEPTION
  WHEN NO_DATA_FOUND THEN
      xxxx;
  END;
  ...

3.IF 判斷
  IF V_TEST=1 THEN
    BEGIN 
       do something
    END;
  END IF;

4.while 循環
  WHILE V_TEST=1 LOOP
  BEGIN
 XXXX
  END;
  END LOOP;

5.變量賦值
  V_TEST := 123;

6.用for in 使用cursor
  ...
  IS
  CURSOR cur IS SELECT * FROM xxx;
  BEGIN
 FOR cur_result in cur LOOP
  BEGIN
   V_SUM :=cur_result.列名1+cur_result.列名2
  END;
 END LOOP;
  END;

7.帶參數的cursor
  CURSOR C_USER(C_ID NUMBER) IS SELECT NAME FROM USER WHERE TYPEID=C_ID;
  OPEN C_USER(變量值);
  LOOP
 FETCH C_USER INTO V_NAME;
 EXIT FETCH C_USER%NOTFOUND;
    do something
  END LOOP;
  CLOSE C_USER;

8.用pl/sql developer debug
  連接數據庫後建立一個Test WINDOW
  在窗口輸入調用SP的代碼,F9開始debug,CTRL+N單步調試   

二:關於oracle存儲過程的若干問題備忘

1.在oracle中,數據表別名不能加as,如:
select a.appname from appinfo a;-- 正確
select a.appname from appinfo as a;-- 錯誤
 也許,是怕和oracle中的存儲過程中的關鍵字as衝突的問題吧
2.在存儲過程中,select某一字段時,後面必須緊跟into,如果select整個記錄,利用遊標的話就另當別論了。
  select af.keynode into kn from APPFOUNDATION af where af.appid=aid and af.foundationid=fid;-- 有into,正確編譯
  select af.keynode from APPFOUNDATION af where af.appid=aid and af.foundationid=fid;-- 沒有into,編譯報錯,提示:Compilation 
  Error: PLS-00428: an INTO clause is expected in this SELECT statement


3.在利用select...into...語法時,必須先確保數據庫中有該條記錄,否則會報出"no data found"異常。
   可以在該語法之前,先利用select count(*) from 查看數據庫中是否存在該記錄,如果存在,再利用select...into...
4.在存儲過程中,別名不能和字段名稱相同,否則雖然編譯可以通過,但在運行階段會報錯
 select keynode into kn from APPFOUNDATION where appid=aid and foundationid=fid;-- 正確運行
select af.keynode into kn from APPFOUNDATION af where af.appid=appid and af.foundationid=foundationid;-- 運行階段報錯,提示
ORA-01422:exact fetch returns more than requested number of rows
5.在存儲過程中,關於出現null的問題
假設有一個表A,定義如下:
create table A(
id varchar2(50) primary key not null,
vcount number(8) not null,
bid varchar2(50) not null -- 外鍵 
);
如果在存儲過程中,使用如下語句:
select sum(vcount) into fcount from A where bid='xxxxxx';
如果A表中不存在bid="xxxxxx"的記錄,則fcount=null(即使fcount定義時設置了默認值,如:fcount number(8):=0依然無效,fcount還是會變成null),這樣以後使用fcount時就可能有問題,所以在這裏最好先判斷一下:
if fcount is null then
    fcount:=0;
end if;
這樣就一切ok了。
6.Hibernate調用oracle存儲過程
        this.pnumberManager.getHibernateTemplate().execute(
                new HibernateCallback() {
                    public Object doInHibernate(Session session)
                            throws HibernateException, SQLException {
                        CallableStatement cs = session
                                .connection()
                                .prepareCall("{call modifyapppnumber_remain(?)}");
                        cs.setString(1, foundationid);
                        cs.execute();
                        return null;
                    }
                });


例子:
首先建表:

create table tab_1
(
       id varchar(11) primary key,
       name varchar(10),
       password varchar(10)
)
添加數據:
insert into TAB_1 (ID, NAME, PASSWORD)
values ('1', '小米', '123');
insert into TAB_1 (ID, NAME, PASSWORD)
values ('2', '小明', '452');
insert into TAB_1 (ID, NAME, PASSWORD)
values ('3', '小華', '145');

無返回值:
                            **過程測試一**

create or replace procedure test is
begin
Update tab_1 t set t.name='小明' where t.name='小華'
end test

【經過測試發現:create or replace procedure test is這裏可以使用’is’ 或者’as’】

這裏寫圖片描述

報錯:
PROCEDURE ZYSMS.TEST 編譯錯誤

錯誤:PL/SQL: ORA-00933: SQL 命令未正確結束
行:3
文本:Update tab_1 t set t.name='小李' where t.name='小明'

錯誤:PL/SQL: SQL Statement ignored
行:3
文本:Update tab_1 t set t.name='小李' where t.name='小明'

錯誤:PLS-00103: 出現符號 "end-of-file"在需要下列之一時:
        ;
行:4
文本:end test

解決過程:是由於更新SQL語句後沒有加分號”;” 

接着執行:
create or replace procedure test is
begin
Update tab_1 t set t.name='小明' where t.name='小華';
end test

報錯:PROCEDURE ZYSMS.TEST 編譯錯誤

錯誤:PLS-00103: 出現符號 "end-of-file"在需要下列之一時:
        ;
       符號 ";" 被替換爲 "end-of-file" 後繼續。
行:4
文本:end test

這裏寫圖片描述

解決過程:由於在end test(當前你的存儲過程名) 後沒有加結束的分號”;”。

運行:編譯成功!
這裏寫圖片描述

Test存儲過程代碼:
create or replace procedure test is
begin
       update tab_1 t set t.name='小明' where t.name='小華';
end test;
測試代碼:
    public static void main(String[] args) throws SQLException {
        Statement stmt = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
          Class.forName(driver);
          conn = DriverManager.getConnection(url,name, password);
          CallableStatement proc = null;
          proc = conn.prepareCall("{ call test() }"); //設置存儲過程
          proc.execute();//執行
        }
        catch (SQLException ex2) {
          ex2.printStackTrace();
        }
        catch (Exception ex2) {
          ex2.printStackTrace();
        }
        finally{
          try {
            if(rs != null){
              rs.close();
              if(stmt!=null){
                stmt.close();
              }
              if(conn!=null){
                conn.close();
              }
            }
          }
          catch (SQLException ex1) {
          }
        }
     }  

運行結果:
這裏寫圖片描述

                                 **過程測試二**

帶返回值:

【1】返回指定參數:
Test2存儲過程代碼:
create or replace procedure test2(var_id in number, var_out_name out varchar2) as
begin
select t.name into var_out_name from tab_1 t where t.id=var_id;
end test2;

測試代碼:
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, name, password);
CallableStatement proc = null;
proc = conn.prepareCall(“{ call test2(?,?) }”); //設置存儲過程
proc.setString(1, “2”);//設置第一個參數輸入參數
proc.registerOutParameter(2,oracle.jdbc.OracleTypes.VARCHAR);//第二個參數輸出參數,是VARCHAR類型的
proc.execute();//執行
String var_out_name = proc.getString(2);//獲得輸出參數
System.out.println(“名字 : “+var_out_name);
}
catch (SQLException ex2) {
ex2.printStackTrace();
}
catch (Exception ex2) {
ex2.printStackTrace();
}
finally{
try {
if(rs != null){
rs.close();
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
catch (SQLException ex1) {
}
}
}
【注意事項:】
1.對於存儲過程的輸入參數,使用setXXX;對於輸出參數,使用registerOutParameter
,問號的順序要對應,同時需要考慮類型。
2.取出存儲過程返回值的方法是CallableStatement提供的getXX()注意輸出參數的位置,
同時也需要考慮輸出參數的類型。

運行結果:名字 : 小華


                                **過程測試三**

【2】返回列表
由於Oracle存儲過程沒有返回值,它的所有返回值都是通過out參數來替代的,列表同樣也不例外,但由於是集合,所以不能用一般的參數,必須要用package了,所以要分爲兩部分:
步驟一:新建一個程序包
create or replace package TESTPACKAGE as
type Test_CURSOR is ref cursor;
end TESTPACKAGE;

步驟二:到這可以創建存儲過程:
create or replace procedure test3(p_cursor out TESTPACKAGE.Test_CURSOR) as
begin
open p_cursor for select * from tab_1;
end test3;

測試代碼:
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, name, password);
CallableStatement proc = null;
proc = conn.prepareCall(“{ call test3(?) }”); //設置存儲過程
proc.registerOutParameter(1,oracle.jdbc.OracleTypes.CURSOR);
proc.execute();
rs = (ResultSet)proc.getObject(1);
while(rs.next())
{
System.out.println(” ID: ” + rs.getString(1) + ” 名字: “+rs.getString(2)+” 密碼: “+rs.getString(3));
}
}
catch (SQLException ex2) {
ex2.printStackTrace();
}
catch (Exception ex2) {
ex2.printStackTrace();
}
finally{
try {
if(rs != null){
rs.close();
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
catch (SQLException ex1) {
}
}
}
運行結果:
ID: 1 名字: 小米 密碼: 123
ID: 2 名字: 小華 密碼: 452
ID: 3 名字: 小組 密碼: 145


                              **過程測試四**

存儲過程加入IF語句:

存儲過程Test5:
先創建包:【在下篇文章詳細介紹Oracle-Package】
create or replace package TESTPACKAGE as
type Test_CURSOR is ref cursor;
end TESTPACKAGE;

再建存儲過程:
create or replace procedure test5(var_id in varchar2,var_outs out TESTPACKAGE.Test_CURSOR) as
id varchar2(10):=’01’;
begin
if id=var_id then
begin
open var_outs for select * from tab_1;
end;
end if;
end test5;

測試代碼:
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,name,password);
CallableStatement proc = null;
proc = conn.prepareCall(“{ call test5(?,?) }”); //設置存儲過程
proc.setString(1,”01”);
proc.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
proc.execute();//執行
rs=(ResultSet) proc.getObject(2);
while(rs.next()){
System.out.println(” ID: ” + rs.getString(1) + ” 名字: “+rs.getString(2)+” 密碼: “+rs.getString(3));
}
}
catch (SQLException ex2) {
ex2.printStackTrace();
}
catch (Exception ex2) {
ex2.printStackTrace();
}
finally{
try {
if(rs != null){
rs.close();
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
catch (SQLException ex1) {
}
}
}
這裏id值設置爲“01”【正確值】時運行結果:

這裏寫圖片描述

這裏id值設置爲“02”【錯誤值】時運行結果:

這裏寫圖片描述

運行報:Ref 遊標無效
                              **過程測試五**
調存儲過程時如果傳List集合測試:
test6存儲過程:
【1】CREATE OR REPLACE TYPE tables_array AS VARRAY(100) OF VARCHAR2(32);

【2】create or replace procedure test6(arr_t in tables_array) as
begin
    for i in arr_t.first .. arr_t.last loop
   -- insert  into test_table values(arr_t(i));
    update tab_1 t set t.password='001' where t.id=arr_t(i);
  end loop;
  commit;
end test6;


【3】測試代碼:
public static void main(String[] args) throws SQLException {
        Statement stmt = null;
        ResultSet rs = null;
        Connection conn = null;
        try {
          Class.forName(driver);
          conn = DriverManager.getConnection(url,name,password);
          CallableStatement proc = null;
          proc = conn.prepareCall("{ call test6(?) }"); //設置存儲過程
          ArrayDescriptor descriptor =  ArrayDescriptor.createDescriptor("TABLES_ARRAY",conn);
          List list=new ArrayList<>();
          list.add("1");
          list.add("3");
          ARRAY array = new ARRAY(descriptor,conn,list.toArray());  
          proc.setArray(1, array);
          proc.execute();//執行
        }
        catch (SQLException ex2) {
          ex2.printStackTrace();
        }
        catch (Exception ex2) {
          ex2.printStackTrace();
        }
        finally{
          try {
            if(rs != null){
              rs.close();
              if(stmt!=null){
                stmt.close();
              }
              if(conn!=null){
                conn.close();
              }
            }
          }
          catch (SQLException ex1) {
          }
        }
     }  

運行結果:
這裏寫圖片描述

我的技術羣這裏給大家分享下:472148690

在下一篇我會分享一個大批量數據插入的性能測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章