Zum Inhalt springen

SET VARIABLE- und RESET VARIABLE-Anweisungen

DuckDB unterstützt die Definition von Variablen auf SQL-Ebene mit den Anweisungen SET VARIABLE und RESET VARIABLE.

Variablen-Scopes

DuckDB unterstützt zwei Ebenen von Variablen-Scopes:

Scope Beschreibung
SESSION Variablen mit SESSION-Scope sind lokal für Sie und betreffen nur die aktuelle Sitzung.
GLOBAL Variablen mit GLOBAL-Scope sind spezielle Konfigurationsoptionsvariablen, die die gesamte DuckDB-Instanz und alle Sitzungen betreffen. Siehe zum Beispiel Eine globale Variable setzen.

SET VARIABLE

Die SET VARIABLE-Anweisung weist einer Variable einen Wert zu, der über den Aufruf getvariable abgerufen werden kann:

SET VARIABLE my_var = 30;
SELECT 20 + getvariable('my_var') AS total;
total
50

Wird SET VARIABLE auf eine vorhandene Variable angewendet, überschreibt sie deren Wert:

SET VARIABLE my_var = 30;
SET VARIABLE my_var = 100;
SELECT 20 + getvariable('my_var') AS total;
total
120

Variablen können unterschiedliche Typen haben:

SET VARIABLE my_date = DATE '2018-07-13';
SET VARIABLE my_string = 'Hello world';
SET VARIABLE my_map = MAP {'k1': 10, 'k2': 20};

Variablen können auch Ergebnissen von Abfragen zugewiesen werden:

-- 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 filename
42 test.csv
84 test2.csv

Wenn eine Variable nicht gesetzt ist, gibt die Funktion getvariable NULL zurück:

SELECT getvariable('undefined_var') AS result;
result
NULL

Die Funktion getvariable kann auch in einem COLUMNS-Ausdruck verwendet werden:

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;
col0 col2
12 56

Syntax

RESET VARIABLE

Die RESET VARIABLE-Anweisung hebt die Setzung einer Variable auf.

SET VARIABLE my_var = 30;
RESET VARIABLE my_var;
SELECT getvariable('my_var') AS my_var;
my_var
NULL

Syntax