Fetching a single column into array - oracle

I have a table which has column_id of type varchar2. This table may contain 1, 0 or multiple rows. My business logic depends on each case.
I am trying to fetch the column into an array but i am getting weird error (given my limited knowledge of pl/sql)
TYPE t_col_id IS TABLE OF TEST_TABLE.COLUMN_ID%TYPE INDEX BY BINARY_INTEGER;
AR_COL_ID T_COL_ID;
Then i am trying to fetch data into this array
SELECT COLUMN_ID INTO AR_SIM_ID FROM TEST_TABLE WHERE COLUMN_ID = 1;
and i am getting this error
Error(7,3): PL/SQL: SQL Statement ignored
Error(7,25): PLS-00597: expression 'AR_SIM_ID' in the INTO list is of wrong type
Error(7,35): PL/SQL: ORA-00904: : invalid identifier
Is there something that i am missing? My original code would use this array as
BEGIN
-- FETCH ARRAY QUERY
IF (AR_SIM_ID.LENGTH = 0) THEN
-- BUSINESS LOGIC 1
ELSE
-- BUSINESS LOGIC 2
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- BUSINESS LOGIC 3
END;

Instead of using INTO you must use BULK COLLECT INTO:
DECLARE
TYPE t_col_id IS TABLE OF TEST_TABLE.COLUMN_ID%TYPE INDEX BY BINARY_INTEGER;
AR_COL_ID T_COL_ID;
BEGIN
SELECT COLUMN_ID
BULK COLLECT INTO AR_SIM_ID
FROM TEST_TABLE
WHERE COLUMN_ID = 1;
IF AR_SIM_ID.LENGTH = 0 THEN
-- BUSINESS LOGIC 1
ELSE
-- BUSINESS LOGIC 2
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- BUSINESS LOGIC 3
END;
But couldn't you just use COUNT for this scenario?
DECLARE
numRows NUMBER;
BEGIN
SELECT COUNT(COLUMN_ID)
INTO numRows
FROM TEST_TABLE
WHERE COLUMN_ID = 1;
IF numRows = 0 THEN
-- BUSINESS LOGIC 1
ELSE
-- BUSINESS LOGIC 2, 3, etc...
END IF;
END;

a. If you want to get all the rows to plsq table - you need bulk collect
b. If you just want to know how many rows there are in the table you should do:
SELECT count(*) INTO v_count from TEST_TABLE where COLUMN_ID = 1;
c. I don't like using the EXCEPTION scope as part of the program's workflow-
I'd do:
IF v_count = 0 THEN
-- BUSINESS LOGIC 1
ELSIF v_count = 1 THEN
-- BUSINESS LOGIC 2
ELSE
-- BUSINESS LOGIC 3
END IF;

Related

How to access and query objects passed as parameter to a procedure while converting from Oracle to postgresql

