How to piece together complex SQL queries in node-mssql

27 views Asked by At

The MSSQL queries I want to execute will vary greatly in length in the following way:

example 1: SELECT itemKey FROM items WHERE vendor in ('WALM', 'TARG', 'COSC') example 2: SELECT itemKey FROM items WHERE vendor in ('HOMD') AND originCountry in ('USA', 'CHN') example 3: SELECT itemKey FROM items WHERE vendor in ('WALM','TARG','COSC','LOWE','HOMD') and originCountry in ('USA','CHN','TAI','VIE')

to accomplish this I use this to build my "filter" if you will:

filter += ' AND vendor in ('
    while(i < vendors.length) {
      if(i == (vendors.length - 1)) {
        filter += '\'' + vendors[i] + '\')'
      }else{
        filter += '\'' + vendors[i] + '\','
      }
      i++
    }

followed by: (I used squiggles to replace backticks for this post)

const result = await sql.query~SELECT itemKeys FROM items WHERE ${filter}~

However doing it this way produces the following error:

stack trace

Where as this following works perfectly: const result = await sql.query~SELECT itemKeys FROM items WHERE vendor in ('TARG')

In the bottom section of the above post, I explained the 'hard coded' query I'm using to verify that no other parts of my code are broken.

The stack trace for the non-working section of code is snipped as a photo.

0

There are 0 answers