3

I have a SQL server table where I want to query for items on rows which have a value equal to an item in Array. Here's my example:

Column1    Column2    Column3
-------    -------    -------
aaa        100        200
bbb        100        400
aaa        200        78  
ccc        200        200

And my array:

string[] arr = {"ddd", "aaa", "fff", "bbb"}

So, I want to return from SQL rows matching items in the array. my SQL query should return items where column1 matches an item in the array:

Column1    Column2    Column3
-------    -------    -------
aaa        100        200
bbb        100        400
aaa        200        78  

This all in C# by the way. Help will be appreciate.

1
  • Have you considered using LINQ? Perfect for this sort of multisource comparisons. Commented Mar 21, 2014 at 20:26

3 Answers 3

3

You can build an SQL query with an IN(@PARAM) clause, and Join them with String.Join, like this:

using(SqlConnection connection = new SqlConnection(
        connectionString)) {
    using(SqlCommand command = new SqlCommand()) {
            SqlDataReader reader = null;
        try {
            command.Connection = connection;
            command.CommandText = "SELECT * FROM <TABLE> WHERE <FIELD> IN (@PARAM)";
            command.CommandType = CommandType.Text;
            command.Parameters.Add(new SqlParameter(@"@PARAM",
                    String.Join(",", <array>)));
            connection.Open();
            reader = command.ExecuteReader();
            if(reader.HasRows) {
                // logic
            }
        } catch(SqlException) {
            throw;
        }
    }
}

The items must be enclosed with ' ' (single quotes).

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, I guess I was getting stuck on how to use a parameter to pass the values in the array back to SQL. Thanks much for your help.
0

You could pass these values as a Table Value Parameter to your SP and then join it to your table on Column1.

Link: How to pass a TVP from C#

Comments

0

The SQL query you want is:

SELECT * FROM Table1 WHERE Column1 IN ('ddd', 'aaa', 'fff', 'bbb')

You can parse your array directly into the query.

Your post didn't mention anything about LINQ, which would make it even easier.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.