SuicideSheep
SuicideSheep

Reputation: 5550

Why do SQL injection not working?

DECLARE @a varchar(max);
set @a ='''a'' OR Name like ''%a'';';

--Why the below query not working
Select TOP 10 * FROM Member where Name = @a

-- The query below was executed to make sure that the query above 
   being constructed properly
print 'SQL: Select TOP 10 * FROM Member where Name ='+ @a
--SQL: Select TOP 10 * FROM Member where Name ='a' OR Name like '%a';

Correct me if im wrong, SQL injection wont work in Stored Procedure is due to some precompiled factor but the above scenario was tested in query statement instead of Stored Procedure. Why still not working?

Upvotes: 0

Views: 425

Answers (3)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

SQL Injection occurs when data is confused for and interpreted as code.

This does not happen in your scenario since parameter or variable values are not directly interpreted as code - they're only at risk of being interpreted as code if you construct new code by combining strings and these parameter/variable values and then pass the entire constructed string to the system and ask it to interpret the entire string as code - via exec, sp_executesql or other such means.

Upvotes: 1

ruakh
ruakh

Reputation: 183456

I'm not sure why you think that would work. @a is a varchar variable, so Select TOP 10 * FROM Member where Name = @a finds rows where Name is equal to the value of that variable.

If you want SQL-Server to take the value of @a and insert it into the query as code, then you need to use sp_executesql (analogous to eval in languages like Bash and Python and JavaScript):

EXECUTE sp_executesql 'Select TOP 10 * FROM Member where Name = ' + @a

Upvotes: 4

Zin Min
Zin Min

Reputation: 4695

Look there is no name ending with 'a'. Try like

Select TOP 10 * FROM Member where Name ='a' OR Name like '%a%'

Updated

Microsoft handle SQL injection for SQL parameters.

Upvotes: 0

Related Questions