> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# SET ROLE

> SET ROLE activates roles, along with all of its associated privileges and nested roles, for the current session.

## 功能

在当前会话下，激活当前用户拥有权限的角色。激活后，用户可以使用该角色进行相关操作。

您可以使用 `select is_role_in_session("<role_name>")` 来检查指定角色在当前会话下是否已经被激活。

该命令从 3.0 版本开始支持。

## 注意事项

* 用户只能激活自己已有权限的角色。

* 用户可以通过 [SHOW GRANTS](/documents/cn/4.2/sql-reference/sql-statements/account-management/SHOW_GRANTS.md) 查看拥有的角色，可以通过[SELECT CURRENT\_ROLE](/documents/cn/4.2/sql-reference/sql-functions/utility-functions/current_role.md) 查看当前激活的角色。

* 激活的角色会影响所有权限检查,包括对 `information_schema` 系统视图的查询。例如,执行 `SET ROLE role1` 后,查询 `SELECT * FROM information_schema.tables` 将只返回通过 `role1` 可访问的表。这确保了基于角色的访问控制在所有系统目录和元数据查询中得到一致应用。

## 语法

```SQL theme={null}
-- 激活特定角色，使用这个角色进行操作。
SET ROLE <role_name>[,<role_name>,..];
-- 激活除指定角色之外，用户拥有的所有角色。
SET ROLE ALL EXCEPT <role_name>[,<role_name>,..]; 
-- 激活用户拥有的所有角色。
SET ROLE ALL;
```

## 参数说明

`role_name`: 用户拥有的角色名。

## 示例

1. 查看当前用户拥有的角色。

   ```SQL theme={null}
   SHOW GRANTS;
   +--------------+---------+----------------------------------------------+
   | UserIdentity | Catalog | Grants                                       |
   +--------------+---------+----------------------------------------------+
   | 'test'@'%'   | NULL    | GRANT 'db_admin', 'user_admin' TO 'test'@'%' |
   +--------------+---------+----------------------------------------------+
   ```

2. 激活 `db_admin` 角色。

   ```plain theme={null}
   SET ROLE db_admin;
   ```

3. 查看当前生效的角色。

   ```SQL theme={null}
   SELECT CURRENT_ROLE();
   +--------------------+
   | CURRENT_ROLE()     |
   +--------------------+
   | db_admin           |
   +--------------------+
   ```

## 相关文档

* [CREATE ROLE](/documents/cn/4.2/sql-reference/sql-statements/account-management/CREATE_ROLE.md): 创建角色。
* [GRANT](/documents/cn/4.2/sql-reference/sql-statements/account-management/GRANT.md): 将角色分配给用户或其他角色。
* [ALTER USER](/documents/cn/4.2/sql-reference/sql-statements/account-management/ALTER_USER.md): 修改角色。
* [SHOW ROLES](/documents/cn/4.2/sql-reference/sql-statements/account-management/SHOW_ROLES.md): 查看当前系统所有角色。
* [current\_role](/documents/cn/4.2/sql-reference/sql-functions/utility-functions/current_role.md): 查看当前用户拥有的角色。
* [is\_role\_in\_session](/documents/cn/4.2/sql-reference/sql-functions/utility-functions/is_role_in_session.md)
* [DROP ROLE](/documents/cn/4.2/sql-reference/sql-statements/account-management/DROP_ROLE.md): 删除角色。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.