问题
I want to create a trigger to display the message “NEW EMPLOYEE DETAILS INSERTED”, whenever a new record is inserted into Employee table, and have this code for it-
set serveroutput on;
create or replace trigger display_message
after insert or update on employee
for each row
when(new.emp_id>0)
begin
dbms_output.put_line('new employee details inserted');
end;
But this isn't giving me any output. Please help, thanks in advance!
回答1:
It won't work only if EMP_ID
isn't larger than 0
. Is it? In my case, it works:
Sample table:
SQL> CREATE TABLE employee
2 (
3 emp_id NUMBER
4 );
Table created.
Trigger:
SQL> CREATE OR REPLACE TRIGGER display_message
2 AFTER INSERT OR UPDATE
3 ON employee
4 FOR EACH ROW
5 WHEN (new.emp_id > 0)
6 BEGIN
7 DBMS_OUTPUT.put_line ('new employee details inserted');
8 END;
9 /
Trigger created.
Testing:
SQL> SET SERVEROUTPUT ON;
SQL> INSERT INTO employee (emp_id)
2 VALUES (100);
new employee details inserted --> the message is here!
1 row created.
SQL>
回答2:
This is a very poor use of a trigger. And even worse use of dbms_output. PL/SQL has zero ability to interact with output devices on the client. Therefore the output of dbms_output.put_line is not written to your screen. It is written to a buffer, to be processed - or not - by the client. Some client processes are totally oblivious to the existence of this buffer. Others, like sqlplus or SQL Developer, know of it, but have to be told to process and display it. With sqlplus that is via 'set serverout on'.
All that to say, dbms_output is a good debugging tool, but should never be relied upon on in an actual production application. You need to reconsider why you even want this. If you execute an INSERT from any application it will either succeed or fail. If it fails, oracle will put an error on the stack that will be reported by the client. If you get no error, then you know it succeeded. Why do you need this message at all?
来源:https://stackoverflow.com/questions/64445495/trigger-to-display-message-using-pl-sql