Oracle数据库创建只读用户并批量授权

Oracle数据库创建只读用户并批量授权

𝓓𝓸𝓷 Lv6

授权只读访问某个用户下的数据

一、创建角色

1
create role select_all_qxphis_table;

二、将qxphis用户的表授权给角色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
declare

cursor c_tabname is select table_name from dba_tables where owner='QXPHIS';
v_tabname dba_tables.table_name%TYPE;

sqlstr varchar2(200);

begin

open c_tabname;

loop
fetch c_tabname into v_tabname;
exit when c_tabname%NOTFOUND;
sqlstr:='grant select on qxphis.'||v_tabname||' to select_all_qxphis_table';

execute immediate sqlstr;

end loop;

close c_tabname;

end;

/

三、将角色授予给qxphis

1
2
3
4
5
6
7
8
9
grant select_all_qxphis_table to qxphis with admin option;

---如果不使用角色,可以使用以下类似SQL将表批量授权给只读用户:
BEGIN
FOR tbl IN (SELECT table_name FROM all_tables WHERE owner = 'HR') LOOP
EXECUTE IMMEDIATE 'GRANT SELECT ON HR.' || tbl.table_name || ' TO read_only_user';
END LOOP;
END;
/

四、创建同义词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
declare

cursor c_tabname is select table_name from dba_tables where owner='QXPHIS';
v_tabname dba_tables.table_name%TYPE;

sqlstr varchar2(200);

begin

open c_tabname;

loop
fetch c_tabname into v_tabname;
exit when c_tabname%NOTFOUND;
sqlstr:='create or replace synonym qxphis.'||v_tabname||' for qxphis.'||v_tabname||'';

execute immediate sqlstr;

end loop;

close c_tabname;

end;

/

五、授权其它权限

1
2
---如果只读用户需要访问数据字典,可以授权访问数据字典权限
GRANT SELECT ANY DICTIONARY TO readonly_user;
  • Title: Oracle数据库创建只读用户并批量授权
  • Author: 𝓓𝓸𝓷
  • Created at : 2025-05-08 16:39:23
  • Updated at : 2025-05-09 16:40:00
  • Link: https://www.zhangdong.me/oracle-create-readonly-user.html
  • License: This work is licensed under CC BY-NC-SA 4.0.
评论