DuckDB 支持使用 SET VARIABLE
和 RESET VARIABLE
语句定义 SQL 级别的变量。
SET VARIABLE
SET VARIABLE
语句用于为变量赋值,该变量可以通过 getvariable
调用访问:
SET VARIABLE my_var = 30;
SELECT 20 + getvariable('my_var') AS total;
总计 |
---|
50 |
如果对现有变量调用SET VARIABLE
,它将覆盖其值:
SET VARIABLE my_var = 30;
SET VARIABLE my_var = 100;
SELECT 20 + getvariable('my_var') AS total;
总计 |
---|
120 |
变量可以有不同的类型:
SET VARIABLE my_date = DATE '2018-07-13';
SET VARIABLE my_string = 'Hello world';
SET VARIABLE my_map = MAP {'k1': 10, 'k2': 20};
变量也可以被分配给查询结果:
-- write some CSV files
COPY (SELECT 42 AS a) TO 'test1.csv';
COPY (SELECT 84 AS a) TO 'test2.csv';
-- add a list of CSV files to a table
CREATE TABLE csv_files(file VARCHAR);
INSERT INTO csv_files VALUES ('test1.csv'), ('test2.csv');
-- initialize a variable with the list of csv files
SET VARIABLE list_of_files = (SELECT LIST(file) FROM csv_files);
-- read the CSV files
SELECT * FROM read_csv(getvariable('list_of_files'), filename := True);
a | 文件名 |
---|---|
42 | test.csv |
84 | test2.csv |
如果变量未设置,getvariable
函数将返回 NULL
:
SELECT getvariable('undefined_var') AS result;
result |
---|
NULL |
getvariable
函数也可以在 COLUMNS
表达式 中使用:
SET VARIABLE column_to_exclude = 'col1';
CREATE TABLE tbl AS SELECT 12 AS col0, 34 AS col1, 56 AS col2;
SELECT COLUMNS(c -> c != getvariable('column_to_exclude')) FROM tbl;
列0 | 列2 |
---|---|
12 | 56 |
Syntax
RESET VARIABLE
RESET VARIABLE
语句用于取消设置一个变量。
SET VARIABLE my_var = 30;
RESET VARIABLE my_var;
SELECT getvariable('my_var') AS my_var;
my_var |
---|
NULL |