I am trying to execute the value of the variable, but I can\'t find documentation about it in Google BigQuery.
DECLARE SQL STRING;
SELECT
SQL =
CONCAT(
While Mikhail is correct that this historically hasn't been supported in BigQuery, the very new beta release of BigQuery Scripting should let you accomplish similar results: https://cloud.google.com/bigquery/docs/reference/standard-sql/scripting
In this case, you would need to use SET to assign the value of the variable, and there isn't an EXEC
statement at this time, but there is support for conditionals, loops, variables, etc.
To recreate your example, you could store the results of a query against either your first.rdds_load
table, then use WHILE to loop over those results. Within that loop, you can run a normal CREATE TABLE
if it doesn't already exist. I'm thinking something along these lines based on your example . . .
DECLARE results ARRAY<STRING>;
DECLARE i INT64 DEFAULT 1;
DECLARE cnt INT64 DEFAULT 0;
SET results = ARRAY(
SELECT
DISTINCT AS VALUE
CAST(actime AS STRING)
FROM
first.rdds AS rd
WHERE
EXISTS (
SELECT
1
FROM
first.rdds_load AS rd_load
WHERE
rd_load.id = rd.id
)
);
SET cnt = ARRAY_LENGTH(results);
WHILE i <= cnt DO
/* Body of CREATE TABLE goes here; you can access the rows from the query above using results[ORDINAL(i)] as you loop through*/
END WHILE;
There's also support for stored procedures, which can be executed via CALL with passed arguments, which may work in your case as well (if you need to abstract the creation logic used by many scripts).
(I would argue that this scripting support is superior to building and executing strings, since you'll still get SQL validation and such for your query.)
As always with beta features, use with caution in production—but for what it's worth, thus far my experience has been incredibly stable.
Update: as of 5/20/2020, BigQuery released dynamic SQL feature for you to achieve the goal.
Dynamic SQL is now available as a beta release in all BigQuery regions. Dynamic SQL lets you generate and execute SQL statements dynamically at runtime. For more information, see EXECUTE IMMEDIATE. x
================
BigQuery does not support this (Dynamic SQL) in pure SQL, but you can implement this in any client of your choice