2012-05-31 5 views
4

두 테이블 (직원 및 부서)을 사용하는 함수에서 % rowtype에 여러 값을 반환하려고하는데 저에게 맞지 않습니다.오라클 : 함수에서 여러 값 반환

create or replace function get_employee 
(loc in number) 
return mv_emp%rowtype 
as 
    emp_record mv_emp%rowtype; 
begin 
    select a.first_name, a.last_name, b.department_name into emp_record 
    from employees a, departments b 
    where a.department_id=b.department_id and location_id=loc; 

    return(emp_record); 
end; 

답변

8

위의 함수는 오류없이 컴파일 되었습니까? MV_EMP 유형은 무엇입니까? 이상적으로는 다음과 같아야합니다.

create or replace type emp_type 
(
first_name varchar2(20) 
, last_name varchar2(20) 
, depart_name varchar2(20) 
) 
/
create or replace function get_employee 
(loc in number) 
return emp_type 
as 
    emp_record emp_type; 
begin 
    select a.first_name, a.last_name, b.department_name into emp_record 
    from employees a, departments b 
    where a.department_id=b.department_id and location_id=loc; 

    return(emp_record); 
end; 
+2

다음과 같이 지정. 나는 타입 AS를 선언해야만했다. OBJECT – andersand

+0

또한이 구문을 11g으로 작성해야했다 : SELECT x.some_field, y.something_else INTO myobject.field1, myobject.field2 FROM ... – andersand

+2

객체를 초기화해야했다. 또한 다음과 같이하십시오.'myobject mytype : = mytype ('', '');' – andersand

1
create type t_row as object (a varchar2(10)); 

create type t_row_tab as table of t_row; 

우리는 지금 입력 문자열을 분할하는 함수를 작성합니다.

create or replace function get_number(pv_no_list in varchar2) return t_row_tab is 
lv_no_list t_row_tab := t_row_tab(); 
begin 

    for i in (SELECT distinct REGEXP_SUBSTR(pv_no_list, '[^,]+', 1, LEVEL) no_list FROM dual 
    CONNECT BY REGEXP_SUBSTR(pv_no_list, '[^,]+', 1, LEVEL) IS NOT NULL) 
    loop 
    lv_no_list.extend; 
    lv_no_list(lv_no_list.last) := t_row(i.no_list); 
    end loop; 

    return lv_no_list; 

end get_number; 

일단 함수가 준비되면 원하는 결과를 얻기 위해 sql 문의 table 절을 사용할 수 있습니다. 원하는대로 함수에서 반환 된 값이 여러 개 있습니다.

SQL> select * from table(get_number('1,2,3,4')); 


A 
---------- 
1 
3 
2 
4 

이제 우리의 기능은 단순히 테이블처럼 행동합니다. 이러한 쉼표로 구분 된 값을 "IN"절의 일부로 사용하려는 상황이있을 수 있습니다.

예를 들어

:

select * from dummy_table where dummy_column in ('1,2,3,4'); 

그러나 위의 쿼리가 '1,2,3,4'로 작동하지 않습니다 문자열이 아닌 개별 번호입니다. 이 문제를 해결하려면 다음 쿼리를 사용하면됩니다.

select * from dummy_table where dummy_column in (select * from table(get_number('1,2,3,4'))); 

참고 : 내 Oracle 버전, 11g, 유형 선언이 컴파일되지 않습니다에서 http://www.oraclebin.com/2012/12/returning-multiple-values-from-function.html