Variables in SQL Where clause
How do I write an SQL statement to use multiple where clauses. I am using user input
(text boxes and combo boxes) as criteria.
Web Development
How do I write an SQL statement to use multiple where clauses. I am using user input
(text boxes and combo boxes) as criteria.
by peyison
You can build the SQL statement on the fly using string concatenation. Say you have two combo boxes that contain field names and two corresponding text boxes that contain values to query on. Your code would look something like this:
sSql = "Select {insert field list} from tblTest Where " & cbxOne & "='" & txtOne & "' and " & cbxTwo & "=" & txtTwo
Note that in this example the field in the first combo box is type Text (need to put ' around the value in the text box) and the second is numeric. If you had a date field, you would have to wrap it in #s - like ...=#" & txtOne & "# and...
To make this more flexible, you could include the datatype (could use 1=num, 2=text, etc.) of each field in the table that the comboboxes are tied to, and use this when building each part of the where clause:
sSql = "Select {insert field list} from tblTest "
(For each combo box, get the field name and datatype, and set sValue = corresponding text box)
Select case iDataType
case 1 'num
sWhere = sFieldName & "=" & sValue
case 2 'text
sWhere = sFieldName & "='" & sValue & "'"
case 3 'date
sWhere = sFieldName & "=#" & sValue & "#"
end select
sSql = sSql & " Where " & sWhere
If you have many combos, you'll have to loop through each and concatenate the pieces of the Where clauses together, putting "And" between them.
Hope this helps.
by lizardo77
by dushy_ant
Try this piece of code. This code tries to capture the fields in which the user has made an entry and ignores the ones in which there are no entries.
StrCond = ""
StrCond = IIf(Trim(Text1.Text) <> "", StrCond & " and " & &"='" & Text1.Text & "'", StrCond)
StrCond = IIf(Trim(Text2.Text) <> "", StrCond & " and " & & "='" & Text2.Text & "'" , StrCond)
:
:
:
Likewise for each textbox
StrCond = IIf(Trim(cbo1.Text) <> "", StrCond & " and " & & "='" & cbo1.Text & "'" , StrCond)
:
:
Likewise for each ComboBox
If StrCond <> "" Then
StrCond = Right(StrCond, Len(StrCond) - 4)
sql = "Select * from where " & StrCond
Else
sql = "Select * from "
End If
Quotes can be removed from the code for numeric fields.
This code works fine in my PC.All the best to you
by lizardo77
by lizardo77
This discussion is closed to new replies.
Sort by Trending