声明变量

描述

DECLARE VARIABLE 语句用于在 Spark 中创建临时变量。临时变量的作用域为会话级别。

您可以在允许常量表达式的任何地方通过变量名引用变量。除非您使用 sessionsystem.session 限定变量,否则 Spark 只有在无法将名称解析为列或列别名时,才会解析变量。

临时变量不能在持久化对象中引用,例如持久化视图、列默认表达式和生成列表达式。

语法

DECLARE [ OR REPLACE ] [ VAR | VARIABLE ]
    variable_name [ data_type ] [ { DEFAULT | = } default_expr ]

参数

示例

-- The dense form of declaring a variable with default
DECLARE five = 5;

-- Declare a defined variable
DECLARE five = 55;
[VARIABLE_ALREADY_EXISTS] Cannot create the variable `system`.`session`.`five` because it already exists.
Choose a different name, or drop or replace the existing variable. SQLSTATE: 42723

-- Use `DECLARE OR REPLACE` to declare a defined variable
DECLARE OR REPLACE five = 55;

-- Explicitly declare the default value of a variable using the keyword `DEFAULT`
DECLARE VARIABLE size DEFAULT 6;

-- STRING variable initialized to `NULL`
DECLARE some_var STRING;