Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Having troubles inserting multiple records at once without using for loop in sql server database using node.js

Hello guys I'm new in using mysql library in node js and I'm interested in possibility of inserting multiple rows at once in database. I've made a simple code which captures user registration id from database table and uses indexes of roles which that user has selected. And now I want to add user and role id into Role_User table which has user_id and role_id respectively.

Let's say I wanna do this 3 times without using loop:

Insert Into User_role VALUES (1,20);

Insert Into User_role VALUES (2,20);

Insert Into User_role VALUES (3,20);

, where numbers 1,2,3 of the first columns are role indexes.

Error I'm getting is RequestError: Incorrect syntax near '?'.

How can I make this query work?

if(req.body.roles){
                var sqlQuery = `SELECT ID from Test_user Where email = @email`;
                var indexiRola = findPositions(db.ROLES, req.body.roles);
                request.input('role', db.sql.NChar, req.body.roles);
                request.query(sqlQuery).then(
                    id => {
                        let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
                        console.log(ids); // [20, 20, 20]
                        let roleUsers = createSeperateLists(indexiRola, ids);
                        console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
                        var insertQuery = `INSERT INTO Role_User ("role_ID", "user_id") VALUES ?`;
                        request.query(insertQuery, [roleUsers], function(err, result){
                            if(err) throw err;
                            console.log("Successfull insertion");
                        });
                    })
                }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Check if it helps, please. I cannot check it running, of course.

It's not complete, on the contrary! request.query is async, and that code has to be revised.

At least, this code, as I hope, does not break into RequestError: Incorrect syntax near '?'.

Please:

  • check if the revision works for one input
  • whenever you get the complete solution, share it with us
    if (req.body.roles) {
        var sqlQuery = `SELECT ID from Test_user Where email = @email`;
        var indexiRola = findPositions(db.ROLES, req.body.roles);
        request.input('role', db.sql.NChar, req.body.roles);
        request.query(sqlQuery).then(
            id => {
                let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
                console.log(ids); // [20, 20, 20]
                let roleUsers = createSeperateLists(indexiRola, ids);
                console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
                // I removed the double quotes from the names and,
                // VALUES (?, ?) - this is the right syntax for SQL
                const insertQuery = 'INSERT INTO Role_User (role_ID, user_id) VALUES (?, ?)';
                // Then, forEach roleUsers
                // By the way, [roleUsers] yields an array of arrays of arrays, not cool
                roleUsers.forEach(
                    roleUser => {
                        request.query(
                            insertQuery,
                            roleUser,
                            // Oh! Shoot!!! This is async.
                            // Man, you will have to deal with it.
                            // Please, share with us the final solution!
                            function(err, result) {
                                if (err) throw err;
                                console.log("Successfull insertion");
                            }
                        );
                    }
                );
            })
    }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda