devxlogo

Generating SQL for List of Options

Generating SQL for List of Options

Question:
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 isThe user can only select one state. How can I pass the whole list box, so in a way the sql statement would readwhere [Econometrics Databse].States = Illinois, New York, Washington, etc.

Answer:
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 StringDim i as integerDim 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 statementFor 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      Else         Exit For                 ' found last selected item so exit loop.      End If   End IfNext i' At this point, sTmp has your entire SQL statement in it.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist