首先,连接到数据库以开始操作: ```sql SQL> conn system/oracle Connected. ``` 接下来,创建两个角色r1和r2,其中r2需要通过密码验证: ```sql SQL> create role r1; Role created. SQL> create role r2 identified by oracle; Role created. ``` 为这两个角色分配不同的权限,确保r2拥有比r1更多的权限: ```sql SQL> grant create session, create table, create view to r1; Grant succeeded. SQL> grant create session, create table, create view, create procedure to r2; Grant succeeded. ``` 创建用户tj,并赋予其r1和r2两个角色。默认情况下,用户登录时所有赋予的角色均自动激活: ```sql SQL> create user tj identified by tj quota 10m on users; User created. SQL> grant r1, r2 to tj; Grant succeeded. SQL> conn tj/tj Connected. ``` 检查当前会话的权限和角色: ```sql SQL> select * from session_privs; PRIVILEGE ------------------------------ CREATE SESSION CREATE TABLE CREATE VIEW CREATE PROCEDURE SQL> select * from session_roles; ROLE -------------------------------------------- R1 R2 ``` 为了控制用户登录时的角色,默认角色可以被设置或更改: ```sql SQL> conn system/oracle Connected. SQL> alter user tj default role r1; User altered. SQL> conn tj/tj Connected. SQL> select * from session_roles; ROLE ------------------------------------------------------------ R1 ``` 如果需要临时激活r2角色,必须使用SET ROLE命令并提供相应的密码,因为r2是在创建时设置了密码的: ```sql SQL> set role r2 identified by oracle; Role set. SQL> select * from session_roles; ROLE ------------------------------------------- R2 ``` 此时,r1角色将不再处于活动状态,除非再次显式激活它。这是因为每次只能有一个角色处于活动状态,除非它们之间存在继承关系。这展示了如何通过角色切换来动态地管理用户的权限,从而满足不同的业务需求。