从 Google 脚本将数据插入 BigQuery:遇到“”

Insert data into BigQuery from a Google Script : Encountered ""

我正在尝试通过 Google App 脚本将数据从 Google 电子表格导入 BigQuery。我可以下载数据,但是当我尝试执行 INSERT INTO 时出现错误。错误信息是

Encountered "" at line 1, column 31. [Try using standard SQL (https://cloud.google.com/bigquery/docs/reference/standard-sql/enabling-standard-sql)]

这是我的代码:

function insertRowsInBigQuery(){
var projectId = 'xxx';
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName("EPC");

var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getValues();
var sqlData = "INSERT INTO ean.eanToAnalyze (EPC, EAN) VALUES (";

for (i = 0; i < data.length; i++){
  if (i > 0) {
    sqlData += ",(";
  }
  for (j = 0; j < data[0].length; j++){
    sqlData += "'" + data[i][j] + "'";
    if (j < data[0].length -1){
      sqlData += ",";
    } else {
      sqlData +=")";
    }
  }     
}

var request = {
  query: sqlData,
  writeDisposition: 'WRITE_TRUNCATE'
};

var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;

// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
  Utilities.sleep(sleepTimeMs);
  sleepTimeMs *= 2;
  queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}

Logger.log(queryResults);

}

几乎相同的功能,只是将 INSERT INTO 改了一个 SELECT,我得到了数据。

如错误所述,您需要 enable standardSQL to use DML。最简单的方法似乎是在查询前加上前缀:

var sqlData = "#standardSQL\nINSERT INTO ean.eanToAnalyze (EPC, EAN) VALUES (";

实现相同目的的另一种方法是将 useLegacySql 参数设置为 false。 您可以按如下方式更新请求变量:

var request = {
  query: sqlData,
  writeDisposition: 'WRITE_TRUNCATE',
  useLegacySql: false
};