Can I insert values from an array at different parts of my Bigquery script?

29 Views Asked by At

I've seen simple Bigquery loops that work great for small calculations, etc, but I need different values from an array to be inserted in various parts of my script.

I have a long script that creates close to 30 temp tables, and I want to loop through different values from an array and insert them in WHERE statements or table names. At the most basic level, it would work like this:

declare array_list ARRAY <STRING>;
set array_list = ['COMEDY', 'DRAMA', 'THRILLER'];


CREATE or replace table running_list
(
  film_title STRING,
  genre STRING
);


create or replace table `all_films_`||array_list[i] as 
SELECT distinct film_title, genre
FROM film_table
WHERE genre = array_list[i];

insert into running_list
SELECT distinct film_title, genre
FROM `all_films_`||array_list[i]

There may be simpler ways to do the above, but like I said, this would in reality be across 30+ tables, so as close to this format as possible would be great.

Based on this, I'd get a table called all_films_COMEDY and the results from that would get inserted into the running table that would hold all of the genre/film data. Then the loop would restart and I'd get a table with all_films_DRAMA and those results would get inserted in, etc.

Every time I try this I get various errors about the syntax -- I also tried to do this inside an "EXECUTE IMMEDIATE" statement, but it errored saying that the keyword CREATE was not expected (when defining my tables).

Any help would be very much appreciated!

0

There are 0 best solutions below