Skip to content
Advertisement

Search SQL database with multiple filters

I have the following code:

This gives me the rows where “category_id” is equal to the 1.

I now want the SELECT statement to return rows where the “category_id” is equal to one of the values I give it.

So a simple SELECT statement would look something like this

The problem is that I wouldn’t know the values to search for when setting up the SELECT statement. I would have the values in a string, list or something similar.

i tried using a foreach loop to change the value of “Id”

But this just returns the rows where “category_id” is equal to the last value int the array “Values”.

I have tried to use the IN operator, but got an error

One final idea I had was using a loop to make a string from the value.

I have not tried this yet but I’m expecting it to give an error as the column is “category_id” has the data type “int”.

Is there any way to search the SQL database with an array/list as parameter, so it gives every row where it equals one of the values in the array/list.

Advertisement

Answer

The best way I have found to do this is to make a joined string with the values in the array/list.

Then using the “IN” keyword and making the CommandText a formatted string.

So the CommandText looks like this:

Not sure if this is the most efficient way, but it works for my specific problem.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement