[英]oracle function which checks two tables for a record
我想在 oracle 11g 中編寫下面的函數,並且我嘗試了很多語法,但它們都不起作用。
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
有什么建議 ?
這是一種選擇。 我使用了 Scott 的示例表。 閱讀代碼中的注釋。
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.
我要測試的數據是
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.