oracle-databaseplsqldatabase-trigger

PL/SQL trigger not working


I've created a table like this:

CREATE TABLE table_name (
name     VARCHAR2(20)
);

After that, I've created a trigger, which before every insert, has to write the users name:

SET SERVEROUTPUT ON;

CREATE OR REPLACE TRIGGER bi_trigger
BEFORE INSERT ON table_name
FOR EACH ROW
ENABLE
DECLARE
v_user      VARCHAR2(20);
BEGIN
SELECT user INTO v_user FROM dual;
DBMS_OUTPUT.PUT_LINE('You inserted a row, ' || v_user);
END;

But, after inserting something into my table, the requested line with the user's name doesn't appear. What am I missing?

INSERT INTO table_name VALUES('qwerty');

Solution

  • I see two potential problems.

    One is that it's not clear if you're actually creating the trigger. In the sample code you've shown, you need a forward slash (/) following the trigger text to actually execute the CREATE statement. You should see "Trigger created" if it is created successfully.

    The other is that you are enabling SERVEROUTPUT prior to creating the trigger, which is irrelevant. You need to enable it in the session where the INSERT statement is executed. (If you are executing the INSERT in the same session as the CREATE, this is not the problem.)

    (The other answer implies you aren't seeing the output because the trigger is executed outside your session. This is incorrect.)