title: Building a dynamic sql query from VB.NET
body: <p>I have searched and searched for an answer for this and I cannot find one.  I have a checked list box where the user will select issues they are experiencing with their computer.  In the checked list box you will see things like... Slow, Viruses, Bad Hard Drive... and based on what they select I will tell them an estimated cost for repair.  Currently this is how I build my query:</p>
  
  <pre><code>Dim mIssues As String = ""
  
  For i = 0 To lstIssues.CheckedItemsCount - 1
   If mIssues = "" Then
    mIssues = String.Format("IssueName = '{0}'", lstIssues.CheckedItems(i))
   Else
    mIssues = String.Format("{0} OR IssueName = '{1}'", mIssues, lstIssues.CheckedItems(i))               
   End If
  Next
  </code></pre>
  
  <p>The above code will look to see how many issues they have selected.  If they only select one issue then it will return a string like this: IssueName = 'Whatever they selected'.  If they have selected more than one issue it will return a string like this: IssueName = 'Whatever they selected' OR IssueName = 'The second selection'.  So basically I will append an OR between all the selections if they select more than one issue.  I do this to dynamically build my where clause in my query.  </p>
  
  <p>Here is my query:</p>
  
  <pre><code>Dim mySQL As String = "SELECT IssueID, IssueTypeID, IssueName, IssueDescription, " _
    &amp; "CustomerID, IndividualCost, GroupCost, Active, ChargeType " _
    &amp; "FROM (SELECT IssueID, IssueTypeID, IssueName, IssueDescription, " _
    &amp; "CustomerID, IndividualCost, GroupCost, Active, ChargeType " _
    &amp; "FROM(cfg_Issues) " _
    &amp; "WHERE " &amp; mIssues &amp; " " _
    &amp; "GROUP BY IssueID, IssueTypeID, IssueName, IssueDescription, CustomerID, " _
    &amp; "IndividualCost, GroupCost, Active) " _
    &amp; "ORDER BY IndividualCost DESC, GroupCost ASC;"
  </code></pre>
  
  <p>As you can see my where clause comes from the first section of code.  My question is this, is there a better way to do this???  I know there has to be a better way to build a dynamic where clause query and I would like to see how.  Thank you for any guidance you can help me with.</p>