表值函数 (TVF) 调用
适用于: Databricks SQL Databricks Runtime
调用一个函数,该函数返回一个关系或一组行作为 [table-reference](sql-ref
TVF 可以是:
SQL 用户定义的表函数。
range 表值函数。
任何表值生成器函数,例如 explode。
适用于: Databricks SQL Databricks Runtime 12.2 LTS 及更高版本。
语法
function_name ( [ expression [, ...] ] ) [ table_alias ]
参数
function_name
表值函数。
-
生成值的一个或多个值、运算符和 SQL 函数的组合。
table_alias
用于引用函数结果及其列的可选标签。
示例
-- range call with end
> SELECT * FROM range(6 + cos(3));
0
1
2
3
4
-- range call with start and end
> SELECT * FROM range(5, 10);
5
6
7
8
9
-- range call with numPartitions
> SELECT * FROM range(0, 10, 2, 200);
0
2
4
6
8
-- range call with a table alias
> SELECT * FROM range(5, 8) AS test;
5
6
7
-- Create a SQL UDTF and invoke it
> CREATE OR REPLACE FUNCTION table_func(a INT) RETURNS TABLE
RETURN SELECT a * c1 AS res FROM VALUES(1), (2), (3), (4) AS T(c1)
> SELECT * FROM table_func(5);
5
10
15
20
-- Using lateral correlation
> SELECT table_func.res FROM VALUES(10), (20) AS S(c1), LATERAL table_func(c1);
10
20
20
40
30
60
40
80
-- Scalar fucntion are not allowed in the FROM clause
> SELECT * FROM trim('hello ');
Error
在 Databricks SQL 和 Databricks Runtime 12.2 LTS 及更高版本上:
> SELECT * FROM explode(array(10, 20));
10
20
> SELECT * FROM inline(array(struct(1, 'a'), struct(2, 'b')));
col1 col2
---- ----
1 a
2 b
> SELECT * FROM posexplode(array(10,20));
pos col
--- ---
0 10
1 20
> SELECT * FROM stack(2, 1, 2, 3);
col0 col1
---- ----
1 2
3 null
> SELECT * FROM json_tuple('{"a":1, "b":2}', 'a', 'b');
c0 c1
--- ---
1 2
> SELECT * FROM parse_url('http://spark.apache.org/path?query=1', 'HOST');
spark.apache.org
> SELECT * FROM VALUES(1), (2) AS t1(c1), LATERAL explode (ARRAY(3,4)) AS t2(c2);
c1 c2
-- --
1 3
1 4
2 3
2 4