I am trying to upload two arrays into my sql database. This is what I have come up with.(this is my server.js using a endpoint from my client side)
My express
app.post("/post-question-answers", async (req, res) => { console.log("!called"); try { await sql.connect(config); // create Request object var request = new sql.Request(); let results = req.body.results; let questions = []; let answers = []; results.forEach(element => questions.push(element.question)); results.forEach(element => answers.push(element.answer)); for (var i = -1; i < results.length; i++) { request.input("Question", sql.VarChar, questions[i]); request.input("Answer", sql.VarChar, answers[i]); request.execute("dbo.AddQuestionResponses", function(err, recordset) { if (err) console.log(err); // send records as a response res.json(recordset); }); } } catch (e) { console.log(e); } });
My sql stored procedrue
alter procedure AddQuestionResponses @Question nvarchar (50), @Answer nvarchar (50) as insert into QuestionResponses(QuestionWhenAnswered, QuestionResponse) values (@Question ,@Answer )
However this throws
RequestError: The parameter name Question has already been declared. Parameter names must be unique
I believe this is because
request.input("Question", sql.VarChar, questions[i]); request.input("Answer", sql.VarChar, answers[i]);
need to be unique and as they are in a for loop they are repeated within the statement. Is there a way in which I can make this a valid transaction with the database and so that these are unique.
Thankyou for your time 🙂
Advertisement
Answer
I solved this issue by putting
var request = new sql.Request();
within the for loop.