I have a type called sell_type defined as
CREATE OR REPLACE TYPE sell_type AS OBJECT (
dname VARCHAR (50),
car_model VARCHAR(20),
make VARCHAR (20),
price NUMBER (10,2),
MEMBER FUNCTION total_sales RETURN NUMBER
);
/
Body:
CREATE OR REPLACE TYPE BODY sell_type AS
MEMBER FUNCTION total_sales RETURN NUMBER IS
BEGIN
RETURN SELF.price;
END total_sales;
END;
/
And an object table
CREATE TABLE sell of Sell_Type;
/
I want to get the total sales for a given seller with something like:
select s.total_sales() from sell s
where s.dname = 'John Doe';
But what I get is a separate list of prices of all the sales of that given seller, rather than the total of those prices.
I know that I have to fix my type body somehow. I tried to use the SUM() inside the return but that didn't work. Can someone please help?
Summing is an aggregation, a set function. A Type is a single thing; it is not possible for a Type instance to execute an aggregation across all the instances of its peers.
If you want to do such a thing you would need to declare a new type, with a signature like this:
CREATE OR REPLACE TYPE sell_set AS OBJECT (
sell_items sell_type,
MEMBER FUNCTION total_sales (p_seller varchar2) RETURN NUMBER
);
/
Writing the body for this type is left as an exercise for the reader ;-)
Note that Oracle SQL and PL/SQL do work with OO concepts but in a clunky fashion. It's fine to explore the syntax for educational purposes, if only to learn its limitations. But there are a very narrow set of use cases in real life. A relational data model is the far superior way of storing data.
This body will do the trick. But it will return the same value for each row on the sell table. Therefore, you have to use 'group by' or 'max()' if you want to see just one row of result.
CREATE OR REPLACE
TYPE BODY SELL_TYPE AS
MEMBER FUNCTION total_sales (p_seller varchar2) RETURN NUMBER IS
total_price NUMBER;
BEGIN
SELECT sum(s.price) INTO total_price FROM sell s where s.dname = p_seller;
RETURN total_price;
END total_sales;
END;
/
select query will look like this.
select s.total_sales('John')
from sell s GROUP BY s.total_sales('John');
Related
Why to I asked this question?
I have a table which as key that have a lot of field. Every time, I'm making a jointure, I miss a field. Therefore I have defined a pipelined function that take the key as an argument so that I am sure that I get only one element when I'm doing a jointure.
But the query take more time now. The table a has an index on some fields but not the table type used by pipelined function. I would like to know if it is possible to created a index on some fields of the table%rowtype
code:
create table a ( a1 integer);
create package p_a
as
type t_a iS TABLE of a%ROWTYPE;
function f(i_a1 integer) return t_a pipelined;
end;
CREATE PACKAGE BODY p_a
AS
CURSOR c_A (i_a1 INTEGER)
RETURN a%ROWTYPE
IS
SELECT t.*
FROM a t
WHERE t.a1 = i_a1;
FUNCTION f (i_a1 INTEGER)
RETURN t_a
PIPELINED
IS
BEGIN
FOR c IN c_a (i_a1)
LOOP
PIPE ROW (c);
END LOOP;
END;
END;
with b as( select 1 b1 from dual) select * from b cross apply (table(p_a.f(b.b1)));
the question
I've tried to index the type table by a field of a table like this
create table a ( a1 integer);
create package p_a2
as
type t_a iS TABLE of a%ROWTYPE index by a.a1%type;
function f(i_a1 integer) return t_a pipelined;
end;
PLS-00315: Implementation restriction: unsupported table index type
Is what I want to do possible. If not how to solve the performance problems mentioned in the introduction?
code
A TYPE is NOT a table and cannot be indexed.
When you do:
create package p_a
as
type t_a iS TABLE of a%ROWTYPE;
end;
/
You are defining a type and the type is a collection data type; an instance of that type is NOT a physical table and but is more like an in-memory array.
When you create a PIPELINED function:
function f(i_a1 integer) return t_a pipelined;
It does NOT return a table; it returns the collection data type.
When you do:
type t_a iS TABLE of a%ROWTYPE index by a.a1%type;
You are NOT creating an index on a table; you are changing to a different collection data type that is an associative array (like a JavaScript object or a Python dictionary) that stores key-value pairs.
An associative array is a PL/SQL data type and (with limited exceptions in later versions for insert, update and delete statements) cannot be used in SQL statements.
When you do:
SELECT * FROM TABLE(SYS.ODCIVARCHAR2LIST('a', 'b', 'c'));
or:
SELECT * FROM TABLE(p_a.f(1));
Then you are passing a collection data type to an SQL statement and the table collection expression TABLE() is treating the collection expression as if it was a table. It is still NOT a table.
If you want to use an index on the table then use the table (without a cursor or a pipeline function):
WITH b (b1) AS (
SELECT 1 FROM DUAL
)
SELECT *
FROM b
CROSS APPLY (
SELECT a.*
FROM a
WHERE a.a1 = b.b1;
);
I think the first line of your question says it all: "key that have a lot of field". If I understand correctly, the table has a primary key that consists of a large number of columns and because of that writing queries becomes a challenge.
It sounds like you're trying to do something pretty complex that should not be an issue at all.
Take a step back and ask yourself - does this need to be the primary key of the table ? Or can you use a surrogate key (identity column, sequence), use that as the primary key and just create a unique index on the set of field that currently make up the primary key. It will (1) simplify your data model and (2) make writing the queries a lot easier.
Thank you for reply guys. I kind of solved my problem.
I used to try to update data with ref cursor in dynamic SQL using "where current of" but I now know that won't work.
Then I tried to use %rowtype to store both 'id' and 'clob' in one variable for future updating but turns out weak ref cursor can't use that type binding either.
After that I tried to use record as return of an ref cursor and that doesn't work on weak cursor either.
On the end, I created another cursor to retrieve 'id' separately along with cursor to retrieve 'clob' on the same time then update table with that id.
I'm now working on a Oracle data cleaning task and have a requirement like below:
There are 38 tables(maybe more in the future) and every table has one or multiple column which type is Clob. I need to find different keyword in those columns and according to a logic return binary label of the column and store it in a new column.
For example, there is a table 'myTable1' which has 2 Clob columns 'clob1' and 'clob2'. I'd like to find keyword 'sky' from those columns and store '0'(if not found) or '1'(if found) in two new columns 'clob1Sky','clob2Sky'.
I know if I could write it on a static way which will provide higher efficiency but I have to modify it for those very similar tasks every time. I want save some time on this so I'm trying to write it in a reusable way and not binding to certain table.
But I met some problem when writing the program. My program is like below:
create or replace PACKAGE body LABELTARGETKEYWORD
as
/**
#param varcher tableName: the name of table I want to work on
#param varchar colName: the name of clob column
#param varchar targetWord: the word I want to find in the column
#param varchar newColName: the name of new column which store label of clob
*/
PROCEDURE mainProc(tableName varchar, colName varchar,targetWord varchar,newColName varchar2)
as
type c_RecordCur is ref cursor;
c_sRecordCur c_recordCur;
/*other variables*/
begin
/*(1) check whether column of newColName exist
(2) if not, alter add table of newColName
(3) open cursor for retrieving clob
(4) loop cursor
(5) update set the value in newColName accroding to func labelword return
(6) close cursor and commit*/
end mainProc;
function labelWord(sRecord VARCHAR2,targetWord varchar2) return boolean...
function ifColExist(tableName varchar2,newColName varchar2) return boolean...
END LABELTARGETKEYWORD;
Most DML and DDL are written in dynamic sql way.
The problem is when I write the (5) part, I notice 'Where current of' clause can not be used in a ref cursor or dynamic sql statement. So I have to change the plan.
I tried to use a record(rowid,label) to store result and alter the table later.(the table only be used by two people in my group, so there won't be problem of lock and data changes). But I find because I'm trying to use dynamic sql so actually I have to define ref cursor with return of certain %rowtype and basically all other variables, %type in dynamic sql statement. Which makes me feel my method has something wrong.
My question are:
If there a way to define %type in dynamic sql? Binding type to variable in dynamic SQL?
Could anybody give me a hint how to write that (5) part in dynamic SQL?
Should not I design my program like that?
Is it not the way how to use dynamic SQL or PLSQL?
I'm very new to PL/SQL. Thank you very much.
According to Tom Kyte's advice, to do it in one statement if it can be done in one statement, I'd try to use a single UPDATE statement first:
CREATE TABLE mytable1 (id NUMBER, clob1 CLOB,
clob2 CLOB, clob1sky NUMBER, clob2sky NUMBER )
LOB(clob1, clob2) STORE AS SECUREFILE (ENABLE STORAGE IN ROW);
INSERT INTO mytable1(id, clob1, clob2)
SELECT object_id, object_name, object_type FROM all_objects
WHERE rownum <= 10000;
CREATE OR REPLACE
PROCEDURE mainProc(tableName VARCHAR2, colName VARCHAR2, targetWord VARCHAR2, newColName VARCHAR2)
IS
stmt VARCHAR2(30000);
BEGIN
stmt := 'UPDATE '||tableName||' SET '||newColName||'=1 '||
'WHERE DBMS_LOB.INSTR('||colName||','''||targetWord||''')>1';
dbms_output.put_line(stmt);
EXECUTE IMMEDIATE stmt;
END mainProc;
/
So, calling it with mainProc('MYTABLE1', 'CLOB1', 'TAB', 'CLOB1SKY'); fires the statement
UPDATE MYTABLE1 SET CLOB1SKY=1 WHERE DBMS_LOB.INSTR(CLOB1,'TAB')>1
which seems to do the trick:
SELECT * FROM mytable1 WHERE clob1sky=1;
id clob1 clob2 clob1sky clob2skiy
33 I_TAB1 INDEX 1
88 NTAB$ TABLE 1
89 I_NTAB1 INDEX 1
90 I_NTAB2 INDEX 1
...
I am not sure with your question-
If this job is suppose to run on daily or hourly basis ,running query through it will be very costly. One thing you can do - put all your clob data in a file and save it in your server(i guess it must be linux). then you can create a shell script and schedule a job to run gerp command and fetch your required value and "if found then update your table".
I think you should approaches problem another way:
1. Find all columns that you need:
CURSOR k_clobs
select table_name, column_name from dba_tab_cols where data_type in ('CLOB','NCLOB');
Or 2 cursor(you can build you query if you have more than 1 CLOB per table:
CURSOR k_clobs_table
select DISTINCT table_name from dba_tab_cols where data_type in ('CLOB','NCLOB');
CURSOR k_clobs_columns(table_namee varchar(255)) is
select column_name from dba_tab_cols where data_type in ('CLOB','NCLOB') and table_name = table_namee;
Now you are 100% that column you are checking is clob, so you don't have to worry about data type ;)
I'm not sure what you want achieve, but i hope it may help you.
I need to get the year from a date in all of the records in an Oracle database. The following is my attempt:
CREATE or replace TYPE BODY student_t AS MEMBER FUNCTION getYear RETURN NUMBER IS
yearDOB NUMBER;
BEGIN
SELECT EXTRACT(YEAR FROM s.dob) INTO yearDOB
from student s;
return yearDOB;
END;END;/
But that will not work when the table has more than 1 record.
How I can fix the issue?
When you do select into rdbms thinks that only one value will be returned, or that your variable will be an array. You cannot set a NUMBER variable to an array of objects.
I'm trying to display at oracle apex IR query, a biggest date from 3 different tables, using greatest function to choice the biggest. For that, created two varchar2 type functions.
One of them return the date converted to char, of a selected table like this:
create or replace FUNCTION RETURN_DATES (key in number, parameter in NUMBER)
RETURN VARCHAR2 IS
...
BEGIN
case parameter
when 1 then
select distinct MAX(mydate) into seal from table1 v WHERE v.num_contract = number_contract;
return NVL(TO_CHAR(TO_DATE (seal),'mm/dd/yyyy'),'01/01/1980')
when 2 then
select... from table2 x WHERE...
...
END;
The second function calls that one using a greatest function between the parameter calls, which refers to case statement:
create or replace FUNCTION RETURN_BIGGEST_DATE(key in number) return VARCHAR2 IS
...
BEGIN
select greatest (RETURN_DATES(key,1),RETURN_DATES(key,2),RETURN_DATES(key,3)) into greatest_date from dual;
return greatest_date;
...
END;
When i call it on sql commands it's works fine, but at an interactive report its fails, returning the ORA-1843, using the quite same query.
Could anyone help?
Simply modifying the RETURN_DATES returning DATE
and the seal variable, of date type, without conversions, works fine at apex IR!
I noticed when a date column is relayed on ir query, there are an extra parameter on Column filter, named Date Ranges. It was the two way traffic to start simulations and change the returning type of the that function.
No more changes was required:
create or replace FUNCTION RETURN_DATES (key in number, parameter in NUMBER)
RETURN DATE IS
...
select distinct MAX(mydate) into seal from table1 v WHERE v.num_contract = number_contract;
return NVL(seal),'01/01/1980')
I have a sample query like below:
INSERT INTO my_gtt_1 (fname, lname) (select fname, lname from users)
In my effort to getting rid of temporary tables I created a package:
create or replace package fname_lname AS
Type fname_lname_rec_type is record (
fname varchar(10),
lname varchar(10)
);
fname_lname_rec fname_lname_rec_type
Type fname_lname_tbl_type is table of fname_lname_rec_type;
function fname_lname_func
(
v_fnam in varchar2,
v_lname in varchar2
)return fname_lname_tbl_type pipelined;
being new to oracle...creating this package took a long time. but now I can not figure out how to get rid of the my_gtt_1
how can i say...
INSERT INTO <newly created package> (select fnma, name from users)
You need to call the pipelined function using the TABLE() syntax:
select *
from table (select fname_lname.fname_lname_func(fnma, name)
from users
where user_id = 123 )
/
Note that the sub-query on USERS must return a single row from that table.
You don't select into packages. You could declare a variable of your table type and bulk collect into that, if you intend to use it in code. I also question your need for a pipelined function. If you're just using the global-temporary table as a springboard for another query, you could probably just use a WITH clause instead. We need a better idea of the bigger picture to recommend a particular technique. Global temporary tables are not inherently bad, either.