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 

devx-admin

Share the Post: