1. 程式人生 > >oracle 自定義函式(非常簡單明瞭)

oracle 自定義函式(非常簡單明瞭)

語法說明

create [or replace] function functionName   (parameterName1 mode1 dataType1,  parameterName2 mode2 dataType2,  ...)  
 return returnDataType  
 is/as  
 	-- 定義使用變數、返回變數
 begin  
 	function_body  
 	return expression  
end functionName; -- 結束函式的宣告,也可以直接寫end不加函式名。  

-- 其中mode1、mode2表示引數型別,dataType表示引數的資料型別。returnDataType表示返回值型別。  

舉例說明

1.舉一個簡單的例子

定義一個簡單的函式 入參為 兩個數, 返回兩個數的和

create or replace function useEasy(add1 in number, add2 in number) return number is
  FunctionResult number;
begin
  FunctionResult := add1 + add2;
  return(FunctionResult);
end useEasy;

函式的使用請繼續往下看

2.舉一個複雜的例子(雖然複雜,但是很實用)

①建立 TYPE 型別 atrr_type

CREATE OR REPLACE TYPE atrr_type  AS OBJECT
(
       attrId varchar2(40),
       objType varchar2(40)
);

②將 TYPE 型別 atrr_type 定義為表, 用做接收返回值


CREATE OR REPLACE TYPE attr_table AS TABLE of atrr_type;

③以遊標形式返回,有很大的侷限性

create or replace function selectAttrId(objType in VARCHAR2)
  return SYS_REFCURSOR is
  attrId SYS_REFCURSOR;
begin
  OPEN attrId FOR
    select attr_id, obj_type from CPS_OBJ_ATTR where obj_type = objType;
  return(attrId);
end selectAttrId;

④以 Table 形式 返回結果集

create or replace function resultFunction(objType in VARCHAR2)
  return attr_table is
  attr_row 	atrr_type;        	 		  -- 定義單條資料變數
  attr     	attr_table := attr_table();   -- 定義返回結果,並初始化
begin
  for thisrow in (select attr_id as attrId, obj_type as objType from CPS_OBJ_ATTR where obj_type = objType) 
    loop
      attr_row := atrr_type(thisrow.attrId, thisrow.objType);
      attr.extend;
      attr(attr.count) := attr_row;
    end loop;
  return(attr);
end resultFunction;

⑤以管道形式返回結果集

create or replace function returnPiperesult(objType in VARCHAR2)
  return attr_table pipelined
   is
   attr_row atrr_type;		 --定義attr_row為行物件型別
begin
  for thisrow in (select attr_id as attrId, obj_type as objType from CPS_OBJ_ATTR where obj_type = objType) loop
    attr_row:= atrr_type(thisrow.attrId, thisrow.objType);
    pipe row (attr_row);
  end loop;
  return;
end returnPiperesult;

⑥函式的使用

select resultFunction('turck') from dual;			-- 直接呼叫函式

select * from table(resultFunction('turck'));  	-- 返回結果集table時,可以呼叫(自定義一個type為table 作為返回結果集)

覺得文章實用,請在右上方點個贊