sp_executesql with 'IN' statement

Posted by user300992 on Stack Overflow See other posts from Stack Overflow or by user300992
Published on 2010-04-08T13:53:11Z Indexed on 2010/04/08 14:13 UTC
Read the original article Hit count: 229

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?

© Stack Overflow or respective owner

Related posts about sp-executesql

Related posts about sql