Tips for utilizing parameters within SQL Server

Hello everyone! I am new to SQL Server in Azure functions using Typescript. I am currently facing an issue while trying to update a row in the database using declared variables, particularly with VARCHAR types. Strangely, it works fine in the database tool but when running the query inside the Azure function, I encounter an HTTP 500 error.

RequestError: Incorrect syntax near 'kg'

(working with weight as a string).

Here is my current code:

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 also attempted inserting the weight variable into the query like this:

 SET weight ' + @weight + ' 

But that did not work either.

I have tried different approaches such as referencing a solution here: How to pass parameter to mssql query in node js, but they have not been successful in resolving my issue. Can anyone provide advice on how to correctly pass the parameters without risking SQL injection?

Thank you for any guidance!

Answer №1

When you input SET @weight = ${weight}; into a query, you are essentially inserting values that will be used in executing another query. Instead of doing this, why not directly use the UPDATE query right after setting parameter values with mssql.input(...), as suggested in this resource?

My understanding leads me to believe that it should look something like this:

const trainingId: number = parseInt(req.params.training_id);
const exerciseId: number = parseInt(req.params.exercise_id);
const weight: string = req.body.weight;

// set up parameters
mssql.input('training_id', Sql.Int, trainingId);
mssql.input('exercise_id', Sql.Int, exerciseId);
mssql.input('weight ', Sql.VarChar, weight);

// execute only the UPDATE query by using the specified parameters
await mssql.query('UPDATE Exercises SET weight = @weight WHERE training_id = @training_id AND exercise_id = @exercise_id');

Answer №2

Everything finally clicked for me! I had been approaching it incorrectly the entire time by not properly connecting the new request to the mssql. Now, what is working perfectly for me is:

const request: mssql.Request = new mssql.Request();
request.input('training_id', mssql.Int, trainingId);
request.input('exercise_id', mssql.Int, exerciseId);
request.input('weight ', mssql.VarChar, weight);
const result = await request.query('UPDATE Exercises SET weight = @weight WHERE training_id = @training_id AND exercise_id = @exercise_id');

I sincerely appreciate all the assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Perform a summation based on categories and group the results by month and year using

Seeking to calculate the total production of each product type, grouped by month and year. There are three tables: Order_Line: id, batch_date_stop, item_id Order_Line_Detail: order_line_id, batched_qty, item_id Mill_Item_Map: item_id, item_class Th ...

What is the capability of dynamically generating an index in Typescript?

Can you explain why the Typescript compiler successfully compiles this code snippet? type O = { name: string city: string } function returnString(s: string) { return s } let o1: O = { name: "Marc", city: "Paris", [returnString("random")]: ...

typescript: declaring types in a separate JavaScript file

Imagine you have a JavaScript library that exports some types for use (let's call it js1.js). You also have some TypeScript code sitting in a <script type="module"> tag that you want to use these types with (let's say ts1.ts). To make this ...

Error: Serialization of circular structure to JSON not possible in Next.js

I am currently working on creating an API in Next.js to add data into a MySQL database. The issue I am facing is related to a circular reference, but pinpointing it has proven to be challenging. It's worth mentioning that Axios is also being utilized ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

Ways to simulate a dependent class in TypeScript & JEST without modifying constructor parameters to optional

Currently, I am attempting to replicate a well-known process in Java development using TypeScript and JEST for practice. In this scenario, there is a Controller class that relies on a Service class. The connection between the two is established through the ...

What is the correct way to use forwardRef in a dynamic import in Next.js?

I've been trying to incorporate the forwardRef in my code, but I'm facing some difficulties. Can anyone help me out with this? I'm encountering the following errors: Property 'forwardedRef' does not exist on type '{}'. ...

Receiving a blank response after making a post request even though the request was processed without

While making a post request using httpClient, I am receiving a null response despite the request being processed successfully. File: serviceClass.ts this.httpOptions = { headers: new HttpHeaders( { 'Content-Type': 'application ...

Avoiding caching of GET requests in Angular 2 for Internet Explorer 11

My rest endpoint successfully returns a list when calling GET, and I can also use POST to add new items or DELETE to remove them. This functionality is working perfectly in Firefox and Chrome, with the additional note that POST and DELETE also work in IE ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

PhantomJS version 2.1.1 encountered an error on a Windows 7 system, displaying "ReferenceError: Map variable not found."

I've been utilizing the "MVC ASP.NET Core with Angular" template. I'm attempting to incorporate phantomJS and execute the tests, but encountering the following errors: ERROR in [at-loader] ..\\node_modules\zone.js\dist&bs ...

Guide on efficiently injecting data into a database using JavaScript and SQL from an array of objects

Let's simplify this process. I am creating a dynamic form for clients to submit data to a PostgreSQL database using React on the front end and NodeJs on the back end. Once the form is filled out, the inputs are stored in an array of objects like this ...

Retrieve an item from an array using a Select component

Is there a way to retrieve the complete object representation of an item from a list in React? Currently, when I select an item and call handleChangeSelectAuto, the original value from useState is returned instead of the entire object. How can I ensure tha ...

Fill up a data repository with the names and corresponding Project IDs

I am tasked with developing a project management system using C#. My inquiry revolves around how to populate a dropdown menu with project names while keeping the project ID hidden. This way, when I need to add a task, I can easily choose the project to wh ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

Exploring the Integration of Graphql Typescript Types in React Applications

I am currently working on a project that involves a React app with a Keystone.js backend and a GraphQL API. Within Keystone.js, I have a list of products and a basic GraphQL query set up like so: import gql from "graphql-tag"; export const ALL_ ...

Optimizing row performance for Angular grids in the Chrome browser

When creating a component that includes a table with numerous rows, everything works well with small amounts of data. However, once the item count reaches 2000 or more, it starts lagging. Scrolling and animations become sluggish. Even after trying to impl ...

When a temporary table is dropped in PostgreSQL, any queries referencing it will result in an

I've encountered an issue while working on a homework assignment that involves retrieving data based on specific criteria and then running another query on the selected data. Initially, I create a temporary table to store the results of the first que ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...