1

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?

sloth
  • 99,095
  • 21
  • 171
  • 219
Nerdsworth
  • 51
  • 1
  • 6
  • 2
    Please don't concat SQL statements like this, use SQL parameters. – Lloyd Feb 25 '14 at 12:46
  • Granted this code may be subject to SQL injection but a lot depends on context. The cost of heightened security may not be worth the expense if there is zero exposure. – rheitzman Feb 25 '14 at 15:52

1 Answers1

3

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
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286