Javascript Stored Procedure Snowflake

  1. I am working on SP which will look for table name defined in ARRAY across all database
  2. create view by union on same table name
  3. For example for Table A if present in DB 1 and DB 2 then create view by selecting records from both the db
create or replace procedure PROC_1()
  returns VARCHAR -- return final create statement
  language javascript
  as     
$$
    //given two db for testing
    var get_databases_stmt = "SELECT DATABASE_NAME FROM SNOWFLAKE.INFORMATION_SCHEMA.DATABASES WHERE DATABASE_NAME='TERRA_DB' OR DATABASE_NAME='TERRA_DB_2'"
    var get_databases_stmt = snowflake.createStatement({sqlText:get_databases_stmt });
    var databases = get_databases_stmt.execute();
    var row_count = get_databases_stmt.getRowCount();
    var rows_iterated = 0;
    //table on which view will be created       
    var results_table=['STAGE_TABLE','JS_TEST_TABLE];
    var results_db=[];
    while (databases.next())  {
        var database_name = databases.getColumnValue(1);
        //rows_iterated += 1;
        for (let j = 0; j < results_table.length; j++){
            var stmt="CREATE OR REPLACE VIEW  TERRA_DB.TERRA_SCHEMA.ALL_"+results_table[j]+" AS \n";
            stmt += "SELECT * FROM "+database_name+".TERRA_SCHEMA." + results_table[j]
            if (rows_iterated < row_count){
                stmt += " UNION ALL";
            }
            ++rows_iterated;
        }
    }
    //var sql = snowflake.createStatement({sqlText:stmt});
    //var res =sql.execute();
    return stmt;
$$;
call PROC_1();  

Note:- code provided above is creating view by selecting data from one db only, ideally it should select from both db's. Any help will be appreciated!! I am new to JS SP



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations