Select function that returns multiple columns.
Currently I have a function that will return 1 column and I can use that in a select statement. What I need is to return multiple columns from a table. In the function I have I return the street address from a table that holds information about dealers, I need to be able to also return the columns that contain the city, state, and zip code so it can be used in an sql select statement. How would I do this?
My function:
FUNCTION GET_ADDRESS(dealer_id IN number)
RETURN tbl_dealer_info.c_street%TYPE AS
v_rc tbl_dealer_info.c_street%TYPE;
CURSOR get_dealer_cur IS
SELECT c_street
FROM tbl_dealer_info
WHERE n_dealer_id = dealer_id;
BEGIN
v_rc := NULL;
OPEN get_dealer_cur;
FETCH get_dealer_cur INTO v_rc;
IF get_dealer_cur%NOTFOUND THEN
NULL;
END IF;
CLOSE get_dealer_cur;
RETURN v_rc;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END GET_ADDRESS;
My select statement:
select GET_ADDRESS(1205) Street, DI.n_inactive_flag, DI.n_onhold_flag
from tbl_dealer_info DI
where DI.n_dealer_id = 1205;
I would like to be able to select the street, city, state, and zip all in this select statement from the GET_ADDRESS function.
Thanks,
Lori Neirynck
"The reality is you've probably already put your blinders on and you won't learn the best approach to solving your problem because you insist on asking a courtroom style question (just "yes" or "no" please)."
Actually, I asked this question because I was looking for the best approach to my problem. I have an SQL statement that correctly selects everything it needs to from all 15 tables. The thing of it is it is very long and difficult to read. I wanted to try using functions so that I could change 12 AND/OR statements into 3 IF statements so everything is easier to read. I have received a couple of different ways to do this from other forums that assumed I knew what I was doing. I have gotten one to work, the other I'm still working on. I'll post the one that worked for others that want to know.
SQL> insert into dealer_info values (1,'Me','13 success street', 'Wonder Town','Wonderland','1313');
SQL> commit;
SQL> create type t_address as object (
2 street varchar2(100),
3 city varchar2(30),
4 state varchar2(30),
5 zip varchar2(10));
6 /
Type created.
SQL> create or replace function get_address (p_id number) return t_address
2 is
3 ret t_address := t_address(null,null,null,null);
4 rec dealer_info%rowtype;
5 begin
6 select * into rec from dealer_info where id=p_id;
7 ret.street := rec.street;
8 ret.city := rec.city;
9 ret.state := rec.state;
10 ret.zip := rec.zip;
11 return ret;
12 end;
13 /
Function created.
SQL> col name format a10
SQL> col address format a70
SQL> select name, get_address(id) address from dealer_info;
NAME ADDRESS(STREET, CITY, STATE, ZIP)
Me T_ADDRESS('13 success street', 'Wonder Town', 'Wonderland', '1313')
1 row selected.
-Lori
Similar Messages
-
How to create a function that returns multiple rows in table
Dear all,
I want to create a funtion that returns multiple rows from the table (ex: gl_balances). I done following:
-- Create type (successfull)
Create or replace type tp_gl_balance as Object
PERIOD_NAME VARCHAR2(15),
CURRENCY_CODE VARCHAR2(15),
PERIOD_TYPE VARCHAR2(15),
PERIOD_YEAR NUMBER(15),
BEGIN_BALANCE_DR NUMBER,
BEGIN_BALANCE_CR NUMBER
-- successfull
create type tp_tbl_gl_balance as table of tp_gl_balance;
but i create a function for return some rows from gl_balances, i can't compile it
create or replace function f_gl_balance(p_period varchar2) return tp_tbl_gl_balance pipelined
as
begin
return
(select gb.period_name, gb.currency_code, gb.period_type, gb.period_year, gb.begin_balance_dr, gb.begin_balance_cr
from gl_balances gb
where gb.period_name = p_period);
end;
I also try
create or replace function f_gl_balance(p_period varchar2) return tp_tbl_gl_balance pipelined
as
begin
select gb.period_name, gb.currency_code, gb.period_type, gb.period_year, gb.begin_balance_dr, gb.begin_balance_cr
from gl_balances gb
where gb.period_name = p_period;
return;
end;
Please help me solve this function.
thanks and best reguardhi,
Use TABLE FUNCTIONS,
[http://www.oracle-base.com/articles/9i/PipelinedTableFunctions9i.php]
Regards,
Danish -
Need a function that return multiple rows
Hi,
I need a function that should return output of this query
SELECT b.branding_code, c.name_desc
FROM
development.brandings b, godot.company c
WHERE b.company_id = c.company_id;
This above function return 30 rows and I am not giving any input
Function using cursor,pipeline
Please help
Edited by: 1008783 on Jun 6, 2013 6:40 AMHi,
1008783 wrote:
Hi
Table A:
Development schema
branding_code,company_id
Table B:
Gogot schema
name_desc,...Those aren't CREATE TABLE and INSERT statements. Post something that the people who want to help you can run on their own systems to re-create the problem and test their ideas.
o/p:
branding_code,name_desc
I should return these column as o/p, no i/pA query will do that. There's no need for a function.
There are good reasons for wanting a functin. If you have one, say what it is. Explain how you plan to use the function.
Have you tried writing a function? Post your code. What specific problems did you have? -
Trying to do something as data would be uploaded and edited in grid. At present I am using Ora_Hash.
SELECT
e.ROWID, e.Employee_Id,e.First_Name,e.Last_Name,e.Email,e.Phone_Number,e.Hire_Date,
e.Job_Id,e.Salary,e.Manager_Id,e.Department_Id,
owa_opt_lock.checksum('HR','EMPLOYEES', e.rowid) As HashForThisRow
FROM EMPLOYEES e;
ThxNo you can't.
owa_opt_lock.checksum is a function which is used for optimist locking. It locks the row(probably by using Select FOR Update mechanism) which you select and which you are trying to update. As a result, what you are eventually trying to do is that inside a Select query you are using a function that is locking the rows, which is not allowed. And thus your query will fail with the below mentioned error.
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "SYS.DBMS_SQL", line 1575
ORA-06512: at "SYS.OWA_OPT_LOCK", line 172
14551. 00000 - "cannot perform a DML operation inside a query "
*Cause: DML operation like insert, update, delete or select-for-update
cannot be performed inside a query or under a PDML slave.
*Action: Ensure that the offending DML operation is not performed or
use an autonomous transaction to perform the DML operation within
the query or PDML slave.
Thanks,
Ishan -
How to Make FUNCTION to return multiple column and multiple row output
Hi All,
Kindly Share ur Idea;Thanks in Advance;
i Have Table Demo.
table DEMO:
id name
1 a10
1 a11
1 a12
2 b10
2 b11
3 ccc
and the function is like:
create or replace function (p1 number) return varchar2 as
vid number;
vname varchar2(20);
begin
select id,name into vid,vname from demo where id=p1;
return v1;
end;
this function returns output for id=3;
BUT,
i need output as (for input as 1)
vid vname
1 a10
1 a11
1 a12A function returns a single datatype.
That datatype may be an atomic datatype (varchar2, number etc.) or it may be an object/record datatype, or even a collection datatype.
Where are you going to use this function? In PL/SQL or SQL?
If you are wanting to use it in SQL, then you would need a pipelined function e.g.
SQL> CREATE OR REPLACE TYPE myemp AS OBJECT
2 ( empno number,
3 ename varchar2(10),
4 job varchar2(10),
5 mgr number,
6 hiredate date,
7 sal number,
8 comm number,
9 deptno number
10 )
11 /
Type created.
SQL> CREATE OR REPLACE TYPE myrectable AS TABLE OF myemp
2 /
Type created.
SQL> CREATE OR REPLACE FUNCTION pipedata(p_min_row number, p_max_row number) RETURN myrectable PIPELINED IS
2 v_obj myemp := myemp(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
3 BEGIN
4 FOR e IN (select *
5 from (
6 select e.*
7 ,rownum rn
8 from (select * from emp order by empno) e
9 )
10 where rn between p_min_row and p_max_row)
11 LOOP
12 v_obj.empno := e.empno;
13 v_obj.ename := e.ename;
14 v_obj.job := e.job;
15 v_obj.mgr := e.mgr;
16 v_obj.hiredate := e.hiredate;
17 v_obj.sal := e.sal;
18 v_obj.comm := e.comm;
19 v_obj.deptno := e.deptno;
20 PIPE ROW (v_obj);
21 END LOOP;
22 RETURN;
23 END;
24 /
Function created.
SQL> select * from table(pipedata(1,5));
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-1980 00:00:00 800 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 00:00:00 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-1981 00:00:00 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 00:00:00 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 00:00:00 1250 1400 30
SQL> select * from table(pipedata(6,10));
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7698 BLAKE MANAGER 7839 01-MAY-1981 00:00:00 2850 30
7782 CLARK MANAGER 7839 09-JUN-1981 00:00:00 2450 10
7788 SCOTT ANALYST 7566 19-APR-1987 00:00:00 3000 20
7839 KING PRESIDENT 17-NOV-1981 00:00:00 5000 10
7844 TURNER SALESMAN 7698 08-SEP-1981 00:00:00 1500 0 30
SQL> select * from table(pipedata(11,15));
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 23-MAY-1987 00:00:00 1100 20
7900 JAMES CLERK 7698 03-DEC-1981 00:00:00 950 30
7902 FORD ANALYST 7566 03-DEC-1981 00:00:00 3000 20
7934 MILLER CLERK 7782 23-JAN-1982 00:00:00 1300 10
SQL>If you are using it in PL/SQL then just populating a collection datatype and returning that will do. Though you should question why you want to pass large amounts of data around like that first.
Explain your purpose and what you are intending to do and we can recommend the best way.
{message:id=9360002} -
Function that returns currently selected cell address or column
Is there a function that returns the address (or just the column) of the currently selected cell? Simply put, something like =selectedcolumn.
Background: I want to display help text in a cell, and I want that help text to change according to which cell (actually, which column) the user has selected. I have put the help texts in a hidden row. They take up too much space to be displayed all the time. I want one cell to contain the help text of the column of the currently selected cell.
Trying to not use Filemaker for this project if possible
Thanks for any help /MattThe Numbers method, using comments as Barry showed, is probably the best method. An alternate method which is more complex would be to use an Applescript running in the background. The Applescript can scan in the background for which cell/column is currently selected and write that cell/column address into a cell in your table. A formula in your table (most likely a lookup formula) can use that address to serve up the correct help text in a diffrerent cell in the table or in another table.
Some problems with this methodare
The script is not part of the document. It is a separate entity.
The script must be started manually. It will not automatically start when the Numbers document is opened.
If the Numbers document is to be used on other Macs, each would also need the script installed. -
Function which returns multiple values that can then be used in an SQL Sele
I'd like to create a function which returns multiple values that can then be used in an SQL Select statement's IN( ) clause
Currently, the select statement is like (well, this is a very simplified version):
select application, clientid
from tbl_apps, tbl_status
where tbl_apps.statusid = tbl_status.statusid
and tbl_status.approved > 0;
I'd like to pull the checking of the tbl_status into a PL/SQL function so my select would look something like :
select application, clientid
from tbl_apps
where tbl_apps.statusid in (myfunction);
So my function would be running this sql:
select statusid from tbl_status where approved > 0;
... will return values 1, 5, 15, 32 (and more)
... but I haven't been able to figure out how to return the results so they can be used in SQL.
Thanks for any help you can give me!!
Trisha GorrPerhaps take a look at pipelined functions:
Single column example:
SQL> CREATE OR REPLACE TYPE split_tbl IS TABLE OF VARCHAR2(32767);
2 /
Type created.
SQL> CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_delim VARCHAR2:=' ') RETURN SPLIT_TBL PIPELINED IS
2 l_idx PLS_INTEGER;
3 l_list VARCHAR2(32767) := p_list;
4 l_value VARCHAR2(32767);
5 BEGIN
6 LOOP
7 l_idx := INSTR(l_list, p_delim);
8 IF l_idx > 0 THEN
9 PIPE ROW(SUBSTR(l_list, 1, l_idx-1));
10 l_list := SUBSTR(l_list, l_idx+LENGTH(p_delim));
11 ELSE
12 PIPE ROW(l_list);
13 EXIT;
14 END IF;
15 END LOOP;
16 RETURN;
17 END SPLIT;
18 /
Function created.
SQL> SELECT column_value
2 FROM TABLE(split('FRED,JIM,BOB,TED,MARK',','));
COLUMN_VALUE
FRED
JIM
BOB
TED
MARK
SQL> create table mytable (val VARCHAR2(20));
Table created.
SQL> insert into mytable
2 select column_value
3 from TABLE(split('FRED,JIM,BOB,TED,MARK',','));
5 rows created.
SQL> select * from mytable;
VAL
FRED
JIM
BOB
TED
MARK
SQL>Multiple column example:
SQL> CREATE OR REPLACE TYPE myrec AS OBJECT
2 ( col1 VARCHAR2(10),
3 col2 VARCHAR2(10)
4 )
5 /
Type created.
SQL>
SQL> CREATE OR REPLACE TYPE myrectable AS TABLE OF myrec
2 /
Type created.
SQL>
SQL> CREATE OR REPLACE FUNCTION pipedata(p_str IN VARCHAR2) RETURN myrectable PIPELINED IS
2 v_str VARCHAR2(4000) := REPLACE(REPLACE(p_str, '('),')');
3 v_obj myrec := myrec(NULL,NULL);
4 BEGIN
5 LOOP
6 EXIT WHEN v_str IS NULL;
7 v_obj.col1 := SUBSTR(v_str,1,INSTR(v_str,',')-1);
8 v_str := SUBSTR(v_str,INSTR(v_str,',')+1);
9 IF INSTR(v_str,',')>0 THEN
10 v_obj.col2 := SUBSTR(v_str,1,INSTR(v_str,',')-1);
11 v_str := SUBSTR(v_str,INSTR(v_str,',')+1);
12 ELSE
13 v_obj.col2 := v_str;
14 v_str := NULL;
15 END IF;
16 PIPE ROW (v_obj);
17 END LOOP;
18 RETURN;
19 END;
20 /
Function created.
SQL>
SQL> create table mytab (col1 varchar2(10), col2 varchar2(10));
Table created.
SQL>
SQL> insert into mytab (col1, col2) select col1, col2 from table(pipedata('(1,2),(2,3),(4,5)'));
3 rows created.
SQL>
SQL> select * from mytab;
COL1 COL2
1 2
2 3
4 5 -
Selecting from a function that returns a sys refcursor or an alternative
I have a query that returns a resultset of three columns, namely SSN,PAID_YEAR and PAID_TOTAL. From this query I can:
Create a view and then query it.
Create a function and return resultset
If I go the first way a simple query like the following takes more than 20 seconds:
SELECT PAID_YEAR,PAID_TOTAL FROM VIEW_1 WHERE SSN=12345678912882;
I know that is because when I query a view the engine first brings all the rows of the view and then it filters the rows for the criteria supplied.
If I go the second way I can send a parameter and make the engine look only for those rows that match the condition and return the recordset. But I do not know how to then SELECT from that returned resultset. I took a look at pipelined tables but didn't quite get how to benefit them. So my ultimate question is if it's somehow possible to select from the resultset that is returned from a function like this:
SELECT * FROM FUNCTION_1(12132323232).
If yes, then how, if no, what would be an alternative way?I know that is because when I query a view the engine first brings all the rows of the view and then it filters the rows for the criteria supplied.
No - you don't 'know that' because it isn't true. Just check the explain plan for yourself. Oracle can still use any appropriate indexes so that only the rows needed are returned.
So my ultimate question is if it's somehow possible to select from the resultset that is returned from a function like this:
SELECT * FROM FUNCTION_1(12132323232).
No - you can't do it like that. You have to use the TABLE function to treat the function result set as a table:
'SELECT * FROM TABLE(FUNCTION_1(12132323232)).
-- type to match emp record
create or replace type emp_scalar_type as object
(EMPNO NUMBER(4) ,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7, 2),
COMM NUMBER(7, 2),
DEPTNO NUMBER(2)
-- table of emp records
create or replace type emp_table_type as table of emp_scalar_type
-- pipelined function
create or replace function get_emp( p_deptno in number )
return emp_table_type
PIPELINED
as
TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
emp_cv EmpCurTyp;
l_rec emp%rowtype;
begin
open emp_cv for select * from emp where deptno = p_deptno;
loop
fetch emp_cv into l_rec;
exit when (emp_cv%notfound);
pipe row( emp_scalar_type( l_rec.empno, LOWER(l_rec.ename),
l_rec.job, l_rec.mgr, l_rec.hiredate, l_rec.sal, l_rec.comm, l_rec.deptno ) );
end loop;
return;
end;
select * from table(get_emp(20)) -
SELECT in SELECT returning multiple columns ?
10.2.0.3 version.
I am trying to tune this query
SELECT A.EMPLID, A.EFFDT, A.ACAD_PROG,
(SELECT A1.DESCR FROM PS_ACAD_PROG_TBL A1
WHERE A1.INSTITUTION = 'AUAO1' AND A1.ACAD_PROG = A.ACAD_PROG AND A1.EFFDT = (SELECT MAX (EFFDT) FROM PS_ACAD_PROG_TBL WHERE INSTITUTION = A1.INSTITUTION AND ACAD_PROG = A1.ACAD_PROG),
(SELECT A2.DESCRSHORT FROM PS_ACAD_PROG_TBL A2
WHERE A2.INSTITUTION = 'AUAO1' AND A2.ACAD_PROG = A.ACAD_PROG AND A2.EFFDT = (SELECT MAX (EFFDT) FROM PS_ACAD_PROG_TBL WHERE INSTITUTION = A2.INSTITUTION AND ACAD_PROG = A2.ACAD_PROG),
as you can see it reading the table PS_ACAD_PROG_TBL two time to get two cloumns DESCR (alias A1) and DESCRSHORT (alias A2) exactly with the same where condition.
I am trying to replace it with just one select returning multiple columns like this
SELECT A.EMPLID, A.EFFDT, A.ACAD_PROG,
(SELECT A1.DESCR, A1.DESCRSHORT FROM PS_ACAD_PROG_TBL A1
WHERE A1.INSTITUTION = 'AUAO1' AND A1.ACAD_PROG = A.ACAD_PROG AND A1.EFFDT = (SELECT MAX (EFFDT) FROM PS_ACAD_PROG_TBL WHERE INSTITUTION = A1.INSTITUTION AND ACAD_PROG = A1.ACAD_PROG),
but I am getting ORA-00913: too many values.
Please help on how to get around this. Thanks in advance.William,
On similar lines I am struggling with the below query based on your suggestions.
SQL*Plus: Release 9.2.0.1.0 - Production on Wed Aug 5 14:17:21 2009
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> WITH arch_dup AS
2 (SELECT a.file_id,
3 a.sale_start,
4 a.activity_start,
5 a.activity_end,
6 a.item_code_cust,
7 a.division,
8 (SELECT MAX (DISTINCT (NVL (b.advertised, 'No')))
9 FROM ah_cust_gis_arch_stg b
10 WHERE b.file_id = a.file_id
11 AND NVL (b.sale_start, 'NULL') = NVL (a.sale_start, 'NULL')
12 AND NVL (b.activity_start, 'NULL') = NVL (a.activity_start, 'NULL')
13 AND NVL (b.activity_end, 'NULL') = NVL (a.activity_end, 'NULL')
14 AND b.item_code_cust = a.item_code_cust
15 AND b.division = a.division) advertised,
16 COUNT (*)
17 FROM ah_cust_gis_arch_stg a
18 WHERE a.file_id = 209
19 AND a.status_id = 21
20 GROUP BY a.file_id, a.sale_start, a.activity_start, a.activity_end, a.item_code_cust, a.d
ivision
21 HAVING COUNT (*) > 1)
22 SELECT dup.*,
23 (SELECT activity_id
24 FROM (SELECT activity_id,
25 ROW_NUMBER () OVER (ORDER BY (activity_retail / activity_mult)) rnk
26 FROM ah_cust_gis_arch_stg
27 WHERE status_id = 21
28 AND NVL (sale_start, 'NULL') = NVL (dup.sale_start, 'NULL')
29 AND NVL (activity_start, 'NULL') = NVL (dup.activity_start, 'NULL')
30 AND NVL (activity_end, 'NULL') = NVL (dup.activity_end, 'NULL')
31 AND item_code_cust = dup.item_code_cust
32 AND division = dup.division
33 AND file_id = 209
34 AND UPPER (NVL (advertised, 'N')) = dup.advertised)
35 WHERE rnk = 1) activity_id
36 FROM arch_dup dup;
AND UPPER (NVL (advertised, 'N')) = dup.advertised)
ERROR at line 34:
ORA-00904: "DUP"."ADVERTISED": invalid identifierCan you throw some light on what to do to make the outer query columns available to inner query?
Thanks,
Raj. -
SOLVED: How can I use or call a function that returns %ROWTYPE?
Hi
edit: you can probably skip all this guff and go straight to the bottom...In the end this is probably just a question of how to use a function that returns a %rowtype. Thanks.
Currently reading Feuerstein's tome, 5th ed. I've downloaded and run the file genaa.sp, which is a code generator. Specifically, you feed it a table name and it generates code (package header and package body) that will create a cache of the specified table's contents.
So, I ran:
HR@XE> @"C:\Documents and Settings\Jason\My Documents\Work\SQL\OPP5.WEB.CODE\OPP5.WEB.CODE\genaa.sp"
749 /
Procedure created.
HR@XE> exec genaa('EMPLOYEES');which generated a nice bunch of code, viz:
create or replace package EMPLOYEES_cache is
function onerow ( EMPLOYEE_ID_in IN HR.EMPLOYEES.EMPLOYEE_ID%TYPE) return HR.EMPLOYEES%ROWTYPE;
function onerow_by_EMP_EMAIL_UK (EMAIL_in IN HR.EMPLOYEES.EMAIL%TYPE) return HR.EMPLOYEES%ROWTYPE;
procedure test;
end EMPLOYEES_cache;
create or replace package body EMPLOYEES_cache is
TYPE EMPLOYEES_aat IS TABLE OF HR.EMPLOYEES%ROWTYPE INDEX BY PLS_INTEGER;
EMP_EMP_ID_PK_aa EMPLOYEES_aat;
TYPE EMP_EMAIL_UK_aat IS TABLE OF HR.EMPLOYEES.EMPLOYEE_ID%TYPE INDEX BY HR.EMPLOYEES.EMAIL%TYPE;
EMP_EMAIL_UK_aa EMP_EMAIL_UK_aat;
function onerow ( EMPLOYEE_ID_in IN HR.EMPLOYEES.EMPLOYEE_ID%TYPE)
return HR.EMPLOYEES%ROWTYPE is
begin
return EMP_EMP_ID_PK_aa (EMPLOYEE_ID_in);
end;
function onerow_by_EMP_EMAIL_UK (EMAIL_in IN HR.EMPLOYEES.EMAIL%TYPE)
return HR.EMPLOYEES%ROWTYPE is
begin
return EMP_EMP_ID_PK_aa (EMP_EMAIL_UK_aa (EMAIL_in));
end;
procedure load_arrays is
begin
FOR rec IN (SELECT * FROM HR.EMPLOYEES)
LOOP
EMP_EMP_ID_PK_aa(rec.EMPLOYEE_ID) := rec;
EMP_EMAIL_UK_aa(rec.EMAIL) := rec.EMPLOYEE_ID;
end loop;
END load_arrays;
procedure test is
pky_rec HR.EMPLOYEES%ROWTYPE;
EMP_EMAIL_UK_aa_rec HR.EMPLOYEES%ROWTYPE;
begin
for rec in (select * from HR.EMPLOYEES) loop
pky_rec := onerow (rec.EMPLOYEE_ID);
EMP_EMAIL_UK_aa_rec := onerow_by_EMP_EMAIL_UK (rec.EMAIL);
if rec.EMPLOYEE_ID = EMP_EMAIL_UK_aa_rec.EMPLOYEE_ID then
dbms_output.put_line ('EMP_EMAIL_UK lookup OK');
else
dbms_output.put_line ('EMP_EMAIL_UK lookup NOT OK');
end if;
end loop;
end test;
BEGIN
load_arrays;
end EMPLOYEES_cache;
/which I have run successfully:
HR@XE> @"C:\Documents and Settings\Jason\My Documents\Work\SQL\EMPLOYEES_CACHE.sql"
Package created.
Package body created.I am now trying to use the functionality within the package.
I have figured out that the section
BEGIN
load_arrays;
end EMPLOYEES_cache;
/is the initialization section, and my understanding is that this is supposed to run when any of the package variables or functions are referenced. Is that correct?
With that in mind, I'm trying to call the onerow() function, but it's not working:
HR@XE> select onerow(100) from dual;
select onerow(100) from dual
ERROR at line 1:
ORA-00904: "ONEROW": invalid identifier
HR@XE> select employees_cache.onerow(100) from dual;
select employees_cache.onerow(100) from dual
ERROR at line 1:
ORA-06553: PLS-801: internal error [55018]
HR@XE> select table(employees_cache.onerow(100)) from dual;
select table(employees_cache.onerow(100)) from dual
ERROR at line 1:
ORA-00936: missing expressionHe provides the code genaa.sp, and a very brief description of what it does, but doesn't tell us how to run the generated code!
Now, I have just done some googling, and it seems that what I am trying to do isn't possible. Apparently %ROWTYPE is PL/SQL, and not understood by SQL, so you can't call onerow() from sql. Correct?
So I try wrapping the call in an exec:
HR@XE> exec select employees_cache.onerow(100) from dual;
BEGIN select employees_cache.onerow(100) from dual; END;
ERROR at line 1:
ORA-06550: line 1, column 30:
PLS-00382: expression is of wrong type
ORA-06550: line 1, column 7:
PLS-00428: an INTO clause is expected in this SELECT statement
HR@XE> exec select table(employees_cache.onerow(100)) from dual;
BEGIN select table(employees_cache.onerow(100)) from dual; END;
ERROR at line 1:
ORA-06550: line 1, column 14:
PL/SQL: ORA-00936: missing expression
ORA-06550: line 1, column 7:
PL/SQL: SQL Statement ignored
HR@XE> exec employees_cache.onerow(100)
BEGIN employees_cache.onerow(100); END;
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00221: 'ONEROW' is not a procedure or is undefined
ORA-06550: line 1, column 7:
PL/SQL: Statement ignoredNo joy.
Of course, now that I'm looking at it again, it seems that the way to go is indicated by the first error:
PLS-00428: an INTO clause is expected in this SELECT statement
So am I supposed to create a type of EMPLOYEES%ROWTYPE in a PL/SQL procedure, and the idea of this code, is that the first call to onerow() runs the initialiation code, which populates the cache, and all subsequent calls to onerow() (whether by my session or any other) will use the cache?
I've had a stab at this, but still, no joy:
create or replace procedure testcache is
emp employees%rowtype;
begin
select employees_cache.onerow(100) from dual into emp;
dbms_output.put_line('Emp id: ' || emp.employee_id);
end testcache;
show errors
HR@XE> @testcache.sql
Warning: Procedure created with compilation errors.
Errors for PROCEDURE TESTCACHE:
LINE/COL ERROR
4/9 PL/SQL: SQL Statement ignored
4/54 PL/SQL: ORA-00933: SQL command not properly ended
HR@XE>Have a feeling this should be really easy. Can anybody help?
Many thanks in advance.
Jason
Edited by: 942375 on 08-Feb-2013 11:45>
Ha, figured it out
>
Hopefully you also figured out that the example is just that: a technical example of how to use certain Oracle functionality. Unfortunately it is also an example of what you should NOT do in an actual application.
That code isn't scaleable, uses expensive PGA memory, has no limit on the amount of memory that might be used and, contrary to your belief will result in EVERY SESSION HAVING ITS OWN CACHE of exactly the same data if the session even touches that package.
Mr. Feuerstein is an expert in SQL and PL/SQL and his books cover virtually all of the functionality available. He also does an excellent job of providing examples to illustrate how that functionality can be combined and used. But the bulk of those examples are intended solely to illustrate the 'technical' aspects of the technology. They do not necessarily reflect best practices and they often do not address performance or other issues that need to be considered when actually using those techniques in a particular application. The examples show WHAT can be done but not necessarily WHEN or even IF a given technique should be used.
It is up to the reader to learn the advantages and disadvantages of each technicalogical piece and determine when and how to use them.
>
Now, I have just done some googling, and it seems that what I am trying to do isn't possible. Apparently %ROWTYPE is PL/SQL, and not understood by SQL, so you can't call onerow() from sql. Correct?
>
That is correct. To be used by SQL you would need to create SQL types using the CREATE TYPE syntax. Currently that syntax does not support anything similar to %ROWTYPE.
>
So am I supposed to create a type of EMPLOYEES%ROWTYPE in a PL/SQL procedure, and the idea of this code, is that the first call to onerow() runs the initialiation code, which populates the cache, and all subsequent calls to onerow() (whether by my session or any other) will use the cache?
>
NO! That is a common misconception. Each session has its own set of package variables. Any session that touches that package will cause the entire EMPLOYEES table to be queried and stored in a new associative array specifically for that session.
That duplicates the cache for each session using the package. So while there might be some marginal benefit for a single session to cache data like that the benefit usually disappears if multiple sessions are involved.
The main use case that I am aware of where such caching has benefit is during ETL processing of staged data when the processing of each record is too complex to be done in SQL and the records need to be BULK loaded and the data manipulated in a loop. Then using an associative array as a lookup table to quickly get a small amount of data can be effective. And if the ETL procedure is being processed in parallel (meaning different sessions) then for a small lookup array the additional memory use is tolerable.
Mitigating against that is the fact that:
1. Such frequently used data that you might store in the array is likely to be cached by Oracle in the buffer cache anyway
2. Newer versions of Oracle now have more than one cache
3. The SQL query needed to get the data from the table will use a bind variable that eliminates repeated hard parsing.
4. The cursor and the buffer caches ARE SHARED by multiple sessions globally.
So the short story is that there would rarely be a use case where ARRAYs like that would be preferred over accessing the data from the table. -
How to use Cursor's Fetch to return multiple column Data
Hi ,
This is my Table :
SQL> select * from Login;
USERNAME PASSWORD CONFIRMPASSWORD
RAvi SAI SAI
Kiran Keyboard Keyboard
VARNU JAINA JAINA
This is my stored Procedure , for that Table , this is working fine , where he Cursor's Fetch is returning only a Single column of Data .
CREATE OR REPLACE PROCEDURE getEmpName(EMP_ID IN VARCHAR2)
IS
EMPNAME VARCHAR2(50);
CURSOR MYCUR
IS
SELECT USERNAME from login where USERNAME=EMP_ID;
BEGIN
OPEN MYCUR ;
LOOP
FETCH MYCUR INTO EMPNAME;
DBMS_OUTPUT.PUT_LINE(EMPNAME);
EXIT WHEN MYCUR%NOTFOUND;
END LOOP;
close MYCUR ;
END;
Now , I have a requirement as , i need to get the Password also along with Username ,
Please tell me how can i use FETCH of Cursor to populate Details into the Declared Variables
FETCH MYCUR INTO EMPNAME;
CREATE OR REPLACE PROCEDURE getEmpName(EMP_ID IN VARCHAR2)
IS
EMPNAME VARCHAR2(50);
PASSWORD VARCHAR2(50);
CURSOR MYCUR
IS
SELECT USERNAME , PASSWORD from login where USERNAME=EMP_ID;
BEGIN
OPEN MYCUR ;
LOOP
FETCH MYCUR INTO EMPNAME; // Help needed here**
DBMS_OUTPUT.PUT_LINE(EMPNAME);
EXIT WHEN MYCUR%NOTFOUND;
END LOOP;
close MYCUR ;
END;
Edited by: user10503747 on Oct 14, 2010 11:51 AM
Edited by: user10503747 on Oct 14, 2010 11:52 AM1) I'm hoping that this is a homework assignment. You would never, in the real world, store a password in clear text. And you would never, from a database design, have separate Password and ConfirmPassword columns.
2) The INTO clause can accept a list of variables. So
FETCH your_cursor_name INTO local_variable1, local_variable2;would be valid.
3) You would generally want to avoid having local variables that share the name of a column-- that leads to some pretty serious confusion related to scoping. One common convention is to prefix local variables with a "l_".
4) You would generally want local variables to inherit the type of the column rather than explicitly declaring the length of a string in your procedure. That way, if you change the table in the future, your code will continue to work.
5) And finally, a procedure that just calls DBMS_OUTPUT would cause all sorts of red flags in reality. It would make far more sense for this to be a function that returns a value than a procedure that tries to write to a buffer that the client application may or may not have created.
Justin -
Error with function that returns a rowtype...
i have a function that returns a rowtype. below is a simplified version:
create or replace function "GETC"
return mytable%rowtype
is
rec mytable%rowtype;
begin
rec.rowid := 1;
return rec;
end;
eventually i'll want to call this from java. but for now i'd settle for calling it from the XE web front end (and sqlplus).
SQLPLUS: i try to call it from sqlplus by first declaring a variable where i can store the return:
var a mytable%rowtype;
it instantly stops me saying that i can only declare a var of a particular type. so what do i do?
XE interface: i tried various ways to call getc(), but they were all unsuccessful. what should i be doing?
thanks so much for your time.
markoGiven a function like this:
CREATE OR REPLACE FUNCTION get_employee
( p_empno emp.empno%TYPE )
RETURN emp%ROWTYPE
AS
v_result emp%ROWTYPE;
BEGIN
SELECT * INTO v_result
FROM emp
WHERE empno = p_empno;
RETURN v_result;
END get_employee;You can call it within PL/SQL like this:
DECLARE
rec emp%ROWTYPE;
BEGIN
rec := get_employee(7902);
DBMS_OUTPUT.PUT_LINE(rec.ename);
END;However,
1. Unless there is a column named "ROWID" in the table (unlikely since it would conflict with the actual rowid and is therefore not allowed), the type will not have an attribute named "rowid".
2. "1" would not be a valid rowid anyway.
3. %ROWTYPE defines a PL/SQL type, which will not be recognised in other environments such as SQL and Java. -
Stored procedure in package return multiple columns from multiple tables
Hi ,
Can a single stored procedure return multiple column values from different tables.
example:
tabA: col2, tabB:col3,tabC:col4 etc.
one more question:
if a stored procedure like to return 10 columns for a particular record from a single table do i need to define a TYPE statement for each colum like
TYPE col1 is TABLE of varchar
TYPE col2 is TABLE of varchar
here i want to return only one row, not many rows.
thanksYou can try one procedure with OUT or IN/OUT parameters that collect the values from one or more sql statements.
CREATE OR REPLACE PROCEDURE P1
(P_COD IN TABLE.COD%TYPE,
P_DESC1 OUT TABLE1.DESC1%TYPE,
P_DESC2 OUT TABLE2.DESC2%TYPE)
IS
BEGIN
SELECT table1.DESC1, table2.DESC2
INTO P_DESC1, P_DESC2
FROM TABLE1, table2 WHERE
table1.COD = P_COD and
table1.cod = table2.cod ;
END P1;
JP -
Is there any function that returns the latest DDL statement
can anyone tell me if there is any FUNCTION that returns latest DDL statement performed in a schema.
OR
if there is any TABLE that will be populated with latest
DDL statement in schema.
THANK YOU.The table all_objects (and/or dba_objects) contains a column called last_ddl_time. Thus, a query like
scott@jcave > SELECT max(last_ddl_time)
2 FROM all_objects
3 WHERE owner = 'SCOTT';
MAX(LAST_DDL_TI
28-NOV-03will tell you the last time any object owned by SCOTT had DDL issued against it.
Justin
Distributed Database Consulting, Inc.
www.ddbcinc.com/askDDBC -
Stored procedure that returns multiple tables
Hello everyone,
I was wondering if there's a way to write a stored procedure that returns multiple result set as in sql server. for example, in sql server, you can write 2 select statements and when loading them in c#, u can get two data tables.
I am not sure having a single ref cursor for each select is the only solution. I might need to return a variable number of tables per procedure call (based on a certain criteria).
Any ideas?
thanks for your timeSure. Ref cursor is the only easier answer for your problem.
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
Elapsed: 00:00:01.43
satyaki>
satyaki>create or replace procedure ref_gen_arg(choice in int,b in out sys_refcursor)
2 is
3 str varchar2(500);
4 begin
5 if choice = 1 then
6 str := 'select * from emp';
7 elsif choice = 2 then
8 str := 'select * from dept';
9 end if;
10
11 open b for str;
12 exception
13 when others then
14 dbms_output.put_line(sqlerrm);
15 end;
16 /
Procedure created.
Elapsed: 00:00:04.38
satyaki>
satyaki>
satyaki>declare
2 rec_x emp%rowtype;
3 rec_y dept%rowtype;
4 w sys_refcursor;
5 begin
6 dbms_output.enable(1000000);
7 ref_gen_arg(1,w);
8 loop
9 fetch w into rec_x;
10 exit when w%notfound;
11 dbms_output.put_line('Employee No: '||rec_x.empno||' - '||
12 'Name: '||rec_x.ename||' - '||
13 'Job: '||rec_x.job||' - '||
14 'Manager: '||rec_x.mgr||' - '||
15 'Joining Date: '||rec_x.hiredate||' - '||
16 'Salary: '||rec_x.sal||' - '||
17 'Commission: '||rec_x.comm||' - '||
18 'Department No: '||rec_x.deptno);
19 end loop;
20 close w;
21
22 ref_gen_arg(2,w);
23 loop
24 fetch w into rec_y;
25 exit when w%notfound;
26 dbms_output.put_line('Department No: '||rec_y.deptno||' - '||
27 'Name: '||rec_y.dname||' - '||
28 'Location: '||rec_y.loc);
29 end loop;
30 close w;
31 exception
32 when others then
33 dbms_output.put_line(sqlerrm);
34 end;
35 /
Employee No: 9999 - Name: SATYAKI - Job: SLS - Manager: 7698 - Joining Date: 02-NOV-08 - Salary: 55000 - Commission: 3455 - Department No: 10
Employee No: 7777 - Name: SOURAV - Job: SLS - Manager: - Joining Date: 14-SEP-08 - Salary: 45000 - Commission: 3400 - Department No: 10
Employee No: 7521 - Name: WARD - Job: SALESMAN - Manager: 7698 - Joining Date: 22-FEB-81 - Salary: 1250 - Commission: 500 - Department No: 30
Employee No: 7566 - Name: JONES - Job: MANAGER - Manager: 7839 - Joining Date: 02-APR-81 - Salary: 2975 - Commission: - Department No: 20
Employee No: 7654 - Name: MARTIN - Job: SALESMAN - Manager: 7698 - Joining Date: 28-SEP-81 - Salary: 1250 - Commission: 1400 - Department No: 30
Employee No: 7698 - Name: BLAKE - Job: MANAGER - Manager: 7839 - Joining Date: 01-MAY-81 - Salary: 2850 - Commission: - Department No: 30
Employee No: 7782 - Name: CLARK - Job: MANAGER - Manager: 7839 - Joining Date: 09-JUN-81 - Salary: 4450 - Commission: - Department No: 10
Employee No: 7788 - Name: SCOTT - Job: ANALYST - Manager: 7566 - Joining Date: 19-APR-87 - Salary: 3000 - Commission: - Department No: 20
Employee No: 7839 - Name: KING - Job: PRESIDENT - Manager: - Joining Date: 17-NOV-81 - Salary: 7000 - Commission: - Department No: 10
Employee No: 7844 - Name: TURNER - Job: SALESMAN - Manager: 7698 - Joining Date: 08-SEP-81 - Salary: 1500 - Commission: 0 - Department No: 30
Employee No: 7876 - Name: ADAMS - Job: CLERK - Manager: 7788 - Joining Date: 23-MAY-87 - Salary: 1100 - Commission: - Department No: 20
Employee No: 7900 - Name: JAMES - Job: CLERK - Manager: 7698 - Joining Date: 03-DEC-81 - Salary: 950 - Commission: - Department No: 30
Employee No: 7902 - Name: FORD - Job: ANALYST - Manager: 7566 - Joining Date: 03-DEC-81 - Salary: 3000 - Commission: - Department No: 20
Department No: 10 - Name: ACCOUNTING - Location: NEW YORK
Department No: 20 - Name: RESEARCH - Location: DALLAS
Department No: 30 - Name: SALES - Location: CHICAGO
Department No: 40 - Name: LOGISTICS - Location: CHICAGO
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.73
satyaki>Regards.
Satyaki De.
Maybe you are looking for
-
MacBook Pro Retina 13" - Can i upgrade the dual-core i7 to quad-core i7 CPU?
MacBook Pro Retina 13" - Can i upgrade the dual-core i7 to quad-core i7 CPU? (obviously not talking about BTO, but about "self-service" upgrade ...)
-
UPDATING HTML PAGE AFTER UPDATING DATABASE
Hello, I work on servlet, and when I update my database (MS Access) and redirect to a new HTML page, the information are not updated, that's the reason why I have to click on the button of my browser to actualize. So how can I do not to have to click
-
Modal dialog to a JFrame creates problem in windows XP
I have a problem with JDialog(modal) when it is set to a JFrame. It works when the focus is on the dialog. If some other application is selected from the taskbar of the windows XP and selecting back the JFrame, the dialog is not poping up on to the f
-
Several errors while syncing, can't sync ipod anymore
Hello, I just hooked up my ipod touch to my pc (windows 7) and hit the sync button, when itunes started throwing error messages at me. a few of them: unknown (0xE8004006), file specified cannot be found, folder specified instead of file, internal dev
-
Why do I get other iphones contacts from my itunes account on my phone?
Why do I get other iphone contacts from my itunes account on my phone? I get my wife and son's contacts in my iphone. I do not want. I have tried cloud and no cloud that only provides all the contacts or empty file of contacts.