简体   繁体   中英

Execute a stored procedure through a trigger right after a user was created on the database

I would like to write a procedure can grant role permissions to a new created user.

My thoughts were that I first create a procedure like this:

CREATE OR REPLACE PROCEDURE P_CREATE_USER

BEGIN
EXECUTE IMMEDIATE 'GRANT RESOURCE TO'||ora_dict_obj_name;
EXECUTE IMMEDIATE 'GRANT CONNECT TO'||ora_dict_obj_name;

END;
/

Then, I create a trigger, which execute this procedure, after a user is created on the database. Like this:

CREATE OR REPLACE TRIGGER T_CREATE_USER
AFTER CREATE ON DATABASE
WHEN (ora_dict_obj_type = 'USER')

BEGIN
  P_CREATE_USER;
END;
/

It did not really work, do you have other suggestions?

I use Oracle as DBMS.

So the problem is this: your trigger throws ORA-30511: invalid DDL operation in system triggers .

The reason is, we cannot commit in triggers. DDL issues implicit commits (before and after the statement). So there is no way your trigger can work, nor could it ever have worked.

The workaround for commits in triggers is pragma AUTONOMOUS TRANSACTION , which causes the trigger to operate in an isolated session. That won't here because the freshly created user won't be visible in the autonomous session.

The best approach you can get to encapsulate the logic would be this:

CREATE OR REPLACE PROCEDURE P_CREATE_USER
   (p_user_name in varchar2
    , p_password in varchar2)
is
BEGIN
    EXECUTE IMMEDIATE ' create user '||p_user_name ||' identified by '||p_password;
    EXECUTE IMMEDIATE 'GRANT RESOURCE TO'||p_user_name ;
    EXECUTE IMMEDIATE 'GRANT CONNECT TO'||p_user_name ;

END;
/

In SQL server a user, such as you can execute a procedure to grant SQL permission to a newly created user. The condition to make this work is that the user's account, such as your account need 'With Grant' to that SQL permission in order to be able to grant other new user this SQL permission

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM