How to update a single row in an Interactive Grid? - oracle

currently i am facing a problem on how to update a single row in an interactive grid. My Page contains multiple IGs and I have to use PL/SQL to update the rows.
Automatic Row Processing didn't work properly. Attached you can find the IG and the code I wrote. I don't know how to select the correct row with the rowid.
I have 4 columns in my table, note that I don't have a column ROWID. Any help is appreciated.
begin
case :APEX$ROW_STATUS
when 'I' then -- Note: In EA2 this has been changed from I to C for consistency with Tabular Forms --I for Insert
insert into poc_sofortmassnahme ( beschreibung_sofort, bearbeiter_sofort, zieldatum_sofort, wirksamkeit, sof_id )
values ( :BESCHREIBUNG_SOFORT, :BEARBEITER_SOFORT, :ZIELDATUM_SOFORT, :WIRKSAMKEIT, :P40_SOFORT_ID)
returning rowid into :ROWID;
when 'U' then -- U for Update
update poc_sofortmassnahme
set BESCHREIBUNG_SOFORT = :BESCHREIBUNG_SOFORT,
BEARBEITER_SOFORT = :BEARBEITER_SOFORT,
ZIELDATUM_SOFORT = :ZIELDATUM_SOFORT,
WIRKSAMKEIT = :WIRKSAMKEIT
where rowid = :ROWID;
when 'D' then -- D for Delete
delete POC_SOFORTMASSNAHME
where rowid = :ROWID;
end case;
end;
Sincerly,
EE

Related

Oracle equivalent query for this postgress query - CONFLICT [duplicate]

The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:
if table t has a row exists that has key X:
update t set mystuff... where mykey=X
else
insert into t mystuff...
Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?
The MERGE statement merges data between two tables. Using DUAL
allows us to use this command. Note that this is not protected against concurrent access.
create or replace
procedure ups(xa number)
as
begin
merge into mergetest m using dual on (a = xa)
when not matched then insert (a,b) values (xa,1)
when matched then update set b = b+1;
end ups;
/
drop table mergetest;
create table mergetest(a number, b number);
call ups(10);
call ups(10);
call ups(20);
select * from mergetest;
A B
---------------------- ----------------------
10 2
20 1
The dual example above which is in PL/SQL was great becuase I wanted to do something similar, but I wanted it client side...so here is the SQL I used to send a similar statement direct from some C#
MERGE INTO Employee USING dual ON ( "id"=2097153 )
WHEN MATCHED THEN UPDATE SET "last"="smith" , "name"="john"
WHEN NOT MATCHED THEN INSERT ("id","last","name")
VALUES ( 2097153,"smith", "john" )
However from a C# perspective this provide to be slower than doing the update and seeing if the rows affected was 0 and doing the insert if it was.
An alternative to MERGE (the "old fashioned way"):
begin
insert into t (mykey, mystuff)
values ('X', 123);
exception
when dup_val_on_index then
update t
set mystuff = 123
where mykey = 'X';
end;
Another alternative without the exception check:
UPDATE tablename
SET val1 = in_val1,
val2 = in_val2
WHERE val3 = in_val3;
IF ( sql%rowcount = 0 )
THEN
INSERT INTO tablename
VALUES (in_val1, in_val2, in_val3);
END IF;
insert if not exists
update:
INSERT INTO mytable (id1, t1)
SELECT 11, 'x1' FROM DUAL
WHERE NOT EXISTS (SELECT id1 FROM mytble WHERE id1 = 11);
UPDATE mytable SET t1 = 'x1' WHERE id1 = 11;
None of the answers given so far is safe in the face of concurrent accesses, as pointed out in Tim Sylvester's comment, and will raise exceptions in case of races. To fix that, the insert/update combo must be wrapped in some kind of loop statement, so that in case of an exception the whole thing is retried.
As an example, here's how Grommit's code can be wrapped in a loop to make it safe when run concurrently:
PROCEDURE MyProc (
...
) IS
BEGIN
LOOP
BEGIN
MERGE INTO Employee USING dual ON ( "id"=2097153 )
WHEN MATCHED THEN UPDATE SET "last"="smith" , "name"="john"
WHEN NOT MATCHED THEN INSERT ("id","last","name")
VALUES ( 2097153,"smith", "john" );
EXIT; -- success? -> exit loop
EXCEPTION
WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted
NULL; -- exception? -> no op, i.e. continue looping
WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted
NULL; -- exception? -> no op, i.e. continue looping
END;
END LOOP;
END;
N.B. In transaction mode SERIALIZABLE, which I don't recommend btw, you might run into
ORA-08177: can't serialize access for this transaction exceptions instead.
I'd like Grommit answer, except it require dupe values. I found solution where it may appear once: http://forums.devshed.com/showpost.php?p=1182653&postcount=2
MERGE INTO KBS.NUFUS_MUHTARLIK B
USING (
SELECT '028-01' CILT, '25' SAYFA, '6' KUTUK, '46603404838' MERNIS_NO
FROM DUAL
) E
ON (B.MERNIS_NO = E.MERNIS_NO)
WHEN MATCHED THEN
UPDATE SET B.CILT = E.CILT, B.SAYFA = E.SAYFA, B.KUTUK = E.KUTUK
WHEN NOT MATCHED THEN
INSERT ( CILT, SAYFA, KUTUK, MERNIS_NO)
VALUES (E.CILT, E.SAYFA, E.KUTUK, E.MERNIS_NO);
I've been using the first code sample for years. Notice notfound rather than count.
UPDATE tablename SET val1 = in_val1, val2 = in_val2
WHERE val3 = in_val3;
IF ( sql%notfound ) THEN
INSERT INTO tablename
VALUES (in_val1, in_val2, in_val3);
END IF;
The code below is the possibly new and improved code
MERGE INTO tablename USING dual ON ( val3 = in_val3 )
WHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2
WHEN NOT MATCHED THEN INSERT
VALUES (in_val1, in_val2, in_val3)
In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could execute the correct insert or update with a single index lookup.
I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.
A note regarding the two solutions that suggest:
1) Insert, if exception then update,
or
2) Update, if sql%rowcount = 0 then insert
The question of whether to insert or update first is also application dependent. Are you expecting more inserts or more updates? The one that is most likely to succeed should go first.
If you pick the wrong one you will get a bunch of unnecessary index reads. Not a huge deal but still something to consider.
Try this,
insert into b_building_property (
select
'AREA_IN_COMMON_USE_DOUBLE','Area in Common Use','DOUBLE', null, 9000, 9
from dual
)
minus
(
select * from b_building_property where id = 9
)
;
From http://www.praetoriate.com/oracle_tips_upserts.htm:
"In Oracle9i, an UPSERT can accomplish this task in a single statement:"
INSERT
FIRST WHEN
credit_limit >=100000
THEN INTO
rich_customers
VALUES(cust_id,cust_credit_limit)
INTO customers
ELSE
INTO customers SELECT * FROM new_customers;

Update after calculate for each record ORACLE

SELECT CIF_ID,
SUM (IN_VERIFIED_DEBT + IN_FAC_WITH_OTHER + IN_FAC_WITH_BANK)
from LOS_CIF_INDV
WHERE STATUS= 'ACTIVE'
GROUP By CIF_ID;
I want to update the total column again after the user manipulates the client as update, insert but it gives an error
ORA-04098: trigger 'RLOS138.UPDATE_IN_TOTAL_COMMIT' is invalid and failed re-validation
CREATE OR REPLACE TRIGGER UPDATE_IN_TOTAL_COMMIT
AFTER UPDATE ON
LOS_CIF_INDV
FOR EACH ROW
DECLARE
inactive_id number;
BEGIN
inactive_id:=
:new.IN_VERIFIED_DEBT + :new.IN_FAC_WITH_OTHER + :new.IN_FAC_WITH_BANK;
UPDAte LOS_CIF_INDV
SET IN_TOTAL_COMMIT = inactive_id
WHERE CIF_ID = :NEW.CIF_ID;
END ;
/
I have tried this again
CREATE OR REPLACE TRIGGER RLOS138.UPDATE_IN_TOTAL_COMMIT
AFTER UPDATE ON RLOS138.LOS_CIF_INDV
FOR EACH ROW
DECLARE
inactive_id number;
BEGIN
SELECT SUM (IN_VERIFIED_DEBT+IN_FAC_WITH_OTHER+IN_FAC_WITH_BANK)
into inactive_id
from LOS_CIF_INDV
WHERE STATUS= 'ACTIVE'
and CIF_ID=:NEw.CIF_ID;
update LOS_CIF_INDV
set IN_TOTAL_COMMIT = inactive_id
where CIF_ID = :NEW.CIF_ID;
END ;
/
yes [CIF_ID] is primary key
In which case this trigger has the logic you need:
CREATE OR REPLACE TRIGGER RLOS138.UPDATE_IN_TOTAL_COMMIT
BEFORE UPDATE ON RLOS138.LOS_CIF_INDV
FOR EACH ROW
BEGIN
if :new.status = 'ACTIVE'
then
:new.IN_TOTAL_COMMIT := :new.IN_VERIFIED_DEBT + :new.IN_FAC_WITH_OTHER + :new.IN_FAC_WITH_BANK;
end if;
END ;
/
I have included the check on status because you used it in your aggregation queries, even though you omitted from the first version of the trigger. I haven't included an ELSE branch, but you may wish to add one. Also, I have assumed that the three columns in the addition are guaranteed to be not null; if that's not the case you'll need to handle that.
I have put a working demo on db<>fiddle. This includes a version of the trigger which fires on inserts as well as updates, and handles null values too....
CREATE OR REPLACE TRIGGER UPDATE_IN_TOTAL_COMMIT
-- handle INSERT as well as UPDATE
BEFORE INSERT OR UPDATE ON LOS_CIF_INDV
FOR EACH ROW
BEGIN
if :new.status = 'ACTIVE'
then
-- handle any of these columns being null
:new.IN_TOTAL_COMMIT := nvl(:new.IN_VERIFIED_DEBT,0)
+ nvl(:new.IN_FAC_WITH_OTHER,0)
+ nvl(:new.IN_FAC_WITH_BANK,0);
end if;
END ;
/
Why not after you could explain it to me
Because Oracle have written triggers that way: the AFTER EACH ROW trigger uses the finalised version of the record, the state which will be written to the database. Consequently, if we want to change any values we need to use a BEFORE EACH ROW trigger. Oracle enforces this with the error you got, ORA-04084: cannot change NEW values for this trigger type.
Just a reminder: ORA-04098 is telling you there are compilation errors in your trigger code. If you're not using an IDE which tells you what these errors are you can find them with this query:
select * from all_errors
where owner = 'RLOS138'
and name = 'UPDATE_IN_TOTAL_COMMIT' ;
(Not sure if you're connecting as RLOS138 - if you are, query USER_ERRORS instead.)
If I understood correctly, You want to update all the records having CIF_ID as an updated record with the same value in the IN_TOTAL_COMMIT column.
This is not a good idea. If you have some derived column then you should use the views instead of updating its value for every insert/update using the trigger.
If you really want to update the column then you must use the combination of Row level trigger, Statement trigger, and package variables. (Search for mutating table error in the SO)
But according to me, the best solution is to use the view, something like follows:
CREATE OR REPLACE VIEW LOS_CIF_INDV_VW AS
SELECT L.*,
COALESCE(
SUM(
CASE
WHEN STATUS = 'ACTIVE' THEN
IN_VERIFIED_DEBT + IN_FAC_WITH_OTHER + IN_FAC_WITH_BANK
END
) OVER(
PARTITION BY L.CIF_ID
),
0
) AS IN_TOTAL_COMMIT
FROM LOS_CIF_INDV L;

Insert inside trigger not firing

Hi i have this simple trigger in oracle
CREATE OR REPLACE TRIGGER OCAP_CREATE_NCRB
BEFORE INSERT
ON OCAP_TBLOCAP
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
DECLARE
Defect_Type varchar2(16);
out_ varchar2(60);
BEGIN
Select A.DEFECT_TYPE into Defect_Type from OCAP_TBLDEFECT A where A.DEFECT_ID = :NEW.DEFECT;
IF Defect_Type = 'C' THEN
--Create NCRB
SP_INSERTTBLD1D2(23,LPAD(:NEW.ISSUED_BY,6,'0'),0,'0','0','035823','Draft',' ',' ',34,' ',0,461,0,0,'035105',trunc(sysdate),' ','A',Lpad(:NEW.ISSUED_BY,6,'0'),Lpad(:NEW.ISSUED_BY,6,'0'),trunc(sysdate),'A',:New.BATCH_NO,out_);
--insert action
SP_INSERTTBLFORMYACTION(Lpad(:NEW.ISSUED_BY,6,'0'), out_, Lpad(:NEW.ISSUED_BY,6,'0'), Lpad(:NEW.ISSUED_BY,'0'), 'Draft');
--Insert other affected Lots
insert into TBLD2LOT(NCRBSERIESNO,LOTNO,CREATEDBY,CREATEDDT,SEQNO) Select (out_), A.BATCH_NO,Lpad(:NEW.ISSUED_BY,6,'0'),sysdate,(TBLD2LOTSEQ.nextval) from OCAP_OTHERBATCH A where A.OCAP_ID = :NEW.OCAP_NO;
--add NCRBSeries no. to table OCAP_TBLOCAP for referencing
Update OCAP_TBLOCAP set NCRBSERIESNO = out_ where OCAP_NO = :NEW.OCAP_NO;
--Insert ocap history
END IF;
END Ocap_Create_NCRB;
/
the first 2 stored procedure is working fine but the insert query is not .
I try to excute the insert query manunaly by replacing the Out_ and the :new.Ocap_no it is working fine.
Is there something wrong in my query?
Hope someone help me out with this.
If it isn't working, then
from OCAP_OTHERBATCH A
where A.OCAP_ID = :NEW.OCAP_NO; --> this condition is never met
which means that no rows in OCAP_OTHERBATCH contain OCAP_ID value which is equal to :NEW.OCAP_NO.
Might be because of wrong letter case, CHAR datatype (right-padded with spaces up to column's full length), ... who knows. Without tables' description and sample data, it is difficult to guess.

Oracle : Creating record-column history

Usually the best solution to capture history would be to create a trigger which takes snapshot of the record while updating into a history table however :
1.) My table contains 60 columns but I want to capture history for only 10 of them.
2.) The data from source come's with a Submit date which is not captured in the target table. The history need's to be captured based on that Submit date sent by the source and not based on current sysdate.
3.) We have control over the Select, Update process.
Proposed Solution:
We created a function as below
In(Primary Key, Submit_Date, Column_Name, Old Value, New Value)
PRAGMA AUTONOMOUS_TRANSACTION;
Fetch max(Submit_date) From History using PK;
If max_Submit_date is Null:
Insert in History using PK, 01-01-1700 as Submit date, Column Name, Old_Value;
Insert into History using PK & Submit_date & new Value;
Elsif max_Submit_date = Submit_date
Update History using PK & Submit_date with new Value;
Elsif max_Submit_date < Submit_date
Insert into History using PK & Submit_date & new Value;
End if;
commit;
While selecting data for update we added
select .... ,
DECODE(T.Column_VALUE_1,S.Column_VALUE_1,NULL,Function(PK,'COLUMN_NAME_1', S.Submit_Date, T.Column_VALUE_1, S.Column_VALUE_1)) XYZ,
DECODE(T.Column_VALUE_2,S.Column_VALUE_2,NULL,Function(PK,'COLUMN_NAME_2', S.Submit_Date, T.Column_VALUE_2, S.Column_VALUE_2)) XYZ,
From Source_Table S Join Target Table T Where ...
I can see that the solution is not ideal or efficient. Please advise if the requirement can be met in any other way.
One solution could be to perform it for all records, at once, utilizing a MERGE INTO statement. Since your submit_date is part of insert and also comparison, ideal solution to avoid conflict would be to have a version column in your History table, containing 1 for initial version and 2,3,4.. and so on for subsequent versions.
And instead of comparing with decode and calling function, you could exclude all such records in where clause condition.
MERGE INTO HISTORY h USING
(
with m(pk,max_Submit_date) AS
( select pk,submit_date,version
FROM HISTORY o where
version IN ( select MAX(version) max_version
FROM HISTORY i where i.pk = o.pk ) ,
select .... PK,
CASE WHEN m.max_Submit_date is Null
THEN 01-01-1700
WHEN m.max_Submit_date <= s.Submit_date THEN
s.Submit_date
END as Submit_date,
decode( m.max_Submit_date,NULL,T.Column_VALUE_1, S.Column_VALUE_1)
decode( m.max_Submit_date,NULL,T.Column_VALUE_2, S.Column_VALUE_2)
..
CASE WHEN m.max_Submit_date is Null
THEN 1
WHEN m.max_Submit_date <= s.Submit_date
THEN m.max_version + 1 new_version
ELSE
m.max_version
END version
From Source_Table S Join Target Table T
JOIN m ON m.pk = s.pk
Where ..
( T.Column_VALUE_1 != S.Column_VALUE_1 ) OR
( T.Column_VALUE_2 != S.Column_VALUE_2 ) OR
..
..
) cur
ON ( cur.pk = h.pk and h.version = cur.version )
WHEN MATCHED THEN
Update SET h.Submit_date = cur.Submit_date,
h.Column_VALUE_1 = s.Column_VALUE_1,
h.Column_VALUE_2 = s.Column_VALUE_2
..
WHEN NOT MATCHED THEN INSERT
INSERT (PK,submit_date,column_1,..) VALUES (..);

Oracle, ROWNUM=1 with FOR UPDATE clause?

My statement:
SELECT ROW_ID DATA_T WHERE CITY_ID=2000 AND IS_FREE=0 AND ROWNUM = 1
is used to retrieve the first row for a db table that has many entries with CITY_ID equal to 2000.
The ROW_ID that is returned is then used in an UPDATE statement in order to use this row and set IS_FREE=1.
That worked very well until two threads called the SELECT statement and the got the same ROW_ID obviously... That is my problem in a few words.
I am using ORACLE DB (12.x)
How do I resolve the problem? Can I use FOR UPDATE in this case?
I want every "client" somehow to get a different row or at least lock on of them
Something like this
function get_row_id return number
as
cursor cur_upd is
SELECT ROW_ID FROM TB WHERE CITY_ID=2000 AND IS_FREE=0 AND ROWNUM = 1
FOR UPDATE SKIP LOCKED;
begin
for get_cur_upd in cur_upd
loop
update TB
set IS_FREE = 1
where ROW_ID = get_cur_upd.ROW_ID;
commit work;
return get_cur_upd.ROW_ID;
end loop;
return null;
end;
commit or not after update depends on your logic.
Also you can return row_id without update&commit and do it later outside func.

Resources