Using variable in SQL WHERE clause

Using variable in SQL WHERE clause

How can I use the contents of a text box as the WHERE clause in a SQL query? “SELECT * FROM Table WHERE Field = Text1.Text” doesn’t work.

The SQL parser is expecting a string of the form:

  SELECT * FROM Table WHERE Field = 'Value'

if ‘Field’ contains text data, or

  . . .WHERE Field = Value

if ‘Field’ is numeric (note the lack of quotes around ‘Value’ in the latter example).

In order to use a variable (including the value of a control property) in a SQL query, you must insert its value, not its name, into the query string:

  SQL = "SELECT * FROM Table WHERE " & _        "Field = '" & txtBox.Text & "'"


Share the Post: