I am trying to use sp_executesql to prevent SQL injection in SQL 2005, I have a simple query like this:
SELECT * from table WHERE RegionCode in ('X101', 'B202')
However, when I use sp_executesql to execute the following, it doesn’t return anything.
Set @Cmd = N'SELECT * FROM table WHERE RegionCode in (@P1)'
SET @ParamDefinition = N'@P1 varchar(100)';
DECLARE @Code as nvarchar(100);
SET @Code = 'X101,B202'
EXECUTE sp_executesql @Cmd, @ParamDefinition, @P1 = @Code
The is what I have tested:
SET @Code = 'X101' <-- This works, it returns a single region
SET @Code = 'X101,B202' <--- Returns nothing
SET @Code = '''X101'',''B202''' <-- Returns nothing
Please help…. what did I do wrong?
The reason it doesn’t work is because @P1 is treated as one, single value.
e.g. when @Code is X101,B202 then the query is just being run as:
SELECT * FROM Table WHERE RegionCode IN (‘X101,B202’)
So, it’s looking for a RegionCode with the value that is contained with @P1. Even when you include single quotes, all that means is the value it searches for in RegionCode is expected to contain those single quotes.
You’d need to actually concatenate the @Code variable into the @Cmd sql command text in order for it to work the way you are thinking:
Obviously though, this just opens you up to SQL injection so you’d need to be very careful if you took this approach to make sure you guard against that.
There are alternative ways of dealing with this situation where you want to pass in a dynamic list of values to search for.
Check out the examples on my blog for 2 approaches you could use with SQL Server 2005. One involves passing in a CSV list in the form “Value1,Value2,Value3” which you then split out into a TABLE variable using a user defined function (there’s a lot of mentions of this approach if you do a quick google or search of this site). Once split out, you then join that TABLE var in to your main query. The second approach is to pass in an XML blob containing the values and use the built-in XML functionality of SQL Server. Both these approaches are demonstrated with performance metrics in that link, and they require no dynamic SQL.
If you were using SQL Server 2008, Table Value Parameters would be the way to go – that’s the 3rd approach I demonstrate in that link which comes out best.