Extracting user DDL and grants
When to use it
When you need to recreate a user in another environment, document its access, or keep a copy before a change.
Run this
Script: user_ddl.sql. Full version in Security › Users and privileges › Users and grants.
-- Configurações para limpar a saída
SET LONG 200000 PAGESIZE 0 HEAD OFF FEEDBACK OFF VERIFY OFF
-- 1. Configura o formato para adicionar o ';' no final dos comandos
EXEC DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', TRUE);
-- 2. Gera o CREATE USER
SELECT DBMS_METADATA.GET_DDL('USER', 'NOME_DO_USUARIO') FROM DUAL;
-- 3. Gera os GRANTS (Privilégios de Sistema e Objetos)
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT', 'NOME_DO_USUARIO') FROM DUAL;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT', 'NOME_DO_USUARIO') FROM DUAL;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT', 'NOME_DO_USUARIO') FROM DUAL;
Script: grants_user.sql. Full version in Security › Users and privileges › Users and grants.
set longchunksize 2000
SET ECHO OFF
set trimspool on
SET PAGESIZE 0
SET LINES 3000
SET LONG 200000
SET FEEDBACK OFF
SET HEADING OFF
SET SERVEROUTPUT ON SIZE 1000000
COLUMN TXT FORMAT a3000 WORD_WRAPPED
EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', TRUE );
SELECT dbms_metadata.get_ddl('USER',USERNAME) FROM dba_users;
SELECT 'GRANT ' || PRIVILEGE || ' TO ' || GRANTEE || ';'
FROM DBA_SYS_PRIVS
WHERE GRANTEE IN ('<Your_User>')
UNION ALL
SELECT 'GRANT ' || GRANTED_ROLE || ' TO ' || GRANTEE || ';'
FROM DBA_ROLE_PRIVS
WHERE GRANTEE IN ('<Your_User>')
UNION ALL
SELECT 'GRANT ' || PRIVILEGE || ' ON ' || OWNER || '.' || TABLE_NAME || ' TO ' || GRANTEE || ';'
FROM DBA_TAB_PRIVS
WHERE GRANTEE IN ('<Your_User>');
How to read the output
- The first script returns the
CREATE USERstatement and then system privileges, roles and object privileges for one user. - If the user has none of one kind, that call raises ORA-31608. This is expected and only means "nothing to show".
- The second script builds plain
GRANTlines from the dictionary views, which is easier to read and compare. - The password in the generated
CREATE USERis a hash, not the clear password. Treat the output as sensitive anyway.
What to do next
- Save the output with the date before any change to a user. It is your rollback.
- Never paste this output into a ticket or a chat without checking it first.
Risk level
GENERATES COMMANDS The script only prints commands. Nothing changes until someone runs that output. Review it line by line first.