Sunday, January 27, 2013

.NET - Passing list of values as a parameter with an IN keyword.

With the .NET code I've been working on, I've been looking all over the places to be able to use a list of values as a parameter with the IN keyword for a sql statement that would look like this:

SELECT * FROM mytable
WHERE FIELD1 IN ('Value1','Value2','Value3')
In the code the SQL statement would look like this:

SELECT * FROM mytable
WHERE FIELD1 IN (?)
Here are some of the suggested answers that I came up with doing searches in forums
 or other blogs:
  • Concatenate the string to the sql statement, but that left it open to SQL injection.
  • Place values into a temporary table and then do a sub-select on that table. This is not a bad idea, but I didn't want to use a temporary table.
  • Have a function that resides into the database where it would split the comma delimited string into a list of values. This also is a nice solution and some of the scripts that I've found are really ingenious. However, releasing a function into a database is a pain in the butt because of the controls that are put in place. Plus, I'm too lazy to fill extra forms.
All I wanted to do is pass the parameter as a string without any crazy stuff. So I started playing around with the sql statement itself and what available functions the database have. One function that seemed to be working for me is XMLTABLE.

So this is what I came up with:

Pass an xml string into the following statement:
  
string "<root><list>Value1</list><list>Value2</list><list>Value3</list></root>"


Select *
from mytable
where field in (select listValues
from xmltable('$d/root/list' passing cast(? as XML) as "d"
COLUMNS listValues varchar(10) path 'document{.}')as a)

I know it looks like a lot, but the statement can be used as is in any sql statements. The only thing that would have to change is the datatype in case it’s a number or increase the varchar size.

Disclaimer: The statement works on DB2 and it should work in oracle too, but do not have a means to test it there. If I get a chance I'll update the post.

Anyway, this is what I came up with. If you know of a better solution I'm all open ears or eyes. So, if you ended up stumbling in this site and you have some comments about it feel free doing it.



No comments:

Post a Comment