Nerdsworth
Nerdsworth

Reputation: 51

What is the missing operator in this sql query?

This is from a VB.Net program:

Dim cmd As String = "SELECT * FROM Employees WHERE Employee Name LIKE '%" & TextBox1.Text & "%';"

When it executes, it says that there is a syntax error (missing operator) in query expression 'Employee Name LIKE '%some text here%'

What am I missing here?

Upvotes: 1

Views: 729

Answers (1)

Steve
Steve

Reputation: 216342

If Employee Name is the name of your column then you have to put square brackets around it to avoid confusing the parser.

Dim cmd As String = "SELECT * FROM Employees WHERE " & _ 
                    "[Employee Name] LIKE '%" & TextBox1.Text & "%';"

And remember that string concatenation to build sql query is a real danger.
A parameterized query is always the way to go.

Supposing that you are working with Sql Server

Dim cmd As String = "SELECT * FROM Employees WHERE " & _ 
                    "[Employee Name] LIKE @name"
Using con = new SqlConnection(.....)
Using cmd = new SqlCommand(cmd, con)
   con.Open()
   cmd.Parameters.AddWithValue("@name", "%" & TextBox1.Text & "%")
   Using reader = cmd.ExecuteReader()
        .....
   End Using
End Using
End Using

Upvotes: 3

Related Questions