Beginner here! I just started working with SQL Server in Azure functions (in Typescript). I am trying to update a row in the database using declared variables but I am failing to do so with VARCHAR types. Interesting is that in the database tool it is working fine but once I try to run the query inside the Azure function, I get an http me 500 error
RequestError: Incorrect syntax near 'kg'
(working with weight as a string).
At the moment, my code looks like this:
const trainingId: number = parseInt(req.params.training_id);
const exerciseId: number = parseInt(req.params.exercise_id);
const weight: string = req.body.weight;
await mssql.query(
`DECLARE @sql NVARCHAR(4000);
DECLARE @training_id INT;
DECLARE @exercise_id INT;
DECLARE @weight VARCHAR(255);
set @sql = N'
UPDATE Exercises SET weight = @weight WHERE training_id = @training_id AND exercise_id = @exercise_id'
SET @training_id = ${trainingId};
SET @exercise_id = ${exerciseId};
SET @weight = ${weight};
exec sp_executesql @sql, N'@training_id INT, @exercise_id INT, @weight VARCHAR(255)',
@training_id, @exercise_id, @weight`
I have also tried the syntax where I insert the weight variable into the query like this:
SET weight ' + @weight + '
and did not work either.
I have also tried to use this approach here: How to pass parameter to mssql query in node js But it did not work for me either. So how can I actually pass the parameters correctly? I am trying to avoid SQL injection.
Thank you so much for any advice!
weightin your table, seems that is one of the numeric type, but your request body has the suffix 'kg' which throws the error.