Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Oct 1, 1996



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Generating SQL for List of Options

This is the first time I visited your site, and its the best VB site I've been too! My question is, I'm writing a sql statement using Variables and vb controls. In the WHERE clause my code reads:
where [Econometrics Database].States = '" & list1.text & "'"
This would except the users selection. The problem is The user can only select one state. How can I pass the whole list box, so in a way the sql statement would read where [Econometrics Databse].States = Illinois, New York, Washington, etc.

Unfortunately, SQL doesn't work very well with multiple choices. However, you could build a dynamic SQL statement from the items in the list. Here's an example of how to do it. Assume that lbData is your list box, and assume that at least one item is selected. If not, just check that before building the where clause.

Dim sTmp as String
Dim i as integer
Dim iSelCount as Integer   ' need to keep track of the number of selected items
                           ' we've found.

sTmp = "(beginning part of SQL statement"
sTmp = sTmp & "WHERE "   ' Don't forget the spaces in the statement

For i = 0 to lbData.ListCount - 1  ' first item in list is numbered zero
   If lbData.Selected(i) Then
      iSelCount = iSelCount + 1
      sTmp = sTmp & "[Econometrics Database].States = '" & lbData.List(i) & "'"
      If iSelCount < lbData.SelCount Then   
         sTmp = sTmp & " OR "     ' more selections to come so add in an OR
         Exit For                 ' found last selected item so exit loop.
      End If
   End If
Next i

' At this point, sTmp has your entire SQL statement in it.
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date