Oracle function within a transaction - oracle

I am inserting a record within a transaction and then later I am retrieving the same record via an Oracle function. The oracle function is returning no records. My DBA told me that Oracle functions do not operate inside a transaction. How do I get around this?
Example:
Begin transaction using the oracle provider
Execute some SQL:
INSERT OWNER
(FIRST_NAME, LAST_NAME)
VALUES
('JOHN', 'SMITH')
Get the record back within the transaction from a function (71 is an example ID):
select * from table (GET_OWNER_DETAILS_FNC (71) )
Here is the Oracle Function:
CREATE OR REPLACE FUNCTION "AROH"."GET_OWNER_DETAILS_FNC" (p_owner_information_oid in aroh_owner_information.owner_information_oid%type )
return OWNER_DETAILS_TABLE_TYPE_FNC
IS
PRAGMA AUTONOMOUS_TRANSACTION;
v_owner_details_set OWNER_DETAILS_TABLE_TYPE_FNC := OWNER_DETAILS_TABLE_TYPE_FNC();
CURSOR c_owner_dtls IS
select oi.owner_information_oid,
oi.first_name,
oi.last_name,
oi.company_name,
oi.license_information,
oi.company_ind,
oi.middle_initial,
oi.title_type_oid,
oi.suffix,
oi.status_type_code,
oi.primary_phone,
oi.secondary_phone,
oi.secondary_phone_type_code,
oi.primary_phone_type_code,
oi.email_address,
oi.comments,
oi.primary_phone_extension,
oi.secondary_phone_extension,
poa.owner_address_oid as primaryaddressid,
poa.address_type_code as primaryaddresscode,
poa.address1 as primaryaddress1,
poa.address2 as primaryaddress2,
poa.city as primarycity,
poa.state as primarystate,
poa.postal_code as primaryzip,
poa.current_ind as primarycurrent,
soa.owner_address_oid as secondaryaddressid,
soa.address_type_code as secondaryaddresscode,
soa.address1 as secondaryaddress1,
soa.address2 as secondaryaddress2,
soa.city as secondarycity,
soa.state as secondarystate,
soa.postal_code as secondaryzip,
soa.current_ind as secondarycurrent,
( select
( select oa2.owner_information_oid
from aroh_owner_aircraft_rlshp oa2
where upper(primary_owner) like '%PRIMARY%'
and oa2.aircraft_oid = oa1.aircraft_oid
and rownum = 1) as prim_owner_oid
from aroh_owner_aircraft_rlshp oa1
where oa1.owner_information_oid = p_owner_information_oid
and rownum = 1
) as primary_owner_oid,
( select
case when (upper(primary_owner) like '%PRIMARY%')
then 'Y'
else 'N' end as isprimary
from aroh_owner_aircraft_rlshp
where owner_information_oid = p_owner_information_oid
and rownum = 1
) as is_primary
from aroh_owner_information oi
inner join (select *
from aroh_owner_address
where upper(current_ind) = 'Y'
and address_type_code = 'OPRIM') poa
on oi.owner_information_oid = poa.owner_information_oid
left outer join (select *
from aroh_owner_address
where upper(current_ind) = 'Y'
and address_type_code = 'OSEC') soa
on oi.owner_information_oid = soa.owner_information_oid
where oi.owner_information_oid = p_owner_information_oid;
begin
For main_row in c_owner_dtls
loop
v_owner_details_set.EXTEND;
v_owner_details_set(v_owner_details_set.LAST) := OWNER_DETAILS_TYPE (main_row.owner_information_oid , main_row.first_name , main_row.last_name , main_row.company_name
, main_row.license_information , main_row.company_ind , main_row.middle_initial , main_row.title_type_oid , main_row.suffix , main_row.status_type_code , main_row.primary_phone
, main_row.secondary_phone , main_row.secondary_phone_type_code , main_row.primary_phone_type_code , main_row.email_address , main_row.comments , main_row.primary_phone_extension
, main_row.secondary_phone_extension , main_row.primaryaddressid , main_row.primaryaddresscode , main_row.primaryaddress1 , main_row.primaryaddress2 , main_row.primarycity
, main_row.primarystate , main_row.primaryzip , main_row.primarycurrent , main_row.secondaryaddressid , main_row.secondaryaddresscode , main_row.secondaryaddress1
, main_row.secondaryaddress2 , main_row.secondarycity , main_row.secondarystate , main_row.secondaryzip , main_row.secondarycurrent , main_row.primary_owner_oid , main_row.is_primary );
end loop;
return v_owner_details_set;
EXCEPTION
When others
then dbms_output.put_line ('Oracle error: '||SQLERRM);
end;

The AUTONOMOUS_TRANSACTION pragma means that the function operates in the context of a separate transaction. By default (see http://docs.oracle.com/cd/B19306_01/server.102/b14220/consist.htm#sthref1972) this uses the "read committed" isolation level, meaning that, when the transaction queries data, it sees only data that was committed before the query began. Since the data you inserted has not been committed, this means that the function can't see it.

From Oracle Docs:
The AUTONOMOUS_TRANSACTION pragma changes the way a subprogram works within a transaction. A subprogram marked with this pragma can do SQL operations and commit or roll back those operations, without committing or rolling back the data in the main transaction.
Can you try getting rid of that pragma?
Lastly, "My DBA told me that Oracle functions do not operate inside a transaction" is questionable. I'm no expert but I sincerely doubt whether this is correct.

Related

Where does the table mutation take place here (Oracle)?

I'm dealing with oracle SQL now, and trying to create a trigger. For some reasonn it shows me the mutated table error, however, I don't see where it gets mutated at all (it's just a select without even counts, however, it has joins). Where should I at least start in writing a compound trigger for the solution? There seems to be just a few examples and they are too far from mine to understand how it should work at all in this particular situation.
CREATE OR REPLACE TRIGGER "EVGENIJ_BOBROVICH"."FIX_UPD_LIMITS"
BEFORE UPDATE OR DELETE ON "EVGENIJ_BOBROVICH"."MAP_CALCULATION_SHOP_LIMITS"
FOR EACH ROW
DECLARE
is_deleted_dependant VARCHAR2(1 BYTE);
is_editable_dependant VARCHAR2(1 BYTE);
BEGIN
SELECT IS_DELETE, IS_EDITABLE INTO is_deleted_dependant, is_editable_dependant
FROM MAP_CALCULATION MC INNER JOIN map_calculation_group MG
ON MC.ID_CALC = MG.ID_CALC INNER JOIN map_calculation_shop_limits MS ON MG.ID_GROUP = ms.id_group
WHERE :OLD.ID_GROUP = MG.ID_GROUP AND MG.ID_CALC = MC.ID_CALC;
IF UPDATING AND (is_editable_dependant = 'F' OR is_deleted_dependant = 'T') THEN
RAISE_APPLICATION_ERROR( -20004, '....Error......' );
ELSIF DELETING AND (is_editable_dependant = 'F' OR is_deleted_dependant = 'T') THEN
RAISE_APPLICATION_ERROR( -20005, '...AnotherError...' );
END IF;
END;
/
The select itself without a trigger (without the into and old of course as well, I used a bind variable instead of old) works fine...
It happens here:
INNER JOIN map_calculation_shop_limits
You can't select from the same table you're updating as it is ... well, mutating.
For updating purposes, you'd
FROM map_calculation mc
INNER JOIN map_calculation_group mg ON mc.id_calc = mg.id_calc
-- INNER JOIN map_calculation_shop_limits MS ON MG.ID_GROUP = ms.id_group --> this
WHERE :old.id_group = mg.id_group
AND mg.id_calc = mc.id_calc
AND mg.id_group = :new.id_group; --> and this
For deleting, you'd use :old.id_group which means that you'll need to rewrite code you use into two parts: one that'll handle updates, and another to handle deletes.

ORA-00947 not enough values with function returning table of records

So I'm trying to build a function that returns the records of items that are included in some client subscription.
So I've been building up the following:
2 types:
CREATE OR REPLACE TYPE PGM_ROW AS OBJECT
(
pID NUMBER(10),
pName VARCHAR2(300)
);
CREATE OR REPLACE TYPE PGM_TAB AS TABLE OF PGM_ROW;
1 function:
CREATE OR REPLACE FUNCTION FLOGIN (USER_ID NUMBER) RETURN PGM_TAB
AS
SELECTED_PGM PGM_TAB;
BEGIN
FOR RESTRICTION
IN ( SELECT (SELECT LISTAGG (ID_CHANNEL, ',')
WITHIN GROUP (ORDER BY ID_CHANNEL)
FROM (SELECT DISTINCT CHA2.ID_CHANNEL
FROM CHANNELS_ACCESSES CHA2
JOIN CHANNELS CH2
ON CH2.ID = CHA2.ID_CHANNEL
WHERE CHA2.ID_ACCESS = CMPA.ID_ACCESS
AND CH2.ID_CHANNELS_GROUP = CG.ID))
AS channels,
(SELECT LISTAGG (ID_SUBGENRE, ',')
WITHIN GROUP (ORDER BY ID_SUBGENRE)
FROM (SELECT DISTINCT SGA2.ID_SUBGENRE
FROM SUBGENRES_ACCESSES SGA2
JOIN CHANNELS_ACCESSES CHA2
ON CHA2.ID_ACCESS = SGA2.ID_ACCESS
JOIN CHANNELS CH2
ON CH2.ID = CHA2.ID_CHANNEL
WHERE SGA2.ID_ACCESS = CMPA.ID_ACCESS
AND CH2.ID_CHANNELS_GROUP = CG.ID))
AS subgenres,
CG.NAME,
A.BEGIN_DATE,
A.END_DATE,
CMP.PREVIEW_ACCESS
FROM USERS U
JOIN COMPANIES_ACCESSES CMPA
ON U.ID_COMPANY = CMPA.ID_COMPANY
JOIN COMPANIES CMP ON CMP.ID = CMPA.ID_COMPANY
JOIN ACCESSES A ON A.ID = CMPA.ID_ACCESS
JOIN CHANNELS_ACCESSES CHA
ON CHA.ID_ACCESS = CMPA.ID_ACCESS
JOIN SUBGENRES_ACCESSES SGA
ON SGA.ID_ACCESS = CMPA.ID_ACCESS
JOIN CHANNELS CH ON CH.ID = CHA.ID_CHANNEL
JOIN CHANNELS_GROUPS CG ON CG.ID = CH.ID_CHANNELS_GROUP
WHERE U.ID = USER_ID
GROUP BY CG.NAME,
A.BEGIN_DATE,
A.END_DATE,
CMPA.ID_ACCESS,
CG.ID,
CMP.PREVIEW_ACCESS)
LOOP
SELECT PFT.ID_PROGRAM, PFT.LOCAL_TITLE
BULK COLLECT INTO SELECTED_PGM
FROM PROGRAMS_FT PFT
WHERE PFT.ID_CHANNEL IN
( SELECT TO_NUMBER (
REGEXP_SUBSTR (RESTRICTION.CHANNELS,
'[^,]+',
1,
ROWNUM))
FROM DUAL
CONNECT BY LEVEL <=
TO_NUMBER (
REGEXP_COUNT (RESTRICTION.CHANNELS,
'[^,]+')))
AND PFT.ID_SUBGENRE IN
( SELECT TO_NUMBER (
REGEXP_SUBSTR (RESTRICTION.SUBGENRES,
'[^,]+',
1,
ROWNUM))
FROM DUAL
CONNECT BY LEVEL <=
TO_NUMBER (
REGEXP_COUNT (RESTRICTION.SUBGENRES,
'[^,]+')))
AND (PFT.LAUNCH_DATE BETWEEN RESTRICTION.BEGIN_DATE
AND RESTRICTION.END_DATE);
END LOOP;
RETURN SELECTED_PGM;
END FLOGIN;
I expect the function tu return a table with 2 columns containing all the records from table PROGRAMS_FT that are included in the user access.
For some reason, I'm getting compilation warning ORA-000947.
My understanding of the error code is that it occurs when the values inserted does not match the type of the object receiving the values, and I can't see how this can be the case here.
You're selecting two scalar values and trying to put them into an object. That doesn't happen automatically, you need to convert them to an object:
...
LOOP
SELECT PGM_ROW(PFT.ID_PROGRAM, PFT.LOCAL_TITLE)
BULK COLLECT INTO SELECTED_PGM
FROM PROGRAMS_FT PFT
...
(It's an unhelpful quirk of PL/SQL that it says 'not enough values' rather than 'too many values', as you might expect when you try to put two things into one; I'm sure I came up with a fairly convincing explanation/excuse for that once but it escapes me at the moment...)
I'm not sure your loop makes sense though. Assuming your cursor query returns multiple rows, each time around the loop you're replacing the contents of the SELECTED_PGM collection - you might think you are appending to it, but that's not how it works. So you will end up returning a collection based only on the final iteration of the loop.
Aggregating and then splitting the data seems like a lot of work too. You could maybe use collections for those; but you can probably get rid of the cursor and loop and combine the cursor query with the inner query, which would be more efficient and would allow you to do a single bulk-collect for all the combined data.

I'm trying to update 2 fields in multiple tables in my database using a trigger after inserting a new row

i just created the trigger
here is the code:
CREATE OR REPLACE TRIGGER tr_update_solde_nbreserv
AFTER INSERT ON reservation
FOR EACH ROW
BEGIN
UPDATE CLIENTS
SET CLIENTS.NB_RESERV = NB_RESERV+1 , CLIENTS.SOLDE = SOLDE+1
FROM dbo.clients as c
INNER JOIN dbo.reservation as r
ON c.numc = r.numc
WHERE r.numr = :new.numr;
BEGIN
SELECT fillHist_station FROM DUAL;
END;
end tr_update_solde_nbreserv;
i'm getting these 2 errors:
Error(1,9): PL/SQL: SQL Statement ignored
Error(3,9): PL/SQL: ORA-00933: SQL command not properly ended
how can i fix them
There are several issues with your trigger code.
1) The purpose of this part of the code is unclear :
BEGIN
SELECT fillHist_station FROM DUAL;
END;
fillHist_station is not declared, hence this code would raise an invalid identifier error.
2) The syntax of the UPDATE query is invalid. Also, your intend is to select from the table that the trigger fired on, which is not allowed in Oracle. From looking at your code, it looks like you don't actually need to query RESERVATION to achieve your goal. As a row was just inserted in RESERVATION, you already know the corresponding client number.
3) You miss a / at the end
Here is an updated version of your code, that you can play around with in this db fiddle (you did not provide the structure of your tables so I just created the coulmns that are referenced in the query) :
CREATE OR REPLACE TRIGGER tr_update_solde_nbreserv
AFTER INSERT ON RESERVATION
FOR EACH ROW
BEGIN
UPDATE CLIENTS
SET NB_RESERV = NB_RESERV+1 , SOLDE = SOLDE+1
WHERE numc = :new.numc;
END tr_update_solde_nbreserv;
/
update CLIENTS
SET CLIENTS.NB_RESERV = NB_RESERV+1 , CLIENTS.SOLDE = SOLDE+1
FROM dbo.clients as c
inner join dbo.reservation as r
on c.numc = r.numc
where r.numr = :new.numr;
update with inner join is not supported in Oracle database in this way. furthermore dbo.clients and dbo.reservations look like Sql Server tables rather then oracle.
I believe that you are looking for something like this, but I am not sure about the relations. You may need to fix the query.
UPDATE
(
SELECT clients.nb_reserv, r.nb_reserv as r_nb_reserv, clients.solde, r.solde as r_solde
FROM clients
inner join reservation as r
on c.numc = r.numc
where r.numr = :new.numr
) t
SET CLIENTS.NB_RESERV = r_nb_reserv + 1, clients.solde = r_solde+1;
Simpler approach
UPDATE clients SET NB_RESERV = (SELECT nb_reserv +1
FROM reservations
WHERE c.numc = r.numc and r.numr = :new.numr),
SOLDE = (SELECT SOLDE +1
FROM reservations
WHERE c.numc = r.numc and r.numr = :new.numr)
WHERE EXISTS (SELECT 1 FROM reservations
WHERE c.numc = r.numc and r.numr = :new.numr);

ORA-01791 Pl-Sql error

hi guy i have a query that give me the followin error:
ORA-01791: not a SELECTed expression
this is the select expresison , please can you tell me why ?
declare
freqLettura varchar2(64);
billingcy varchar2(64);
begin
freqLettura := null;
billingcy := null;
for rec in ( select distinct(fn_get_facilityid(z.uidfacility) ) as a, 1 as b
from facilityhistory z,
locality l ,
plant p ,
ztmp_sam_tb_sdv zsdv ,
ztmp_sam_tb_plantcode zplant ,
sam_tb_ca_pdr sam,
meterhistory mh,
meter m ,
meterclass mc
where
Z.UIDLOCALITY = L.UIDLOCALITY and
p.UIDPLANT = L.UIDPLANT and
z.uidaccount = zsdv.uidaccount and
p.plantcode = zplant.plantcode and
sam.uidfacility = z.uidfacility and
z.stoptime is null and
sam.status = 'U' and
mh.uidfacility = z.uidfacility and
mh.uidmeter = m.uidmeter and
m.uidmeterclass = mc.uidmeterclass and
(billingcy is null or p.UIDBILLINGCYCLE = billingcy )
AND
(
(
(freqLettura = 'G') AND ( mh.corrmeterid is not null and mh.stoptime is null and mc.maxflowmeter >= SAM_FN_GET_PARAMETER_FLOAT('MAXFLOWMET_DETT_GIORN'))
)
OR
(
nvl(freqLettura,'nullo') <> 'G' AND (freqLettura is null or sam.readfrequency = freqLettura)
)
) and ROWNUM = 1 order by sam.stoptime, sam.uidsamtbpdr desc ) loop
begin
insert into ztmp_sam_tb_elab_pdr (facilityid, uidbatchrequest) VALUES (rec.a, rec.b);
exception
when dup_val_on_index then
null;
end;
end loop;
end;
Whenever you get an Oracle error message you don't understand, the first thing to do is look up the meaning. One way is simply to Google it. In this case the full description found in
Oracle9i Database Error Messages is:
ORA-01791 not a SELECTed expression
Cause: There is an incorrect ORDER
BY item. The query is a SELECT DISTINCT query with an ORDER BY clause.
In this context, all ORDER BY items must be constants, SELECT list
expressions, or expressions whose operands are constants or SELECT
list expressions.
Action: Remove the inappropriate ORDER BY item from the SELECT list
and retry the statement.
(Oddly this error message isn't documented in the 10G or 11G manuals, despite still being raised!)
This matches the statement you have written, which is a SELECT DISTINCT query where you are trying to order the results by a column that you did not select.
If you think about it, what you are asking for doesn't make sense: by selecting DISTINCT values that do not include sam.stoptime (for example) you may be consolidating many rows with different values for sam.stoptime, so which one would govern the ordering?
Also, as Noel's answer points out, there is no reason to have an ORDER BY clause in this code anyway, so the solution is simply to remove it.
If you are using DISTINCT in your SELECT query, then your ORDER BY clause should contain only those columns that your selecting. In this case sam.stoptime, sam.uidsamtbpdr are not there in SELECT statement. You can remove the ORDER BY clause, as it is not doing anything useful in your example.

Binding variables in dynamic PL/SQL

I have a dynamic PL/SQL that will construct the SELECT statement based on what the searching criteria input from the users,likes:
l_sql := 'SELECT * INTO FROM TABLEA WHERE 1=1 ';
IF in_param1 IS NOT NULL THEN
l_sql := l_sql || 'AND column1 = in_param1 ';
END IF;
IF in_param2 IS NOT NULL THEN
l_sql := l_sql || 'AND column2 = in_param2 ';
END IF;
...................................
IF in_paramXX IS NOT NULL THEN
l_sql := l_sql || 'AND columnXX = in_paramXX ';
END IF;
To reduce the hard parse overhead , I consider to use the binding variables. However , it is difficult to manage when supplying the actual values to the binding variables as there are so many binding variables and combination of the generated SELECT statement . I cannot use the method of DBMS_SESSION.set_context() introduced at http://www.dba-oracle.com/plsql/t_plsql_dynamic_binds.htm because my account has no right to use this package. Besides , I want the generated SQL only contains the conditions on the fields that the user did not leave empty. So I cannot change the dynamic SQL to something likes
SELECT * INTO FROM TABLEA WHERE 1=1
and ( in_param1 is NULL or column1 = in_param1)
and ( in_param2 is NULL or column2 = in_param2)
...............................................
and ( in_paramXX is NULL or columnXX = in_paramXX)
So , I want to try to use the DBMS_SQL method .Can anyone give an example about how to use DBMS_SQL to call dynamic SQL with binding variables? Especially , how can I get the result executed from DBMS_SQL.execute() to the SYS_REFCURSOR , something like :
open refcursor for select .... from
The oracle version that I use is 10g and it seems that the oracle 10g does not have DBMS_Sql.To_Refcursor()
In your Oracle version you can apply some tricks to your query in order to do this. The idea is to use a query in the following form:
select *
from
(select
:possibleParam1 as param1
-- do the same for every possible param in your query
:possibleParamN as paramN
from dual
where rownum > 0) params
inner join
-- join your tables here
on
-- concatenate your filters here
where
-- fixed conditions
then execute it with:
open c for query using param1, ..., paramN;
It works by using DUAL to generate a fake row with every single param, then inner joining this fake row to your real query (without any filters) using only the filters you want to apply. This way, you have a fixed list of bind variables in the SELECT list of the params subquery, but can control which filters are applied by modifying the join condition between params and your real query.
So, if you have something like, say:
create table people (
first_name varchar2(20)
last_name varchar2(20)
);
you can construct the following query if you just want to filter on first name
select *
from
(select
:first_name as first_name,
:last_name as last_name
from dual
where rownum > 0) params
inner join
people
on
people.first_name = params.first_name;
and this if you want to filter on both first_name and last_name
select *
from
(select
:first_name as first_name,
:last_name as last_name
from dual
where rownum > 0) params
inner join
people
on
people.first_name = params.first_name and
people.last_name = params.last_name;
and in every case you would execute with
open c for query using filterFirstName, filterLastName;
It is important for performance to use the where rownum > 0 with DUAL as it forces Oracle to "materialize" the subquery. This usually makes DUAL stop interfering with the rest of the query. Anyway, you should check the execution plans to be sure Oracle is not doing anything wrong.
In 10g a DBMS_SQL cursor can't be changed into a Ref Cursor. Going through a result set through DBMS_SQL is tortuous since, as well as looping through the rows, you also have to loop through the columns in a row.
I want the generated SQL only contains
the conditions on the fields that the
user did not leave empty
Is that purely for performance reasons ? If so, I suggest you work out what the practical execution plans are and use separate queries for them.
For example, say I'm searching on people and the parameters are first_name, last_name. gender, date_of_birth. The table has indexes on (last_name,first_name) and (date_of_birth), so I only want to allow a query if it specifies either last_name or date_of_birth.
IF :p_firstname IS NOT NULL and :p_lastname IS NOT NULL THEN
OPEN cur FOR
'SELECT * FROM PEOPLE WHERE last_name=:a AND first_name=:b AND
(date_of_birth = :c or :c is NULL) AND (gender = :d or :d IS NULL)' USING ....
ELSIF :p_lastname IS NOT NULL THEN
OPEN cur FOR
'SELECT * FROM PEOPLE WHERE last_name=:a AND
(date_of_birth = :c or :c is NULL) AND (gender = :d or :d IS NULL)' USING ....
ELSIF :p_dateofbirth IS NOT NULL THEN
OPEN cur FOR
'SELECT * FROM PEOPLE WHERE date_of_birth=:a AND
(first_name=:b OR :b IS NULL) AND (gender = :d or :d IS NULL)' USING ....
ELSE
RAISE_APPLICATION_ERROR(-20001,'Last Name or Date of Birth MUST be supplied);
END IF;

Resources