Getting a count of rows inserted in a Snowflake procedure

3.4k views Asked by At

I'm using a procedure to insert rows into a table. I want to return the count of rows inserted, but I can't figure out how to turn on the variable substitution from inside a procedure. I've tried all of the following, but they all return errors:

snowflake.execute({sqlText: '!set variable_substitution=True'});
snowflake.execute({sqlText: 'set variable_substitution=True'});
snowflake.execute({sqlText: '-o variable_substitution=True'});

How do I turn this option on so I can run "select &__rowcount;" and get my count back?

Here's code for a test procedure, if that helps:

CREATE OR REPLACE PROCEDURE TEST_OF_GETTING_COUNTS()
  RETURNS VARCHAR
  LANGUAGE javascript
  CALLED ON NULL INPUT
  AS
  $$  
    // Turn on variable substitution
    snowflake.execute(
      {sqlText: '!set variable_substitution=True'}
    );
    
    // Prepare SQL to identify tables to be updated
    snowflake.execute({sqlText: 'SELECT 1'});
    
    // Now get the count of rows selected  
    var getCount = snowflake.createStatement({sqlText: "SELECT &__ROWCOUNT;"});
    var rowCountResultSet = getCount.execute();
    while (rowCount.next()) {
      rowCount= rowCountResultSet.getColumnValue(1);
    }

    // Turn off variable substitution
    snowflake.execute({sqlText: '!set variable_substitution=False'});
          
    return rowCount;
  $$;

CALL TEST_OF_GETTING_COUNTS();
1

There are 1 answers

0
ASturt On

NickW, in his comment above, gave me a link to a page in Snowflake's documentation that lists all the JavaScript methods available for the snowflake, Statement, ResultSet, and SfDate objects. It gave me exactly what I needed: the getRowCount() method.