Oracle存儲過程小解 1.建立語法 create or replace procedure pro_name( paramIn in type, paramOUt out type, paramInOut in out type ) as(is)[相似於mysql的declare] begin statement... end; 注:<1>入參不用寫長度,只需寫類型,in、out、in out寫在參數名後,區別於mysql寫在參數名前,不寫默認爲in; <2>in是值傳遞,out和in out是引用傳遞,in的值不可修改,out的值在進入存儲過程是初始化null。 <3>as(is)相似於mysql的declare,也能夠在begin後使用declare定義變量; 設置變量值,也不用set,直接name := value或者使用select...into...; <4>沒有相似於mysql中的變換分隔符,最後end;便可。 <5>沒有入參時,可不要pro_name後();
<6>變量聲明:在begin以前,直接varName type;在內部,declare varName type.變量賦值須要使用 := 符號 2.經常使用方法 <1> if...then...elseif...then...end if; <2>多種循環: a.loop...exit when... end loop; b.while...loop....end loop; c.for...in...loop...end loop;(強烈推薦,mysql沒有for循環)
d.exit可用於跳出循環,return結束存儲過程
e.<<loopName>>...goto loopName:相似於標記;
<3>遊標cursor: 遊標屬性: cursor%found; --有數據 cursor%notfound; --無數據 cursor%isopen; --遊標已開啓 cursor%rowcount; --受最後SQL語句影響的行數 3.異常處理 <1>.經過關鍵字exception捕獲異常 語法: exception when exception_decription then statemnt when exception_description2 then statement when others then statement <2>.最經常使用的異常: no_data_found:select into語句沒有數據; too_many_rows:select into有多條數據; dup_val_on_index:惟一索引列重複; storage_error:內存溢出; zero_devide:除數爲0; case_not_found:case沒有匹配的條件且沒有else; cursor_already_open:遊標已打開; timeout_on_resource:請求資源超時。 <3>.自定義異常:(相似於mysql的自定義condition,避免error_code值帶來的閱讀性太差的問題); progma exception_init(selfexception,-oracle_error_code); 示例:declare demo_exception exception; progma exception_init(demo_exception,-60); <4>.處理異常 a.不拋出,statement處理; b.拋出異常: ●存儲過程自動拋出 ●經過raise關鍵字拋出,如 raise no_data_found; ●經過raise_application_error(error_number,message[flag(true,false)]); error_number數值範圍從-20999到-20000; messgae表示異常描述; flag表示是添加到(true)或者覆蓋(false)錯誤堆,默認是false; 如:raise_application_error(-20001,'invalid id number'); <5>異常處理機制與java異常處理機制類似。 4.經常使用技巧: <1>execute immediate statement to param; 關鍵字:execute immediate...to...; 它解析並立刻執行動態的SQL語句或非運行時建立的PL/SQL塊,能夠理解爲執行動態SQL。 注意幾點: a.不支持返回多行的操做,這種狀況應該用refcursor來處理 b.執行sql時不要加分好,pl/sql塊時加分號; c.使用以前應該將以前的事務顯示提交。 示例: execute immediate 'select dname, loc from dept where deptno = :1' into l_nam, l_loc using l_dept ; <2>sys_refscursor:非正常遊標,用於返回結果集 示例: create or replace procedure up_test(o out sys_refcursor) is --能夠在代碼中獲取返回值 begin open o for select * from lq_test; end; <3>%type 做用:與關聯表的關聯字段類型長度綁定起來,跟隨綁定表字段的變化,是一種很是好的變成習慣,避免屢次更改: 示例: declare v_name students.name%type; <4>%rowtype 表示該列爲行數據類型,存儲的爲一行數據,至關於一條record相對於查詢結果或者遊標。 做用:當查詢一行數據時,比多個字段採用%type效率要高一些。 示例: declare v_emp emp%rowtype; cursor cursor_name is select...from table... open cursor_name for xxx in cursor_name loop v_emp := xxx; end loop; end cursor_name;