I'm trying to insert two arrays into my SQL database. Here is a snippet from my server.js file that utilizes an endpoint on the client side:
Express setup:
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 procedure:
alter procedure AddQuestionResponses
@Question nvarchar (50),
@Answer nvarchar (50)
as
insert into QuestionResponses(QuestionWhenAnswered, QuestionResponse)
values (@Question ,@Answer )
However, I encounter this error:
RequestError: The parameter name Question has already been declared. Parameter names must be unique
I suspect this issue arises from:
request.input("Question", sql.VarChar, questions[i]);
request.input("Answer", sql.VarChar, answers[i]);
Since they are inside a loop, they are repeated causing the conflict. Is there a way to ensure uniqueness and make a successful transaction with the database?
Thank you for your time :)