Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

What's the best approach for creating on the fly a string of intergers for a WHERE IN clause in SQL

For example@

string whereClause = "4,5,6"

select * from tableA where id in + whereClause

Edit

Should add i'm using Dapper.NET, so can pass in parameters

share|improve this question

closed as off-topic by amon, kleinfreund, palacsint, Jamal Feb 17 at 14:54

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "Questions asking for code to be written to solve a specific problem are off-topic here as there is no code to review." – palacsint, Jamal
  • "Your question must contain working code for us to review it here. For questions regarding specific problems encountered while coding, try Stack Overflow. After getting your code to work, you may edit this question seeking a review of your working code." – amon, kleinfreund
If this question can be reworded to fit the rules in the help center, please edit the question.

    
OK so Dapper seems to support what you are trying to acheive. You really want the reverse of what I suggested, i.e. to split the string into ints. Please see the following post which should help: stackoverflow.com/questions/1763613/… –  Simon Feb 17 at 14:16
    
Please see this as well: stackoverflow.com/questions/8388093/… –  Simon Feb 17 at 14:21

1 Answer 1

up vote 2 down vote accepted

First you query will fail in SQL Server, it should be written like:

SELECT * FROM tableA WHERE id IN (WhereClause)

What I would suggest is to use the following method to generate your whereclause:

public static string ToIntCSV(this IEnumerable<int> ints)
{
  if (ints == null) throw new ArgumentNullException("ints");
  string result = string.Empty;
  foreach(int i in ints)
  {
    if (string.IsNullOrEmpty) result = i.ToString();
    else result += string.Format(",{0}",i);
  }
  return result;
}

You could potentially use a StringBuilder if you expect large quantities of integers. Alternatively you could use the LINQ Aggregate() extension too.

public static string ToIntCSV(this IEnumerable<int> ints)
{
  if (ints == null) throw new ArgumentNullException("ints");
  return ints.Aggregate((csvSoFar, next) => string.Format("{0},{1}",csvSoFar,next);
}

This also ensures you actually have a list of integers for your where clause.

Finally to build your query, you should get into the habit of using string.Format():

  public void GetQuery(IEnumerable<int> ints)
  {
     try
     {
     var query = string.Format("SELECT * FROM [tableA] WHERE [ID] IN ({0})",ints.toIntCSV());
      //perform sql command
     }
     catch (ArgumentNullException)
     {
        MessageBox.Show("Invalid input");
     }
  }

Note, unfortunately you cannot use a parameterized query in this instance, but be sure to use them elsewhere.

share|improve this answer
    
you first method assumes i already have a list of ints. As mentioned this is a string. –  CSharpNewBee Feb 17 at 13:54
    
Im confused, if you already have a string there is no need to convert it? –  Simon Feb 17 at 13:57
    
So my string of '4,5'6 is not treat as an integer, due to SQL not being able to handle a list, hence I get nvarchar conversion error. –  CSharpNewBee Feb 17 at 14:00
    
What SQL backend are you using? Most SQL providers can handle the command: SELECT * FROM tableA WHERE id IN (WhereClause). Be sure to include the brackets. And finally you CANNOT pass a parameter to the query. @WhereClause will not work. You have to build the query in C# and send it direct. –  Simon Feb 17 at 14:04
    
thanks Simon, couldn't see the wood through the trees. Simply replaced the parameter with a standard where clause :-) –  CSharpNewBee Feb 17 at 14:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.