Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select where values in List<string>

Tags:

.net

sql

ado.net

Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

like image 608
JoelHess Avatar asked Mar 02 '09 14:03

JoelHess


2 Answers

You could use String.Join. Try something like this:

String query = "select * from table where RecordId in ({0});";
String formatted = String.Format(query, String.Join(",", list.ToArray()));

As a side note this will not protect you against SQL injection - hopefully this example will point you in the right direction.

like image 122
Andrew Hare Avatar answered Sep 23 '22 06:09

Andrew Hare


I've only done what your trying to do with a comma separated list

Select * from Table where RecordID in (1,2,34,45,76,34,457,34)

or where the results come from a separate select

Select * from Table where RecordID in (select recordId from otherTable where afieldtype=1)

I'm pretty sure you can't achieve what you're after....

like image 40
GordonB Avatar answered Sep 24 '22 06:09

GordonB