0

Please help me fix the syntax for this command text "query" below. I want to pass a list of integers "ints" to retrieve all rows that match them.

private void(List<int>ints)
{     
     // some variables  
        string query =
                    string.Format(
                       "SELECT * FROM " +  table +
                       " WHERE SubId={0} AND RouteID IN({1})",
                       SubId,
                       ints
                       );

       // more stuff
 }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Asha
  • 25
  • 1
  • 7

1 Answers1

2

If you would like to format a list of ints like that, you need to add commas in between:

string.Format(
    "SELECT * FROM " +  table +
    " WHERE SubId={0} AND RouteID IN({1})",
    SubId,
    string.Join(",", ints)
);

Assuming that everything is an int, nothing comes from user input, and the list is not too long, this should work fine. However, you should strongly consider moving to parameterized SQL. Specifically, in this case you could improve the query a great deal by using a table-valued parameter.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523