1
let todo = [1, 2, 3, 4, 5, 6, 7, 8];

var stmt = "SELECT * FROM MY_USERS WHERE USER_ID = ?";

connection.query(stmt, todo, function(err, row) {
});

connection.release();

I would like to SELECT * FROM MY_USERS WHERE the USER_ID could be any of the values in the array [1, 2, 3, 4, 5, 6, 7, 8].

Is there a way I could do this without iterating over the array, constructing a new string segment and concatenating it to a final query statement?

Thank you all in advance.

EDIT

I cannot tell the exact number of the array elements in advance, so SELECT * FROM MY_USERS WHERE USER_ID IN (?, ?, ?, ?, ?, ? ,? ,?) will not do.

3
  • Your title says insert but you'r query has select. Confusing. Commented Jun 5, 2019 at 3:52
  • @slon I just edited it to How to append values of an array to an SQL statement in Javascript Commented Jun 5, 2019 at 3:54
  • You can turn the array to string separated by comma and put into ....USER_ID IN(Comma Separated string) Commented Jun 5, 2019 at 4:01

2 Answers 2

3
SELECT * FROM MY_USERS WHERE USER_ID IN (?, ?, ?, ?, ?, ? ,? ,?)

Just make sure the number of ? matches the number of elements in your parameter array

Then finally, use todo.length to do something like :

let todo = [1, 2, 3, 4, 5, 6, 7, 8];

var stmt = "SELECT * FROM MY_USERS WHERE USER_ID IN (";

for (let i = 0; i < todo.length; i++) {
  if (i === 0) {
    stmt += "?";
  } else {
    stmt += ", ?";
  }
}

stmt += ")";

connection.query(stmt, todo, function(err, row) {});

connection.release();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response @aaron, but there is no way to tell the length of the array in advance.
use todo.length then do something like stmt = 'SELECT * FROM MY_USERS WHERE USER_ID IN ('; for (let i=0; i<todo.length; i++){ if (i === 0) {stmt += '?'} else {stmt += ', ?'} }; stmt += ')'
1

let todo = [1, 2, 3, 4, 5, 6, 7, 8];
var stmt = `SELECT * FROM MY_USERS WHERE USER_ID IN (${todo.join(",")})`;
console.log(stmt); // your query

You can use template literals like this,In this way you wouldn't have to bother about number of elements in array.See Array​.prototype​.join()

let todo = [1, 2, 3, 4, 5, 6, 7, 8];

var stmt = `SELECT * FROM MY_USERS WHERE USER_ID IN (${todo.join(",")})`;

Comments

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.