Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Aim: Dynamic SQL based on user input

Use: User search boxes to get a result

Query/Review Question: Does the below leave the code exposed to SQL Injection attacks?

--Declare Variable to hold the Dynamic SQL
DECLARE @vSQL varchar(max);
DECLARE @sSomeValue varchar(max);
DECLARE @sFirstName varchar(max);

--Your ifcondition
IF LTRIM(RTRIM(@sSomeValue))= 'DefaultValue'
    BEGIN
    --Create you statement with OR condition
        SET @vSQL = 'OR SomeValue = ' + @sSomeValue;
    END;
ELSE
    BEGIN
    --Create you statement with AND condition
        SET @vSQL = 'ANDSomeValue = ' + @sSomeValue;
    END;

SELECT Firstname, SomeValue
  FROM TblMainTable
  WHERE Firstname LIKE '%' + @sFirstName + '%' + @vSQL;

Notes:

This is a more complex code however the If/Else statements are the same in structure so this is sample code for the principle of the code review.

References:

1) C# code but a good guide

2) Preventing SQL Injection

share|improve this question

closed as off-topic by Malachi, konijn, Vogel612, syb0rg, 200_success Nov 24 '14 at 21:04

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

    
We would prefer to review real code rather than simplified code. If you must simplify, please make sure that it still "works". –  200_success Nov 24 '14 at 15:47
    
Pass a' OR 'a' = 'a' for the value of @sSomeValue and see what happens. –  RobH Nov 24 '14 at 15:57
1  
Need to see the actual code. What is provided will not work. The context: is this performed in a stored proc, package, or execute statement may change the answer. The database platform would be useful knowledge as well. –  psaxton Nov 24 '14 at 16:54
    
how are the parameters passed into the query? –  Malachi Nov 24 '14 at 18:15

1 Answer 1

In a short, YES!

Any atempt to use non parameterized dynamic SQL can let you prone to SQL Injection.

Why/How? Because you are building a SQL Script on the fly and a attacker can exploit it to build a malicious script instead. Read the first paragraph of the second link you posted.

There a few things you can do, like sanitizing your input but it's not guaranted to work. The best approach is to avoid to use dynamic SQL or at least use parameterized dynamic SQL.

There are lots of trick you can use to build a non dynamic conditinal query

SP_EXCUTESQL on MSDN

Great article about thecniques on conditional quering

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.