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 & "'"

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