Three methods for Oracle function function to return result set

1. Introduction

In the process of using Oracle data, functions are very useful. We often define a function to deal with the results of the same and similar problems.

Usually, we use functions to return individual values, which may be NUMBER or VARCHAR types. In fact, functions can also return data sets in the form of table-structured data.

The most commonly used method is the cursor method, followed by the Table method, and finally the pipeline method. The difference between the pipeline method and the previous two is that it does not need to return a value, that is, there is no need to connect content after RETURN, and it returns data line by line. The way of Table and pipeline is to emulate the return content of the function into a data set through the 'TABLE()' keyword when calling.

2. Examples of three ways to return result sets

1. Return the result set in the form of a cursor

(1) Create a function

CREATE OR REPLACE FUNCTION FN_R_REFCUR(P_VALUE IN VARCHAR2)
RETURN SYS_REFCURSOR IS
	C_EMPNO SYS_REFCURSOR;
BEGIN
		OPEN C_EMPNO FOR
			SELECT NAME,ADDR FROM EMP WHERE ADDR=P_VALUE;
	RETURN(C_EMPNO);
END;
/

(2) Call function

SELECT FN_R_REFCUR('Raphael') FROM DUAL;

2. Return the result set in the form of Table

(1) Create a function

--Define a row type

CREATE OR REPLACE TYPE TYPE_TTEMP_ROW AS OBJECT(NAME VARCHAR2(10), ADDR VARCHAR2(20));

--Define a table type

CREATE OR REPLACE TYPE TYPE_TEMP_TABLE AS TABLE OF TYPE_TTEMP_ROW;

-- create function

CREATE OR REPLACE FUNCTION FN_R_TAB (P_VALUE IN VARCHAR2)
RETURN TYPE_TEMP_TABLE IS
	TEMP_ROW TYPE_TTEMP_ROW; -- 定义单行
	TEMP_TABLE TYPE_TEMP_TABLE := TYPE_TEMP_TABLE(); -- 定义返回结果,并初始化
BEGIN
	FOR CURROW IN (SELECT NAME, ADDR FROM EMP WHERE NAME=P_VALUE) -- 查询名字是参数的值的结果
	LOOP
		TEMP_ROW := TYPE_TTEMP_ROW(CURROW.NAME, CURROW.ADDR); -- 获得一行
		TEMP_TABLE.EXTEND; -- 表类型增加一行(EXTEND就是扩展的意思,相当于增加一行数据空间)
		TEMP_TABLE(EMP_TABLE.COUNT) := TEMP_ROW; -- 一行放进去
	END LOOP;
	RETURN(TEMP_TABLE);
END;
/

(2) Call function

SELECT * FROM TABLE(FN_R_TAB('Raphael'));

3. Return the result set in the form of a pipeline

(1) Create a function

--Define a row type

CREATE OR REPLACE TYPE TYPE_TTEMP_ROW AS OBJECT(NAME VARCHAR2(10), ADDR VARCHAR2(20));

--Define a table type

CREATE OR REPLACE TYPE TYPE_TEMP_TABLE AS TABLE OF TYPE_TTEMP_ROW;

-- create function

CREATE OR REPLACE FUNCTION FN_R_PIP(P_VALUE IN VARCHAR2)
RETURN TYPE_TEMP_TABLE PIPELINEDIS
	TEMP_ROW TYPE_TTEMP_ROW; --定义一个行对象类型变量
BEGIN
	FOR CURROW IN (SELECT NAME, ADDR FROM EMP WHERE NAME=P_VALUE) -- 查询名字是参数值的结果
	LOOP
		TEMP_ROW := TYPE_TTEMP_ROW(CURROW.NAME, CURROW.ADDR); -- 获得一行
		PIPE ROW (TEMP_ROW); -- 返回一行
	END LOOP;
	RETURN; -- 这里返回没有值
END;
/

(2) Call function

SELECT * FROM TABLE(FN_R_PIP('Raphael'));

Official website address: Oracle | Cloud Applications and Cloud Platform

Guess you like

Origin blog.csdn.net/qq_57226198/article/details/128188218