雪花存储过程中的事务

时间:2021-03-17 16:05:10

标签: snowflake-cloud-data-platform

我在雪花中的第一个存储过程,尝试在其中一个示例存储过程中使用事务,请帮助修复错误,为什么? "未捕获的语法错误:'BEGIN TRANSACTION;'处的 GET_ROW_COUNT 中出现意外标识符位置 8" 尝试遵循文档:https://docs.snowflake.com/en/sql-reference/transactions.html

这是过程。

  create or replace procedure get_row_count(table_name VARCHAR)
  returns float not null
  language javascript
  as
  $$
  var row_count = 0;
  BEGIN TRANSACTION;
  // Dynamically compose the SQL statement to execute.
  var sql_command = "select count(*) from " + TABLE_NAME;
  // Run the statement.
  var stmt = snowflake.createStatement(
         {
         sqlText: sql_command
         }
      );
  var res = stmt.execute();
  // Get back the row count. Specifically, ...
  // ... get the first (and in this case only) row from the result set ...
  res.next();
  // ... and then get the returned value, which in this case is the number of
  // rows in the table.
  row_count = res.getColumnValue(1);
  return row_count;
  COMMIT ;
  $$
  ;

1 个答案:

答案 0 :(得分:0)

您需要使用 snowflake.execute() 调用 COMMIT 和 BEGIN TRANSACTION,因为它们是 SQL 命令:

 create or replace procedure get_row_count(table_name VARCHAR)
  returns float not null
  language javascript
  as
  $$
  var row_count = 0;
  snowflake.execute({ sqlText: 'BEGIN TRANSACTION' });
  // Dynamically compose the SQL statement to execute.
  var sql_command = "select count(*) from " + TABLE_NAME;
  // Run the statement.
  var stmt = snowflake.createStatement(
         {
         sqlText: sql_command
         }
      );
  var res = stmt.execute();
  // Get back the row count. Specifically, ...
  // ... get the first (and in this case only) row from the result set ...
  res.next();
  // ... and then get the returned value, which in this case is the number of
  // rows in the table.
  row_count = res.getColumnValue(1);

  snowflake.execute({ sqlText: 'COMMIT' }); 
  return row_count;
  $$
  ;