Categories:

Context functions (General)

SYS_CONTEXT(SNOWFLAKE$SESSION_ATTRIBUTES 命名空间)

Returns a custom session attribute that was set using SET_SYS_CONTEXT in the SNOWFLAKE$SESSION_ATTRIBUTES namespace.

自定义会话属性一经设置便不可变,并在会话持续期间一直存在。它们对于跟踪有关会话的元数据非常有用,例如应用程序上下文、用户属性或审计信息。

See also:

SYS_CONTEXT , SET_SYS_CONTEXT

语法

SYS_CONTEXT(
  'SNOWFLAKE$SESSION_ATTRIBUTES' ,
  '<key>'
)

实参

'SNOWFLAKE$SESSION_ATTRIBUTES'

指定要检索自定义会话属性。

'key'

要检索的自定义属性的名称。属性名称 区分大小写

返回

该函数会返回 VARCHAR 值:

  • The value of the specified attribute if it has been set in the current session using SET_SYS_CONTEXT.
  • 如果尚未设置该属性,则返回 NULL。

访问控制要求

检索自定义会话属性不需要特殊权限。任何用户都可以从其自己的会话中检索属性。

使用说明

  • Attributes must be set using SET_SYS_CONTEXT before they can be retrieved.
  • Attribute names are case-sensitive. app_context and APP_CONTEXT are treated as different attributes.
  • 属性的范围限定在会话内,对其他会话不可见。
  • If you are specifying the function call in a double-quoted string in a shell, escape the $ character with a backslash (\) so that $session_attributes is not interpreted as a shell variable.

示例

以下示例设置了一个自定义属性,然后对其进行检索:

-- Set a custom session attribute
CALL SET_SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'app_context', 'production');

-- Retrieve the custom attribute
SELECT SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'app_context');
+---------------------------------------------------------------+
| SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'app_context')   |
%---------------------------------------------------------------%
| production                                                    |
+---------------------------------------------------------------+

检索尚未设置的属性会返回 NULL:

SELECT SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'nonexistent_attr');
+------------------------------------------------------------------+
| SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'nonexistent_attr') |
%------------------------------------------------------------------%
| NULL                                                             |
+------------------------------------------------------------------+

属性名称区分大小写:

-- Set attributes with different cases
CALL SET_SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'mykey', 'lowercase');
CALL SET_SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'MyKey', 'mixedcase');
CALL SET_SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'MYKEY', 'uppercase');

-- Each is a distinct attribute
SELECT
  SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'mykey') AS lower,
  SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'MyKey') AS mixed,
  SYS_CONTEXT('SNOWFLAKE$SESSION_ATTRIBUTES', 'MYKEY') AS upper;
+-----------+-----------+-----------+
| LOWER     | MIXED     | UPPER     |
|-----------+-----------+-----------|
| lowercase | mixedcase | uppercase |
+-----------+-----------+-----------+