Updating a value in an ARRAY in a BigQuery table

Viewed 6174

I have a BigQuery table with a similar schema to that shown in the picture, rows that can hold arrays of structs. What syntax should I use to attempt to change/update an itemDelta.typeId to another value? (see SQL if unclear)

BigQuerySchema

UPDATE itemInformation
SET    itemDelta.typeId = 9426
WHERE  itemDelta.typeId = 2424; 

UPDATE:

One work around I found is to implement a User-Defined-Function. BigQuery allows you to create custom functions using JavaScript.

Here is the code:

CREATE TEMPORARY FUNCTION edit(table ARRAY<STRUCT<typeId INT64, amount INT64>>)
RETURNS ARRAY<STRUCT<typeId INT64, amount INT64>>
LANGUAGE js AS """
var i;  
for(i = 0; i < table.length; i++)
{
  if(table[i].typeId == 2452)
  {
    table[i].typeId = 1000
  }
}
return table;
""";

UPDATE itemInformation
SET    itemDelta = edit(itemDelta)
where  true
2 Answers
#standardSQL
UPDATE `yourProject.yourTable.itemInformation`
SET itemDelta = ARRAY(
    SELECT STRUCT<typeId INT64, amount INT64>(IF(typeId = 2424, 9426, typeId), amount) 
    FROM UNNEST(itemDelta)
  ) 
WHERE 2424 IN (SELECT typeId FROM UNNEST(itemDelta)) 
Related