简体   繁体   中英

oracle function which checks two tables for a record

I want to write below function in oracle 11g and I've tried many syntaxes, Non of them work.

function a(id Number) return VARCHAR2
begin

return(
case 
when
check if record exists in first table 
then
select a varchar column from record
when
check if record exists in second table 
then
select a varchar column from record
else
 ''
end
)

end

Any suggestions ?

Here's one option. I used Scott's sample tables. Read comments within code.

SQL> create or replace function f_test (par_id number)
  2    return varchar2
  3  is
  4    l_rec_emp   emp%rowtype;
  5    l_rec_dept  dept%rowtype;
  6    retval      varchar2(20);
  7  begin
  8    begin
  9      -- select from the first table
 10      select *
 11        into l_rec_emp
 12        from emp
 13        where empno = par_id;
 14      -- something was found; set return value
 15      retval := l_rec_emp.ename;
 16    exception
 17      when no_data_found then
 18      -- nothing was found in the first table; go on to the second
 19      begin
 20        select *
 21          into l_rec_dept
 22          from dept
 23          where deptno = par_id;
 24        -- something was found; set return value
 25        retval := l_rec_dept.dname;
 26      exception
 27        when no_data_found then
 28        -- nothing was found in the second table; return a dummy value
 29        retval := 'Dummy';
 30      end;
 31    end;
 32    -- return what you've found
 33    return retval;
 34  end;
 35  /

Function created.

Data I'll be testing is

SQL> select empno, ename from emp where empno = 7369;

     EMPNO ENAME
---------- ----------
      7369 SMITH

SQL> select deptno, dname from dept where deptno = 10;

    DEPTNO DNAME
---------- --------------
        10 ACCOUNTING

SQL> select f_test(7369) retval_1,
  2         f_test(10)   retval_2,
  3         f_test(-1)   retval_3
  4  from dual;

RETVAL_1     RETVAL_2     RETVAL_3
------------ ------------ ------------
SMITH        ACCOUNTING   Dummy

SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM