Using SQL Queries in Loops: Best Practices

csql

Is it a bad idea? I need to compare each entry.Key value in a Dictionary of strings to a SQL table. If there is a match, then I pull the data from that row.
I was originally going to use a foreach loop to query each entry.Key value.
I was told by someone that doing this is a bad idea.
Is it bad because I'm doing too many queries?
Each Dictionary could have thousands of values (which probably means thousands of queries)…
Can anybody suggest a better way? (compare the dictionary to a datatable of results?)

Best Answer

You can use an IN clause for this.

SELECT someFields FROM yourDictionaryTable WHERE key IN (List of values)

You'll need to build your list of values as a string with single quotes and commas, like this:

'value1', 'value2', 'value3'

This will give you a single, high-performing SQL query which will return the data set you want.

Related Topic