问题
I'm trying to get the value of multiple columns in an array and set them as a variable that can be used in the loop to do something else. Thanks.
DECLARE the_array ARRAY<STRUCT<value1 STRING,value2 STRING>>;
SET the_array = (
SELECT ARRAY_AGG(STRUCT(value1,value2))
FROM `project.dataset.table`
WHERE somthing = 'somthing'
);
LOOP
SET i = i + 1;
SET var1 = the_array[ORDINAL(????)]; // what do I do here?
SET var2 = the_array[ORDINAL(???)]; // what do I do here?
IF i > ARRAY_LENGTH(the_array) THEN
LEAVE;
END IF;
insert into `project.dataset.other_table` values(var1,var2);
END LOOP;
回答1:
If you are looking for correct way of achieving above result - do it in set based way which is most effective way of expressing your logic in SQL
INSERT INTO `project.dataset.other_table`
SELECT value1, value2
FROM `project.dataset.table`
WHERE somthing = 'somthing'
Meantime, if purpose of your question is to learn BigQuery Scripting - see below example
DECLARE the_array ARRAY<STRUCT<value1 STRING,value2 STRING>>;
DECLARE i INT64 DEFAULT 0;
DECLARE var1, var2 STRING;
SET the_array = (
SELECT ARRAY_AGG(STRUCT(value1,value2))
FROM `project.dataset.table`
WHERE somthing = 'somthing'
);
LOOP
SET i = i + 1;
IF i > ARRAY_LENGTH(the_array) THEN
LEAVE;
END IF;
SET var1 = the_array[ORDINAL(i)].value1;
SET var2 = the_array[ORDINAL(i)].value2;
insert into `project.dataset.other_table` values(var1,var2);
END LOOP;
来源:https://stackoverflow.com/questions/65825604/set-column-of-array-to-variable-value-in-bigquery-scripting