SQL Server - Prevent SQL injection while accepting user input.

Asked By Aryan Bhatt on 11-Feb-21 02:22 AM

I have a legacy web application which accepts user input from textboxes.
In one of the screens where user can add new records to the database,
need to prevent SQL injection by making not much changes to existing code.

Existing code is as below :

Current SQL Statement

Insert into ##TableName## (" + varResult1 + ") Values (" + varResult2 + ")

which translates to :

Insert into ##TableName## ([Deptname],[Location],[Column1],[Column2],[Column3]) values ('testval1','testval2','30','50','60')

Where the values i.e. 'testval1','testval2','30','50','60' are all coming from textboxes in the UI screen,

Behind the scenes, the above insert statement is assigned to a string variable @query
in a stored proc and Execute(@query) is being called.

Any way we could avoid SQL injection making minimum changes to existing code?

Any help would be much appreciated.