I have a procedure in Oracle that I need to convert to Postgresql and need help on it. It paases a collection of objects in a procedure.The procedure then checks if each object is present in a database table or not and if present it gives a message that , that specific element is found/present. if some element that is paassed to the procedure is not present in the table, the procedure just doesnt do anything. I have to write equivalent of that in postgresql. I think the heart of the issue is this statement:
SELECT COUNT (*)
INTO v_cnt
FROM **TABLE (p_cust_tab_type_i)** pt
WHERE pt.ssn = cc.ssn;
In Oracle a collection can be treated as a table and one can query it but I dont know how to do that in postgresql. The code to create the table, add data, create the procedure, call the procedure by passing the collection (3 objects) and output of that is posted below. Can someone suggest how this can be done in postgresql?
Following the oracle related code and details:
--create table
create table temp_n_tab1
(ssn number,
fname varchar2(20),
lname varchar2(20),
items varchar2(100));
/
--add data
insert into temp_n_tab1 values (1,'f1','l1','i1');
--SKIP no. ssn no. 2 intentionally..
insert into temp_n_tab1 values (3,'f3','l3','i3');
insert into temp_n_tab1 values (4,'f4','l4','i4');
insert into temp_n_tab1 values (5,'f5','l5','i5');
insert into temp_n_tab1 values (6,'f6','l6','i6');
commit;
--create procedure
SET SERVEROUTPUT ON
CREATE OR REPLACE PROCEDURE temp_n_proc (
p_cust_tab_type_i IN temp_n_customer_tab_type)
IS
t_cust_tab_type_i temp_n_customer_tab_type;
v_cnt NUMBER;
v_ssn temp_n_tab1.ssn%TYPE;
CURSOR c
IS
SELECT ssn
FROM temp_n_tab1
ORDER BY 1;
BEGIN
--t_cust_tab_type_i := p_cust_tab_type_i();
FOR cc IN c
LOOP
SELECT COUNT (*)
INTO v_cnt
FROM TABLE (p_cust_tab_type_i) pt
WHERE pt.ssn = cc.ssn;
IF (v_cnt > 0)
THEN
DBMS_OUTPUT.put_line (
'The array element '
|| TO_CHAR (cc.ssn)
|| ' exists in the table.');
END IF;
END LOOP;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.PUT_LINE (SQLERRM);
END;
/
--caller proc
SET SERVEROUTPUT ON
declare
array temp_n_customer_tab_type := temp_n_customer_tab_type();
begin
for i in 1 .. 3
loop
array.extend;
array(i) := temp_n_cust_header_type( i, 'name ' || i, 'lname ' || i,i*i*i*i );
end loop;
temp_n_proc( array );
end;
/
caller proc output:
The array element 1 exists in the table.
The array element 3 exists in the table.
When you create a table in Postgres, a type with the same name is also created. So you can simply pass an array of the table's type as a parameter to the function.
Inside the function you can then use unnest() to treat the array like a table.
The following is the closest match to your original Oracle code:
create function temp_n_proc(p_cust_tab_type_i temp_n_tab1[])
returns void
as
$$
declare
l_rec record;
l_msg text;
l_count integer;
BEGIN
for l_rec in select t1.ssn
from temp_n_tab1 t1
loop
select count(*)
into l_count
from unnest(p_cust_tab_type_i) as t
where t.ssn = l_rec.ssn;
if l_count > 0 then
raise notice 'The array element % exist in the table', l_rec.ssn;
end if;
end loop;
END;
$$
language plpgsql;
The row-by-row processing is not a good idea to begin with (neither in Postgres, nor in Oracle). It would be a lot more efficient to get the existing elements in a single query:
create function temp_n_proc(p_cust_tab_type_i temp_n_tab1[])
returns void
as
$$
declare
l_rec record;
l_msg text;
BEGIN
for l_rec in select t1.ssn
from temp_n_tab1 t1
where t1.ssn in (select t.ssn
from unnest(p_cust_tab_type_i) as t)
loop
raise notice 'The array element % exist in the table', l_rec.ssn;
end loop;
return;
END;
$$
language plpgsql;
You can call the function like this:
select temp_n_proc(array[row(1,'f1','l1','i1'),
row(2,'f2','l2','i2'),
row(3,'f3','l3','i3')
]::temp_n_tab1[]);
However a more "Postgres" like and much more efficient way would be to not use PL/pgSQL for this, but create a simple SQL function that returns the messages as a result:
create or replace function temp_n_proc(p_cust_tab_type_i temp_n_tab1[])
returns table(message text)
as
$$
select format('The array element %s exist in the table', t1.ssn)
from temp_n_tab1 t1
where t1.ssn in (select t.ssn
from unnest(p_cust_tab_type_i) as t)
$$
language sql;
This returns the output of the function as a result rather than using the clumsy raise notice.
You can use it like this:
select *
from temp_n_proc(array[row(1,'f1','l1','i1'),
row(2,'f2','l2','i2'),
row(3,'f3','l3','i3')
]::temp_n_tab1[]);

how to look up another field in Oracle Function

Table 1
ID
----------
1
2
3
4
5
Table 2
ID Desc
------------------------------
A1 Apple
A2 Pear
A3 Orange
I am trying to create a Function in Oracle, so that it add the prefix 'A' in Table 1, and after that I want to look up in Table 2 to get the DESC returned. It has to be a function.
Thank you!!!
You may use the following for creation of such a function :
Create or Replace Function Get_Fruit( i_id table2.description%type )
Return table2.description%type Is
o_desc table2.description%type;
Begin
for c in ( select description from table2 where id = 'A'||to_char(i_id) )
loop
o_desc := c.description;
end loop;
return o_desc;
End;
where
no need to include exception handling, because of using cursor
instead of select into clause.
using table_name.col_name%type for declaration of data types for
arguments or variables makes the related data type of the columns
dynamic. i.e. those would be able to depend on the data type of the
related columns.
the reserved keywords such as desc can not be used as column names
of tables, unless they're expressed in double quotes ("desc")
To call that function, the following might be preferred :
SQL> set serveroutput on
SQL> declare
2 i_id pls_integer := 1;
3 o_fruit varchar2(55);
4 begin
5 o_fruit := get_fruit( i_id );
6 dbms_output.put_line( o_fruit );
7 end;
8 /
Apple
PL/SQL procedure successfully completed
I am not sure with your question- Are you trying to achieve something like this:-
CREATE OR REPLACE FUNCTION Replace_Value
(
input_ID IN VARCHAR2
) RETURN VARCHAR2
AS
v_ID varchar(2);
BEGIN
begin
SELECT distinct a.ID into v_id from Table 2 a where a.ID in (select 'A'||b.id from table1 b where b.id=input_ID);
exception
when others then
dbms_output.put_line(sqlcode);
end;
RETURN v_id;
END Replace_Value;
Are you trying for something like this?
CREATE OR replace FUNCTION replace_value (table_name IN VARCHAR2,
input_id IN INTEGER)
RETURN VARCHAR2
AS
v_desc VARCHAR(20);
BEGIN
SELECT descr
INTO v_desc
FROM table2
WHERE id = 'A' || input_id
AND ROWNUM = 1; -- only needed if there are multiple rows for each id.
RETURN v_desc;
END replace_value;
You may also add an exception handling for NO_DATA_FOUND or INVALID_NUMBER

Oracle trigger on 2 tables : no data found

Please help,I'm trying to allow/ban insertion into a table called 'vol' that has a foreign key (id_av) from another table 'avion'
allow insertion : if avion.etat = 'disponible'
ban it if it is different from 'disponible'
for that I have created this trigger :
create or replace trigger t
before insert on vol
declare etat VARCHAR(10);
BEGIN
select avion.etat into etat
from vol,etat
where avion.id_av = vol.id_av;
IF(etat <> 'disponible')
THEN
RAISE_APPLICATION_ERROR( -20001, 'insertion imposible');
END IF;
END t;
/
the result : the trigger is created but when I tryed to insert in vol it shows me these errors
I've tryed also with JOIN..ON but didn't really worked out
Perhaps something like this?
create or replace trigger t
before insert on vol
for each row --> edited
declare
etat VARCHAR(10);
BEGIN
-- MAX will prevent NO-DATA-FOUND
-- Also, you don't need join - use :NEW.ID_AV which is equal to currently inserted value
select max(avion.etat)
into etat
from avion
where avion.id_av = :new.id_av;
-- NVL because - if SELECT returns, nothing, you can't compare NULL with 'disponible'
IF nvl(etat, 'x') <> 'disponible'
THEN
RAISE_APPLICATION_ERROR( -20001, 'insertion imposible');
END IF;
END t;
/

Oracle Insert Missing Records

I have written a package for building a reporting table. The simplified code for the function I am testing follows:
function do_build return integer is
V_RESULT PLS_INTEGER := 0;
cursor all_entities is
select e.id_number
from entity e
;
BEGIN
c_count := 0; -- this variable is declared at the package level outside of this function
for rec in all_entities LOOP
BEGIN
insert into reporting (
select *
from table(get_report_data(rec.id_number))
);
c_count := c_count + 1;
if MOD(c_count, 1000) = 0 Then
-- record status to table
commit;
end if;
EXCEPTION
WHEN OTHERS THEN
-- record exception to table
END;
END LOOP;
return V_RESULT;
END;
A little background: get_report_data is a function that returns a dataset with all of the input entity's reporting data.
About 1000 records out of 1 million are missing from the "reporting" table when the build completes. No exceptions are thrown and other than the missing records, everything appears to have been successful (function returns 0 to caller).
When I run the get_report_data for the entity records that do not have their reporting data recorded, the records show up fine. In fact, I can do an adhoc "insert into reporting (select * from table(get_reporting_data(missing_id))" and the information will be inserted.
Why would these records be skipped/fail to insert? Should I be looping a different way? Any better way to do it?
You're only committing every 1000 rows. You're not committing the last batch. Add a commit after the END LOOP;
BEGIN
c_count := 0; -- this variable is declared at the package level outside of this function
for rec in all_entities LOOP
BEGIN
insert into reporting (
select *
from table(get_report_data(rec.id_number))
);
c_count := c_count + 1;
if MOD(c_count, 1000) = 0 Then
-- record status to table
commit;
end if;
EXCEPTION
WHEN OTHERS THEN
-- record exception to table
END;
END LOOP;
COMMIT; -- <-- Add this commit to pick up last few records
return V_RESULT;
END;
Can this be a concurrency issue? If the records are committed in the ENTITY table while you loop is running they won't be processed.
BTW: Using WHEN OTHERS in this way is asking for trouble.
BTW2: Why not simply use:
INSERT INTO reporting
SELECT rep.*
FROM entity e
CROSS JOIN table(get_report_data(e.id_number)) rep;

Reasonable SELECT ... INTO Oracle solution for case of multiple OR no rows

I just want to SELECT values into variables from inside a procedure.
SELECT blah1,blah2 INTO var1_,var2_
FROM ...
Sometimes a large complex query will have no rows sometimes it will have more than one -- both cases lead to exceptions. I would love to replace the exception behavior with implicit behavior similiar to:
No rows = no value change, Multiple rows = use last
I can constrain the result set easily enough for the "multiple rows" case but "no rows" is much more difficult for situations where you can't use an aggregate function in the SELECT.
Is there any special workarounds or suggestions? Looking to avoid significantly rewriting queries or executing twice to get a rowcount before executing SELECT INTO.
Whats wrong with using an exception block?
create or replace
procedure p(v_job VARCHAR2) IS
v_ename VARCHAR2(255);
begin
select ename into v_ename
from (
select ename
from scott.emp
where job = v_job
order by v_ename desc )
where rownum = 1;
DBMS_OUTPUT.PUT_LINE('Found Rows Logic Here -> Found ' || v_ename);
EXCEPTION WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No Rows found logic here');
end;
SQL> begin
p('FOO');
p('CLERK');
end; 2 3 4
5 /
No Rows found logic here
Found Rows Logic Here -> Found SMITH
PL/SQL procedure successfully completed.
SQL>
You could use a for loop. A for loop would do nothing for no rows returned and would be applied to every row returned if there where multiples. You could adjust your select so that it only returns the last row.
begin
for ARow in (select *
from tableA ta
Where ta.value = ???) loop
-- do something to ARow
end loop;
end;

Resources