Oracle DBMS_ALERT in Oracle 12c - oracle

I have a table (my_tab) that contains a STATUS column against a specific ID in this same table.
I need a means of being alerted via a DBMS_ALERT process of when the STATUS column changes value.
I was looking at using a trigger to kick off the ALERT, i.e.:
create or replace trigger my_tab_upd after update of status on my_tab for each row
begin
dbms_alert.signal('mystatusalert', 'changed from '||:old.status||' to '||:new.status||'.');
end;
/
With this, how do I now get alerted/notified that this STATUS change has occurred within a PL/SQL procedure to now go off and perform another operation based on this STATUS change?
Further to the above, with my application setup, there will be multiple users. Based on this, how can I target the alert for specific users/sessions so that the correct user gets their alert only and not someone else's.
I am looking at checking the alert from a web based application (Oracle APEX), so don't want to lock the front-end up so any recommendations on this would be good.
An example would be great.

I'd send an e-mail to myself. For example:
create or replace trigger my_tab_upd
after update of status on my_tab
for each row
begin
utl_mail.send (sender => 'me#company.com',
recipients => 'me#company.com',
subject => 'MY_TAB status changed',
message => 'old = ' || :old.status ||', new = ' || :new.status
);
end;
DBMS_ALERT example: in Scott's schema, I want to notify my stored procedure that something has changed in the EMP table and then do something (I'll just display the message).
First, create a triggger; alert name is alert_emp and will be used later in the stored procedure:
SQL> create or replace trigger trg_au_emp
2 after update on emp
3 for each row
4 begin
5 dbms_alert.signal
6 ('alert_emp', 'Salary changed for ' || :new.ename ||
7 ' from ' || :old.sal ||
8 ' to ' || :new.sal);
9 end;
10 /
Trigger created.
The procedure:
SQL> create or replace procedure p_test is
2 l_msg varchar2(200);
3 l_status number;
4 begin
5 dbms_alert.register ('alert_emp');
6 dbms_alert.waitone ('alert_emp', l_msg, l_status);
7 dbms_output.put_line(l_msg ||': '|| l_status);
8 end;
9 /
Procedure created.
Now, execute the procedure:
SQL> exec p_test;
Here, it is just waiting for something to happen in the EMP table. In another session I'm updating the table. Commit is obligatory; otherwise, nothing happens. p_test will still be waiting.
update emp set sal = 1000 where empno = 7369;
commit;
In the first session, once commit is being executed, screen shows this:
PL/SQL procedure successfully completed.
Salary changed for SMITH from 800 to 1000: 0
PL/SQL procedure successfully completed.
SQL>

Related

How to call procedure using triggers

Table:
create table department(deptno number, deptname varchar2(50), deptloc varchar2(50));
insert into department values(1,'A','X');
insert into department values(2,'B','Y');
insert into department values(3,'C','Z');
Stored procedure :
create or replace procedure secure_dml(i_month IN varchar2)
is
begin
if i_month <> 'March' then
dbms_output.put_line('You can modify or add a department only at the end of a financial year');
else
--should I write insert/update DML statement?
end;
Trigger :
create or replace trigger tr_check_dept before insert on department
begin
dbms_output.put_line('Record inserted');
end;
Requirement :
Implement the following business rule with the help of a Procedure and a Trigger :-
i. Changes to the data in the Department table, will be allowed only in the month of March.
ii. Create a procedure named SECURE_DML that prevents the DML statement from executing in any other month other than March. In case, if a user tries to modify the table in any other month apart from March, the procedure should display a message
“You can modify or add a department only at the end of a financial year”
iii. Create a statement level trigger named TR_CHECK_DEPT on the Department table that calls the above procedure.
iv. Test it by inserting a new record in the Department table
Basically, you could do everything within a trigger, but OK - that's some kind of a homework. Here's how I understood it.
Procedure doesn't do anything "smart", just displays the message. Note that DBMS_OUTPUT.PUT_LINE call displays a message, it doesn't prevent anyone to do anything - instead of it, you should raise_application_error.
The answer to your question
should I write insert/update DML statement?
is - in my opinion - NO, you shouldn't.
Trigger calls that procedure. Yours doesn't check the month, while it should (i.e. move that control from procedure to trigger).
Everything put together might look like this:
SQL> create or replace procedure secure_dml
2 is
3 begin
4 raise_application_error(-20000,
5 'You can modify or add a department only at the end of a financial year');
6 end;
7 /
Procedure created.
SQL> create or replace trigger tr_check_dept
2 before insert on department
3 for each row
4 begin
5 if extract(month from sysdate) <> 3 then
6 secure_dml;
7 end if;
8 end;
9 /
Trigger created.
SQL> insert into department(deptno, deptname, deptloc)
2 values (4, 'D', 'W');
insert into department(deptno, deptname, deptloc)
*
ERROR at line 1:
ORA-20000: You can modify or add a department only at the end of a financial year
ORA-06512: at "SCOTT.SECURE_DML", line 4
ORA-06512: at "SCOTT.TR_CHECK_DEPT", line 3
ORA-04088: error during execution of trigger 'SCOTT.TR_CHECK_DEPT'
SQL>
Just for testing purposes, as it is September today, let's modify trigger code so that it works for this month (instead of March) and see what INSERT does in that case.
SQL> create or replace trigger tr_check_dept
2 before insert on department
3 for each row
4 begin
5 if extract(month from sysdate) <> 9 then --> this line was changed
6 secure_dml;
7 end if;
8 end;
9 /
Trigger created.
SQL> insert into department(deptno, deptname, deptloc)
2 values (4, 'D', 'W');
1 row created.
SQL>
Right; now it works.

To display data using cursors in pl/sql

I have written this code to 'display the department names from department table using cursors'
declare
v_dname department.department_name%type;
cursor dept_cursor is select department_name from department;
begin
open dept_cursor;
loop
fetch dept_cursor into v_dname;
exit
when dept_cursor%notfound;
dbms_output.put_line('Department names are :' || v_dname);
end loop;
close dept_cursor;
end;
/
This code runs fine and shows shows 'the procedure is created', but the output values are not being displayed. I tried running the 'dbms_output.put_line' statement alone, it worked. I don't know what else to check. Please help, and thanks in advance!
Did you SET SERVEROUTPUT ON? If not literally, then enable it in your GUI. Because, code itself looks (and works) OK. I don't have your table, but Scott's DEPT is OK for testing as well.
Your code, unmodified (apart from DEPARTMENT being changed to DEPT):
SQL> set serveroutput on --> did you do this?
SQL>
SQL> declare
2 v_dname dept.dname%type;
3
4 cursor dept_cursor is select dname from dept;
5 begin
6 open dept_cursor;
7
8 loop
9 fetch dept_cursor into v_dname;
10
11 exit when dept_cursor%notfound;
12 dbms_output.put_line ('Department names are :' || v_dname);
13 end loop;
14
15 close dept_cursor;
16 end;
17 /
Department names are :ACCOUNTING
Department names are :RESEARCH
Department names are :SALES
Department names are :OPERATIONS
PL/SQL procedure successfully completed.
SQL>
If it still doesn't work, check whether table contains any rows.
One more thing: you said
This code runs fine and shows shows 'the procedure is created'
This isn't actually an Oracle message so I'm not sure whether I'm interpreting it correctly, but: if you actually created a stored procedure (what you posted is an anonymous PL/SQL block), message says Procedure created. It, furthermore, means that you have to actually execute it to get some result.
For example, if procedure's name was p_show_dept, you'd
SQL> set serveroutput on
SQL>
SQL> begin --> executing the procedure
2 p_show_dept;
3 end;
4 /
Department names are :ACCOUNTING
Department names are :RESEARCH
Department names are :SALES
Department names are :OPERATIONS
PL/SQL procedure successfully completed.
SQL>

Oracle Trigger To Check Values On Insert & Update

I am trying to check a value-gap crossed with each other or not. Let me explain with a quick scenario.
Rec 1 : Company AA : Distance Gap -> 100 - 200
Rec 2 : Company AA : Distance Gap -> 200 - 300 VALID
Rec 3 : Company AA : Distance Gap -> 250 - 450 INVALID
Rec 4 : Company JL : Distance Gap -> 250 - 450 VALID
Rec 3 Invalid because it is between REC 2's distance values.
Rec 4 Valid because company is different
Thus I wrote a trigger to prevent it.
create or replace trigger ab_redemption_billing_mpr
after insert or update on redemption_billing_mpr
for each row
declare
v_is_distance_range_valid boolean;
begin
v_is_distance_range_valid := p_redemption_billing.is_distance_range_valid(:new.id,
:new.redemption_billing_company,
:new.distance_min,
:new.distance_max,
'redemption_billing_mpr');
if not v_is_distance_range_valid then
raise_application_error(-20001, 'This is a custom error');
end if;
end ab_redemption_billing_mpr;
FUNCTION:
function is_distance_range_valid(p_id in number,
p_company in varchar2,
p_distance_min in number,
p_distance_max in number,
p_table_name in varchar2) return boolean is
d_record_number number;
begin
execute immediate 'select count(*) from ' || p_table_name || ' r
where r.redemption_billing_company = :1
and (:2 between r.distance_min and r.distance_max or :3 between r.distance_min and r.distance_max)
and r.id = nvl(:4, id)'
into d_record_number
using p_company, p_distance_min, p_distance_max, p_id;
if (d_record_number > 0) then
return false;
else
return true;
end if;
end;
is_distance_range_valid() works just as I expected. If it returns false, that means range check is not valid and don't insert or update.
When I create a scenario to catch this exception, oracle gives
ORA-04091: table name is mutating, trigger/function may not see it
and it points select count(*) line when I click debug button.
I don't know why I am getting this error. Thanks in advance.
Just check whether the below approach resolves your issue
Create a log table with columns required for finding the is_distance_range_valid validation and In your trigger insert into this log tab.The trigger on main table has to be a before insert or update trigger
Create a trigger on this log table and do the validation in the log table trigger and raise error.The trigger on log table has to be an after insert or update trigger.
Also this will only work if the row is already existing in the main table and it is not part of the current insert or update. If validation of the current insert or update is required then we need to use the :new.column_name to do the validation
Test:-
create table t_trg( n number);
create table t_trg_log( n number);
create or replace trigger trg_t
before insert or update on t_trg
for each row
declare
l_cnt number;
begin
insert into t_trg_log values(:new.n);
end trg_t;
create or replace trigger trg_t_log
after insert or update on t_trg_log
for each row
declare
l_cnt number;
begin
select count(1) into l_cnt from t_trg
where n=:new.n;
if l_cnt > 0 then
raise_application_error(-20001, 'This is a custom error');
end if;
end trg_t_log;
The first time I insert it doesn't throw error
insert into t_trg values(7);
1 row inserted.
The second time I execute, I get the custom error
insert into t_trg values(7);
Error report -
ORA-20001: This is a custom error
ORA-06512: at "TRG_T_LOG", line 7
ORA-04088: error during execution of trigger 'TRG_T_LOG'
ORA-06512: at "TRG_T", line 4
ORA-04088: error during execution of trigger 'TRG_T'
Update:-Using compound trigger the error is thrown in the first time the insert is done since it also takes into account the current row that we are updating or inserting while doing the SELECT
First I want to thanks to psaraj12 for his effort.
I found solution. Oracle forces us to not use select query before each row.
Oracle trigger error ORA-04091
So I wrote this and it works.
create or replace trigger ab_redemption_billing_mpr
for insert or update on redemption_billing_mpr
compound trigger
v_is_distance_range_valid boolean;
id redemption_billing_mpr.id%type;
redemption_billing_company redemption_billing_mpr.redemption_billing_company%type;
distance_min redemption_billing_mpr.distance_min%type;
distance_max redemption_billing_mpr.distance_max%type;
after each row is
begin
id := :new.id;
redemption_billing_company := :new.redemption_billing_company;
distance_min := :new.distance_min;
distance_max := :new.distance_max;
end after each row;
after statement is
begin
v_is_distance_range_valid := p_redemption_billing.is_distance_range_valid(id,
redemption_billing_company,
distance_min,
distance_max,
'redemption_billing_mpr');
if not v_is_distance_range_valid then
raise_application_error(-20001, 'This is a custom error');
end if;
end after statement;
end ab_redemption_billing_mpr;
We must use compound trigger to deal with it.

Oracle procedure input is comma delimited, not returning any values

the procedure Im working has an input variable that is comma delimited. As of right now when I go to run a test script, I dont get any values back. Here is what I have so far.
procedure get_patient(
p_statusmnemonic_in in membermedicalreconcilationhdr.reconciliationstatusmnemonic%type,
p_return_cur_out out sys_refcursor,
p_err_code_out out number,
p_err_mesg_out out varchar2)
is
begin
open p_return_cur_out for
select h.primarymemberplanid,
h.assigneduserid,
h.accountorgid,
h.reconciliationstatusmnemonic,
h.estimatedenddt,
h.actualenddt,
h.inserteddt,
h.insertedby,
h.updateddt,
h.updatedby
from membermedicalreconcilationhdr h
where h.reconciliationstatusmnemonic in (p_statusmnemonic_in);
p_err_code_out := 0;
exception
when others then
p_err_code_out := -1;
p_err_mesg_out := 'error in get_patient=> ' || sqlerrm;
end get_patient;
Here is the test script:
set serveroutput on
declare
type tempcursor is ref cursor;
v_cur_result tempcursor;
errcode number;
errmesg varchar2(1000);
p_primarymemberplanid_in membermedicalreconcilationhdr.primarymemberplanid%type;
p_assigneduserid_in membermedicalreconcilationhdr.assigneduserid%type;
p_accountorgid_in membermedicalreconcilationhdr.accountorgid%type;
p_reconstatusmnemonic_in membermedicalreconcilationhdr.reconciliationstatusmnemonic%type;
p_estimatedenddt_in membermedicalreconcilationhdr.estimatedenddt%type;
p_actualenddt_in membermedicalreconcilationhdr.actualenddt%type;
p_inserteddate_in membermedicalreconcilationhdr.inserteddt%type;
p_insertedby_in membermedicalreconcilationhdr.insertedby%type;
p_updateddate_in membermedicalreconcilationhdr.updateddt%type;
p_updatedby_in membermedicalreconcilationhdr.updatedby%type;
begin
get_patient
('COMPLETE,SUSPENDED_PRIOR_TO_COMPARE',v_cur_result, errcode, errmesg);
--('COMPLETE',v_cur_result, errcode, errmesg);
loop
fetch v_cur_result into p_primarymemberplanid_in,p_assigneduserid_in,p_accountorgid_in,p_reconstatusmnemonic_in,
p_estimatedenddt_in,p_actualenddt_in,p_inserteddate_in,p_insertedby_in,
p_updateddate_in,p_updatedby_in;
dbms_output.put_line(' planid '||p_primarymemberplanid_in||' userid '||p_assigneduserid_in);
exit when v_cur_result%notfound;
end loop;
dbms_output.put_line(' error code '||errcode||' message '||errmesg);
end;
As of right now I get values back when I just have one input value, but when I try to do two I dont get anything. Ive done research and it looks like my select statement is correct so Im at a loss as to what Im doing wrong. Any help is appreciated, thanks.
If you can change the definition of the procedure, you are better served passing in a proper collection.
CREATE TYPE status_tbl IS TABLE OF VARCHAR2(100);
procedure get_patient(
p_statusmnemonic_in in status_tbl,
p_return_cur_out out sys_refcursor,
p_err_code_out out number,
p_err_mesg_out out varchar2)
is
begin
open p_return_cur_out for
select h.primarymemberplanid,
h.assigneduserid,
h.accountorgid,
h.reconciliationstatusmnemonic,
h.estimatedenddt,
h.actualenddt,
h.inserteddt,
h.insertedby,
h.updateddt,
h.updatedby
from membermedicalreconcilationhdr h
where h.reconciliationstatusmnemonic in (SELECT *
FROM TABLE(p_statusmnemonic_in));
...
Otherwise, you would either have to resort to using dynamic SQL (which would have security and performance implications) or you would need to write code to parse the comma-separated string into a collection and then use the TABLE operator to use that collection in the query.
Assuming you modify the signature of the procedure, the call will also have to change so that you are passing in a collection.
get_patient
(status_tbl('COMPLETE','SUSPENDED_PRIOR_TO_COMPARE'),
v_cur_result,
errcode,
errmesg);
And just to point it out, writing procedures that have error code and error message OUT parameters rather than throwing exceptions is generally highly frowned upon. It makes far more sense to eliminate those parameters and to just throw exceptions when you encounter an error. Otherwise, you are relying on every caller to every procedure to correctly check the returned status code and message (which your sample code does not do). And you are losing a ton of valuable information about things like exactly what line an error occurred on, what the error stack was, etc.
Since you don't post your table definitions or your sample data, it is impossible for us to test this code. Here is a quick demonstration, though, of how it would work
SQL> create table patient (
2 patient_id number primary key,
3 status varchar2(10),
4 name varchar2(100)
5 );
Table created.
SQL> insert into patient values( 1, 'COMPLETE', 'Justin' );
1 row created.
SQL> insert into patient values( 2, 'SUSPENDED', 'Bob' );
1 row created.
SQL> insert into patient values( 3, 'NEW', 'Kerry' );
1 row created.
SQL> commit;
Commit complete.
SQL> CREATE TYPE status_tbl IS TABLE OF VARCHAR2(100);
2 /
Type created.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure get_patients( p_statuses in status_tbl,
2 p_cursor out sys_refcursor )
3 as
4 begin
5 open p_cursor
6 for select *
7 from patient
8 where status in (select *
9 from table( p_statuses ));
10* end;
SQL> /
Procedure created.
SQL> variable rc refcursor;
SQL> exec get_patients( status_tbl('COMPLETE', 'SUSPENDED'), :rc );
PL/SQL procedure successfully completed.
SQL> print rc;
PATIENT_ID STATUS
---------- ----------
NAME
--------------------------------------------------------------------------------
1 COMPLETE
Justin
2 SUSPENDED
Bob

ORACLE Mutating trigger error [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
ORACLE After update trigger: solving ORA-04091 mutating table error
So I have a trigger to check if a an admin has been locked out of login (if they are they will have a 1 set to temp_pw. It then send the admin a four digit pass code to unlock their account. Problem is I update the failed_logins field, incrementing it by 1 for every failed login before the trigger is called.
The rest of the trigger checks if there is an admin has a locked account before sending them an email with a pass code.
If I take out the Update Pi_admin_table set blah blah it sends the email but if I include it to insert the new pass code in the table it errors with this:
Message: 60 ORA-00060: deadlock detected while waiting for resource
ORA-06512: at "PI_USER_ADMIN.TR_ADMIN_LOCKOUT", line 17
ORA-04088: error during execution of trigger
'PI_USER_ADMIN.TR_ADMIN_LOCKOUT' UPDATE *pi_admin_table SET
failed_logins = failed_logins + 1 where
EMAIL='nathan#perceptive.co.uk' returning failed_logins into :bind_var
Here's my trigger:
create or replace
TRIGGER "TR_ADMIN_LOCKOUT"
AFTER UPDATE ON PI_ADMIN_TABLE
for each row
declare
-- pragma autonomous_transaction seems to fix trigger mutation errors.
-- Look at rewriting trigger later.
--pragma autonomous_transaction;
tempEmail varchar2(80 BYTE);
tempID varchar2(80 BYTE);
mail_host varchar2(255);
mail_port varchar2(255);
mail_from varchar2(255);
tempPW int;
begin
SELECT EMAIL, ADMINID
into tempEmail, tempID
from pi_admin_table
where TEMP_PW = :NEW.TEMP_PW;
SELECT MAIL_HOST, MAIL_PORT, MAIL_FROM
into mail_host, mail_port, mail_from
from pi_settings_table;
select dbms_random.value(1,10000)
into tempPW
from dual;
if tempEmail IS NOT NULL then
UPDATE PI_ADMIN_TABLE SET RESET_PW=round(tempPW) where adminid=tempID;
send_mail(tempEmail,
mail_host,
mail_port,
mail_from,
'Locked Out Event',
'Your administrator account was locked out. '|| chr(10) || chr(10) ||
'Please use this four digit pass code next time try to log in' ||
chr(10) || chr(10) ||
'Temp pass code: '|| round(tempPW) );
end if;
END;
Oracle does not allow code in a ROW trigger to issue a SELECT, INSERT, UPDATE, or DELETE against the table on which the trigger is defined. Your choices are to use an AUTONOMOUS TRANSACTION (but see the warning at the post referenced in #Ben's comment above) or use a COMPOUND TRIGGER.
Share and enjoy.
I would recommend you not to use trigger for that task. Encapsulate the logic you're trying to achieve in stored procedure.

Resources