7

I have an array where each element corresponds to an alphanumeric string, lets say :

userIds : ['Ab526', 'shvx23', '23636dsd']

I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :

Select * from Users where userIds in '(...)';

I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.

var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids    = userIds.join(',');
var query  = 'Select * from Users where userIds in (' + ids + ')'; 
console.log(query);

which results in :

Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');

If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.

3
  • 1
    var ids = "'"+userIds.join("','")+"'"; Commented Apr 2, 2017 at 8:03
  • It gives escape character along with single quotes. Tried already Commented Apr 2, 2017 at 8:19
  • late to party, but your code output is different than provided result - it may be missing something Commented Jan 25, 2019 at 8:59

6 Answers 6

3

You could map the quoted values and join later.

var userIds = ['Ab526', 'shvx23', '2363\'6dsd'],
    result = userIds.map(function (a) { return "'" + a.replace("'", "''") + "'"; }).join();
    
console.log(result);

Sign up to request clarification or add additional context in comments.

4 Comments

I think this is simpler: var ids = "'"+userIds.join("','")+"'"
you need to quote single quotes in the string as well.
With this solution too, m getting resultant string as '\'Ab526\',\'shvx23\',\'23636dsd\''
you may have a look here: stackoverflow.com/questions/7744912/…
3

Or a simple one liner

const userIds = [12,13,14,15];
const query  = `Select * from Users where userIds in ('${userIds.join("','")}')`; 

console.log(query)

Comments

2

You could use reduce on the array:

var userIds = ['Ab526', 'shvx23', '23636dsd'];
    var clause = userIds.reduce(
                 function (cl , a, currIndex, arr) 
                     { 
                     return cl + 
                      (currIndex == 0 ? "" : ",")  
                     +"'"+ a + "'"+ 
                     (currIndex == arr.length-1 ? ")" : "") ; } , "(" );
    
    console.log(clause );

2 Comments

As a string it comes out fine, but when appending it to SQL Query string, it throws an error : error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "(\'Ab526\',\'shvx23\',\'23636dsd\')'
I know it's trivial, but do you add a space between 'in' and '( ... ' ? Many of my errors in query concat were due to missing spaces.
2

You can use the following code :

var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
    ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);

1 Comment

this is exactly similar to what array.prototype.join() does.
-1

This worked for me for the same issue:

var myList = [1, 2, 3]
var listAsString = myList.toString() 
var queryList = "(" + listAsString + ")"

SQL Query is like so: WHERE number IN queryList

1 Comment

Does not work for strings in array like in the question
-1
let tickers = ['AAPL', 'MSFT']
const inStmt = "('" + tickers.join("','") + "')"

This will give you the result inStmt == ('AAPL','MSFT') which can be later on used as:

const QUERY = `select x from Y where Y.z in ${inStmt}`

Please note, that if you have numbers, not strings, single quotes must be removed:

let tickers = [1, 2, 3]
const inStmt = "(" + tickers.join(",") + ")"

1 Comment

Can you edit your answer with a textual explanation of the code for future readers please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.