Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

648
Views
Javascript print SQL first item in ResultSet without comma, then all others with comma

create procedure my_stored_procedure(TABLE VARCHAR)
  returns varchar
  language javascript
  as
    $$

var sql_col_list = `select distinct key_name from TABLE;`
results = snowflake.execute({sqlText: sql_col_list});

while (results.next())
{
     script += ',' + results.getColumnValue(1) + '\n';
}

Current output:

, column1
, column2
, column3

Desired output:

  column1
, column2
, column2

How can I do this in javascript within the sql stored procedure? I would like to not have to execute the query more than once because the actual query is computationally intensive.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

using your sp, i would remove the first result from the loop so it is:

create or replace procedure my_stored_procedure(TABLE VARCHAR)
  returns varchar
  language javascript
  as
    $$

var sql_col_list = `select distinct key_name from TABLE;`
results = snowflake.execute({sqlText: sql_col_list});
var script = '';

results.next()
script += results.getColumnValue(1)

while (results.next())
{
       script += ',' + results.getColumnValue(1) + '\n';
}
return script;
$$;
about 4 years ago · Juan Pablo Isaza Report

0

A poor solve it after the fact solution, remove it:

> ',a,b,c'.replace(/^,/,'');
'a,b,c'
>

another option is to build an array of the wanted parts, and then use join

> ['a','b','c'].join(',\n');
'a,\nb,\nc'
>

and if you want the trailing newline:

> ['a','b','c'].join(',\n')+'\n';
'a,\nb,\nc\n'
>

OR you could get Snowflake to do it for you:

SELECT listagg( DISTINCT key_name, ',\\n') || '\\n'
FROM VALUES
   ('apple'),('cat'),('apple'),('cat'),('dog') t(key_name);
LISTAGG( DISTINCT KEY_NAME, ',\N')|| '\N'
apple,\ncat,\ndog\n
about 4 years ago · Juan Pablo Isaza Report

0

you can add boolean check if this first or not:

var sql_col_list = `select distinct key_name from TABLE;`
results = snowflake.execute({sqlText: sql_col_list});

var isFirst = true;

while (results.next())
{
      if(isFirst)
      {
        script += results.getColumnValue(1) + '\n';
        isFirst = false;
        continue;
      }
     script += ',' + results.getColumnValue(1) + '\n';
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!