笔记本中的会话上下文

笔记本的会话上下文由您在创建笔记本时定义的角色、仓库、数据库和架构定义。当您运行笔记本时,它会以该角色运行,使用笔记本中定义的仓库,并在包含笔记本的数据库和架构上下文中运行。

本主题介绍如何访问或更改笔记本的会话上下文。

访问笔记本的会话上下文

您可以使用 Python 和 SQL 访问会话上下文。

If you’re using the Snowpark Python library or Snowflake Python APIs, use the get_active_session() method to get the active session context.

from snowflake.snowpark.context import get_active_session
session = get_active_session()

For SQL, you can use the Context functions SQL functions.

SELECT CURRENT_WAREHOUSE(), CURRENT_DATABASE(), CURRENT_SCHEMA();

更改笔记本的会话上下文

您可以更改笔记本的会话上下文以使用不同的角色、数据库和架构和/或仓库:

  • Specify a different role to use with the USE ROLE SQL command.

    • You can check the role in use by the notebook by calling the CURRENT_ROLE function.
    • If you change your role to one that does not have privileges to use the notebook warehouse, database, or schema, queries that require a warehouse or access to the notebook database or schema fail to run. However, you can still run queries that do not use the notebook warehouse, database, and schema.
    • Roles specified with the USE ROLE SQL command do not persist across notebook sessions.
    • If you specify a database or schema that the currently active role does not have privileges to access, queries using that database and schema fail to run.
  • If you run the SQL command USE SECONDARY ROLES to set secondary roles to ALL, the secondary roles associated with your user are used to generate the results of the notebook cells.

  • Specify a different warehouse using the SQL command USE WAREHOUSE.

    • You can check the warehouse in use for the notebook by calling the CURRENT_WAREHOUSE function.
  • Specify a different database or schema using USE DATABASE or USE SCHEMA SQL commands.

    • You can check the database in use for the notebook by calling the CURRENT_DATABASE function.
    • If you reference objects in the notebook database or the database specified in an earlier notebook cell, you can simplify your SQL statements to include only the schema and object that you want to reference, instead of the fully qualified path to the object.