2

I want to make a sql query in C# that finds all rows with a key that is specified in a list. Can I do this with one query? I suppose that is much more efficent than my solution which finds one item at the time inside a for loop, se below:

foreach (int i in list)
{
    string Q = "... where pk = " + i.ToString();
    using (SqlCommand CM = new SqlCommand(Q, C))
    {
         using (SqlDataReader R = CM.ExecuteReader())
         {
              while (R.Read())
              {
                  ...
              }
          }
     }
}

list contains different in values.

Thanks in advance!

2

2 Answers 2

3

Replace

string Q = "... where pk = " + i.ToString();

with

string Q = "... where pk IN ('" + string.Join("','", list)+"')";

then you can remove the loop. The result should look like ... where pk IN ('1','2','3')

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

Comments

0

You can use the IN keyword and pass your list by converting it to a comma seperated string in your query.

Something like

string Q = "select * from tablename where pk IN " + (comma seperated list here);

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.