3

I have an ASP.Net MVC application which use SQL 2012 as the database server. I have used Views,Stored Procedures (With/Without dynamic sql queries). I 've heard that dynamic sql can be a victim of sql injection.

Here is one of my sample dynamic query..

DECLARE @Username AS Varchar(100);
DECLARE @Password AS Varchar(100);

SET @Username = 'user1';
SET @Password = '123';

DECLARE @Query AS VARCHAR(MAX);

SET @Query = 'SELECT * FROM USERS WHERE Username ='+ @Username+ ' AND Password = '+@Password+';

EXEC(@Query)

How can I write this query preventing sql injection?

2
  • 1
    blogs.msdn.com/b/raulga/archive/2007/01/04/… Commented Jul 10, 2015 at 19:03
  • 2
    Kudos to you for taking the time to make this right!!! Far too many people just blindly toss that kind of code into production and their site gets hijacked. Commented Jul 10, 2015 at 20:17

1 Answer 1

7

The premise is essentially the same in SQL as it is in application code... Never directly concatenate input as code but instead treat it as a parameter. So if your query is something like this:

SET @Query = 'SELECT * FROM USERS WHERE Username = @Username AND Password = @Password';

Then you can execute it with parameters using sp_executesql:

exec sp_executesql @Query, N'@Username varchar(100), @Password varchar(100)', @Username, @Password
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.