Set column of Array to variable value in bigquery scripting

点点圈 提交于 2021-02-05 07:46:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!