0

I need to import data from a table with mysql and node.

In a select statement I have to use a variable("var_destino" ) in the list of fields.

This variable come from req.body.

Is there a way to do it?

router.post("/importacao", async (req, res) => {
  const var_origem = req.body.origem;
  const var_destino = req.body.destino;
  let sql = `INSERT INTO cl_preco_material (
    id_mat,
    data_valor,
    valor,
    reducao,
    plano_id,
    tabela_mat,
    cod_mat)
    SELECT * FROM (
      SELECT id_mat,
      data_valor,
      valor,
      reducao,
      var_destino, //my problem is here
      tabela_mat,
      cod_mat from cl_preco_material B where B.plano_id=?) AS tmp
      WHERE NOT EXISTS (
         SELECT 1 FROM cl_preco_material K WHERE K.cod_mat = tmp.cod_mat and K.plano_id=?
      ) LIMIT 1`;
  try {
    await pool.query(sql, [var_origem, var_destino]);
    return res.send({ message: "OK" });
  } catch (e) {
    return res
      .status(400)
      .send("Error);
  }
});

1 Answer 1

1

I would try this:

await pool.query("SET @VAR_DESTINO = ?", [var_destino]);
await pool.query(sql, [var_origem]);

And mention @VAR_DESTINO in your bulk insert select clause

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

1 Comment

how to use "like" operator in sql in this case?

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.