在Oracle 11g中,我试图从与表连接的函数调用中返回多个列。此函数以employee_id作为输入,并且应从雇员表中返回first_name和last_name作为两个单独的列。
我创建了一个类型
create or replace
type mytype as object
( val_1 varchar2(100),
val_2 number
);
/
和功能
create or replace
function myfunc(p_in number) return mytype is
v_deptname varchar2(100);
v_mgrid number;
begin
select department_name,manager_id into v_deptname,v_mgrid from DEPARTMENTS where department_id = p_in;
return
mytype(v_deptname,v_mgrid);
end;
/
两个都成功创建。但是当我执行功能时,
select employee_id, salary, myfunc(department_id) from EMPLOYEES where employee_id in(100,101);
它给出如下结果,
EMPLOYEE_ID SALARY
----------- ----------
MYFUNC(DEPARTMENT_ID)(VAL_1, VAL_2)
--------------------------------------------------------------------------------
100 24000
MYTYPE('Executive', 100)
101 17000
MYTYPE('Executive', 100)
但是我希望我的结果像,
EMPLOYEE_ID SALARY VAL_1 VAL_2
----------- ---------- ------------------------------ ----------
100 24000 Executive 100
101 17000 Executive 100
请帮助实现这一目标。 谢谢
答案 0 :(得分:1)
好吧,您可能还缺少基于MYTYPE
的另一种类型。
这是一个示例(由于没有您的表,因此我使用的是Scott的架构)。我已将DEPTNO
添加到MYTYPE
中,以便能够将结果(由函数返回)与EMP
表联接。
这是您拥有的:
SQL> create or replace type mytype as object
2 (deptno number,
3 dname varchar2(20),
4 loc varchar2(20));
5 /
Type created.
这是您所缺少的:
SQL> create or replace type mytab as table of mytype;
2 /
Type created.
功能:注释第9行:
SQL> create or replace function myfunc (p_in number) return mytab is
2 v_dname varchar2(20);
3 v_loc varchar2(20);
4 begin
5 select dname, loc
6 into v_dname, v_loc
7 from dept
8 where deptno = p_in;
9 return mytab(mytype(p_in, v_dname, v_loc));
10 end myfunc;
11 /
Function created.
测试:
SQL> select * from table(myfunc(10));
DEPTNO DNAME LOC
---------- -------------------- --------------------
10 ACCOUNTING NEW YORK
SQL>
SQL> select e.ename, e.sal, m.dname, m.loc
2 from emp e join table(myfunc(e.deptno)) m on m.deptno = e.deptno
3 where e.deptno = 10
4 order by m.dname, e.ename;
ENAME SAL DNAME LOC
---------- ---------- -------------------- --------------------
CLARK 2450 ACCOUNTING NEW YORK
KING 10000 ACCOUNTING NEW YORK
MILLER 1300 ACCOUNTING NEW YORK
SQL>
答案 1 :(得分:0)
您可以尝试以下操作:
--Tables
CREATE TABLE dept (
deptno NUMBER,
dname VARCHAR2 (20),
loc VARCHAR2 (20)
);
/
CREATE TABLE employee (
employee_id NUMBER,
salary NUMBER
);
代码:
CREATE OR REPLACE TYPE mytype AS OBJECT (
deptno NUMBER,
dname VARCHAR2 (20),
loc VARCHAR2 (20)
);
CREATE OR REPLACE TYPE mytab AS TABLE OF mytype;
CREATE OR REPLACE FUNCTION myfunc ( p_in NUMBER)
RETURN mytab
IS
v_var mytab := mytab ();
BEGIN
SELECT
mytype (
deptno,
dname,
loc
)
BULK COLLECT INTO
v_var
FROM
dept
WHERE
deptno = p_in;
return (v_var);
END myfunc;
/
执行:
SELECT
e.*,
t.deptno,
t.dname
FROM
employee e
CROSS JOIN
TABLE ( myfunc (100) ) t ;
输出:
Employee_Id SALARY DEPT DNAME
--------- ------ ---- ------
1001 20000 100 Executive
1002 25000 100 Executive