Program-Me-Rev
Program-Me-Rev

Reputation: 6624

How to append values of an array to an SQL statement in Javascript

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.

Upvotes: 1

Views: 470

Answers (2)

Aaron
Aaron

Reputation: 147

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();

Upvotes: 3

Shubham Dixit
Shubham Dixit

Reputation: 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(",")})`;

Upvotes: 1

Related Questions