Create Type based on an exiting Table - oracle

As the title said : I want to create a type in oracle based on an existing Table.
I did as follow :
create or replace type MY_NEW_TYPE as object( one_row EXISTING_TABLE%rowtype);
The Aim is to be able to use this into a function which will return a table containing sample row of the table EXISTING_TABLE :
create or replace function OUTPUT_FCT() return MY_NEW_TYPE AS
...

If you only need to create a function that returns a row from your table, you could try something like the following, without creating types.
setup:
create table EXISTING_TABLE( a number, b varchar2(100));
insert into EXISTING_TABLE values (1, 'one');
function:
create or replace function OUTPUT_FCT return EXISTING_TABLE%rowtype AS
retVal EXISTING_TABLE%rowType;
begin
select *
into retVal
from EXISTING_TABLE
where rownum = 1;
--
return retVal;
end;
function call
SQL> begin
2 dbms_output.put_line(OUTPUT_FCT().a);
3 dbms_output.put_line(OUTPUT_FCT().b);
4 end;
5 /
1
one
However, I would not recommend such an approach, because things like select * can be really dangerous; I would much prefer defining a type with the fields I need, and then explicitly query my table for the needed columns.

No, you can't do that, you'll get a compilation error:
create or replace type my_new_type as object(one_row t42%rowtype);
/
Type MY_NEW_TYPE compiled
Errors: check compiler log
show errors
Errors for TYPE STACKOVERFLOW.MY_NEW_TYPE:
LINE/COL ERROR
-------- -----------------------------------------------------------------------
0/0 PL/SQL: Compilation unit analysis terminated
1/36 PLS-00329: schema-level type has illegal reference to MYSCHEMA.T42
You will need to specify each field in the object type, and you will have to specify the data types manually too - you can't use table.column%type either.
You could create the type dynamically based on column and data type information from the data dictionary, but as this will (hopefully) be a one-off task and not something you'd do at runtime, that doesn't really seem worth it.
You can create a PL/SQL table type based on your table's rowtype, but you would only be able to call a function returning that from PL/SQL, not from plain SQL - so you couldn't use it in a table collection expression for example. If you were only returning a single sample row you could return a record rather than a table, but the same applies. You can also have a function that returns a ref cursor which could match the table's structure, but you wouldn't be able to treat that as a table either.
Read more about object type creation in the documentation. Specifically the attribute and datatype sections.

Related

Is it possible to create a pipeline table function returning a table of a record of record

create package pa as
type ra1 is record (
one integer,
two integer
);
type ra2 is record (
r1 ra1,
three integer,
fore integer
);
type ta1 is table of ra1;
type ta2 is table of ra2;
function pa1 return ta1 pipelined;
function pa2 return ta2 pipelined; --pipelined functions must have a supported collection return type
end;
It doesn't seem possible too create a table of a record.
I explain why I want to do that. Perhaps you a another solution.
I have a big query with a "with statement" with n part.
Some parts are reused in others queries. I could rewrite these parts as views. But views doesn't accept parameters and the what is in the where block is long.
I want to define each step like that:
function f_stepn(arg integer) return t_stepn
is
for c in (
select r_stepnMinus1(stepnMinus1.* ) , o.f1,o.f2
from
f_stepnMinus1(arg) stepnMinus1 join othertable o on .....
) loop
pipe row(c)
end loop
In the end I do this this select :
select skip(t.r_stepMinus1.r_stepMinus1.*), skip(t.r_stepMinus1.*), skip(t.*))
where skip in a polymophich function that delete the fields that are records.
P.S.
the function in example in simplified. I can't do that : select r_stepnMinus1(stepnMinus1.* )
I know that I could rewrite the whole definition of r1 inside r2 but I don't want to write 2 times the same thing
A Record is a PL/SQL-only data type and CANNOT be used in SQL statements.
A pipelined function is designed to be used in SQL statements and MUST return a collection that can be used in SQL.
When you return a collection of records, Oracle will implicitly create an OBJECT data-type that reflects the attributes of the record and will return a collection of this object rather than the record (and a collection of object can be used in SQL statements).
However, an OBJECT cannot contain an attribute with a RECORD data type. So when you try to create pipelined function returning a collection of records with a nested record attribute then Oracle cannot implicitly create an Object that reflects the record as the nested record is incompatible and so creating a PIPELINED function will fail.
Either:
Use OBJECT data types created in the SQL scope (instead of records); or
Do not nest records inside records.

Oracle substitutes asterisk to all columns in a view

I've just bumped into the case when I have a view that has an asterisk reference to one of underlying tables. After compilation this asterisk sign is being exchanged to all column list and I don't want it to happen. See example below:
create or replace view test_view_cols as
select 1 f_1,
2 f_2,
3 f_3
from dual
/
create or replace view test_interface as
select d.*
from test_view_cols d
/
create or replace view test_view_cols as
select 1 f_1,
2 f_2,
3 f_3,
4 f_4,
5 f_5
from dual
/
select count(*) col_cnt -- returns 3 and not 5
from user_tab_cols s
where s.TABLE_NAME = 'TEST_INTERFACE';
select s.text
from user_views s
where s.VIEW_NAME = 'TEST_INTERFACE'
/* returns
select d."F_1",d."F_2",d."F_3"
from test_view_cols d
*/
But I don't want asterisk to be exchanged and I want have all the columns from test_view_cols in test_interface view.
Can I somehow force Oracle to keep an asterisk in an underlying query?
Oracle 11gR2
No.
You can't define a view that returns a variable number of columns depending on the changing definition of an underlying object (whether that underlying object is a table or a view). You could define a stored procedure that has an OUT parameter of type SYS_REFCURSOR that would return whatever columns are in the underlying object. You should also be able to define a pipelined table function that returns a different number of columns based on the underlying object-- that does get much easier in more recent versions, though.
You need after each change of the underlining object simple re-create the interface view as well.
create or replace view test_interface as
select d.*
from test_view_cols d
Than is the view definition again adjusted to the new object. The start * is expanded in the view compilation not in the query.
What you can use starting with Oracle 19c (or better 21c) is SQL Macro
The TABLE SQL Macros are defined similar as function, but they return text of the subquery that will be used.
You can define the SQL Macro that returns all columns of the base view as follows
create or replace function test_interface
return varchar2 SQL_MACRO
is
begin
return q'[
select * from test_view_cols]';
end;
/
You use the SQL Macro in the FROM clause
select * from test_interface();
This query return on the first run the three columns of the underlining view.
After the view is modified, you get back the five columns. Why?
The SQL Macro is activated only at parse time, so you should take some care, that you do not get the old columns state from the cached cursor.
But this is not a problem, because by changing the underlining view your cursor is automatically invalidated and must be reparsed with the new definition.
But SQL Macros are even more powerful. You can define one universal interface SQL Macro that can be applied on all your tested objects by passing the name of the underlining view or table as a parameter:
create function my_interface (t DBMS_TF.Table_t)
return varchar2 SQL_MACRO(TABLE)
is
begin
return q'[
select * from t]';
end;
/
In the query you than pass the name of the tested view
select * from my_interface(test_view_cols);
More information and examples of SQL Macros can be found here and there.

How to use sequence in a function in PLSQL?

In my schema, I have a reference number column in my settlement
table with a null value of varchar2 type, that I want to update it continuously.
Then I've created a sequence called ref_seq_num using a built-in function.
I want to use it (ref_seq_num) within my function get_ref_num to update the sequence ref. number to my settlement table,
which the return type also is varchar2 and I have a function like below
CREATE OR REPLACE FUNCTION get_ref_num RETURN settlement.ref_nr %TYPE IS
v_ref_seq settlement.ref_nr%TYPE;
BEGIN
v_ref_seq := to_char(sysdate, 'YYYYMMDD')||LPAD(ref_seq_num.nextval, 8,'0');
RETURN v_ref_seq;
END get_ref_num;
However, I bum into this error message 1/55 PLS-00302: component 'ref_nr' must be declared. I also tried changing the data type to varchar2 and error message is PLS-00215: String length constraints must be in range (1 .. 32767) How can I fix it?
According to your code, it seems that there's a table whose name is SETTLEMENT, but it doesn't contain the REF_NR column.
The following example shows how to do that:
SQL> create sequence ref_seq_num;
Sequence created.
A table that does contain the REF_NR column (which is then used in the function):
SQL> create table settlement (ref_nr varchar2(20));
Table created.
Your code, unmodified:
SQL> CREATE OR REPLACE FUNCTION get_ref_num RETURN settlement.ref_nr %TYPE IS
2 v_ref_seq settlement.ref_nr%TYPE;
3 BEGIN
4 v_ref_seq := to_char(sysdate, 'YYYYMMDD')||LPAD(ref_seq_num.nextval, 8,'0');
5 RETURN v_ref_seq;
6 END get_ref_num;
7 /
Function created.
Testing:
SQL> select get_ref_num from dual;
GET_REF_NUM
--------------------------------------------------------------------------------
2019050400000001
SQL>
If you have a column called ref_nr within settlement table, you code must work properly. I think the problem in the second case raises due to missing data precision part ( should be such as varchar2(16) ) for defining the variable as v_ref_seq varchar2. I would prefer using a numeric type such as number or int to hold the values for ref_nr, since they are all numeric, and this data type protects the data remain as numeric. Whenever you need to query you may use to_char function preventing exponential display( select to_char(ref_nr) from settlement ).
Moreover, if you use Oracle 12c version, you don't need to create such an extra function, just alter your table so that being sequence as your default for the column :
alter table settlement
modify ref_nr default to_char(sysdate, 'yyyymmdd')||lpad(ref_seq_num.nextval, 8,'0');

PL/SQL reusable dynamic sql program for same type of task but different table and column

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.

plsql table type with index of is complaining

Pl/SQL:
Intent: My intent was to access employee tuple object defied as cursor below by using key as the employee_id.
Problem: I created a cursor - *l_employees_cur* and want to create type table as below type *l_employees_t*, as below but the compiler is complaining saying that PLS-00315 implementation restriction unsupported table index type.
CURSOR l_employees_cur
IS
SELECT employee_id,manager_id,first_name,last_name FROM employees;
type l_employees_t
IS
TABLE OF l_employees_cur%rowtype INDEX BY employees.employee_id%TYPE;
The definition of employees.employee_id is:
EMPLOYEE_ID NUMBER(6) NOT NULL
why can't I do this ? or Am I doint something wrong.
From the Oracle Documenation:
Associative Arrays
An associative array (formerly called PL/SQL table or index-by table) is a set of key-value pairs. Each key is a unique index, used to locate the associated value with the syntax variable_name(index).
The data type of index can be either a string type or PLS_INTEGER. Indexes are stored in sort order, not creation order. For string types, sort order is determined by the initialization parameters NLS_SORT and NLS_COMP.
I think that your mistake is the declaration of the plsql table.
Why don't you try the next one:
type l_employees_t
IS
TABLE OF l_employees_cur%rowtype INDEX BY pls_integer;
I also have a question for you:
What is the meaning of EMPLOYEE_ID NOT NULL NUMBER(6) in your code above?
Greetings
Carlos
Storing and Retreiving SQL Query Output in a PL/SQL Collection
The example in the OP looks a lot like Oracle's new sample HR data schema. (For those old-timers who know, the successor to the SCOTT-TIGER data model). This solution was developed on an Oracle 11g R2 instance.
The Demo Table Design - EMP
Demonstration Objectives
This example will show how to create a PL/SQL collection from an object TYPE definition. The complex data type is derived from the following cursor definition:
CURSOR l_employees_cur IS
SELECT emp.empno as EMPLOYEE_ID, emp.mgr as MANAGER_ID, emp.ename as LAST_NAME
FROM EMP;
After loading the cursor contents into an index-by collection variable, the last half of the stored procedure contains an optional step which loops back through the collection and displays the data either through DBMS_OUTPUT or an INSERT DML operation on another table.
Stored Procedure Example Source Code
This is the stored procedure used to query the demonstration table, EMP.
create or replace procedure zz_proc_employee is
CURSOR l_employees_cur IS
SELECT emp.empno as EMPLOYEE_ID, emp.mgr as MANAGER_ID, emp.ename as LAST_NAME
FROM EMP;
TYPE employees_tbl_type IS TABLE OF l_employees_cur%ROWTYPE INDEX BY PLS_INTEGER;
employees_rec_var l_employees_cur%ROWTYPE;
employees_tbl_var employees_tbl_type;
v_output_string varchar2(80);
c_output_template constant varchar2(80):=
'Employee: <<EMP>>; Manager: <<MGR>>; Employee Name: <<ENAME>>';
idx integer;
outloop integer;
BEGIN
idx:= 1;
OPEN l_employees_cur;
FETCH l_employees_cur INTO employees_rec_var;
WHILE l_employees_cur%FOUND LOOP
employees_tbl_var(idx):= employees_rec_var;
FETCH l_employees_cur INTO employees_rec_var;
idx:= idx + 1;
END LOOP;
CLOSE l_employees_cur;
-- OPTIONAL (below) Output Loop for Displaying The Array Contents
-- At this point, employees_tbl_var can be handed off or returned
-- for additional processing.
FOR outloop IN 1 .. idx LOOP
-- Build the output string:
v_output_string:= replace(c_output_template, '<<EMP>>',
to_char(employees_tbl_var(outloop).employee_id));
v_output_string:= replace(v_output_string, '<<MGR>>',
to_char(employees_tbl_var(outloop).manager_id));
v_output_string:= replace(v_output_string, '<<ENAME>>',
employees_tbl_var(outloop).last_name);
-- dbms_output.put_line(v_output_string);
INSERT INTO zz_output(output_string, output_ts)
VALUES(v_output_string, sysdate);
COMMIT;
END LOOP;
END zz_proc_employee;
​
I commented out the dbms_output call due to problems with the configuration of my server beyond my control. The alternate insert command to a output table is a quick way of visually verifying that the data from the EMP table found its way successfully into the declared collection variable.
Results and Discussion of the Solution
Here is my output after calling the procedure and querying my output table:
While the actual purpose behind the access to this table isn't clear in the very terse detail of the OP, I assumed that the first approach was an attempt to understand the use of collections and custom data types for efficient data extraction and handling from structures such as PL/SQL cursors.
The portion of this example procedure is very reusable, and the initial steps represent a working way of making and loading PL/SQL collections. If you notice, even if your own version of this EMP table is different, the only place that requires redefinition is the cursor itself.
Working with types, arrays, nested tables and other collection types will actually simplify work in the long run because of their dynamic nature.

Resources