Search code examples
sqlvb.netoledbstring-concatenationoledbcommand

Syntax error in query. Incomplete query clause in Max statement inside a function


I am trying to simply connect to a database. But the problem arises in the concatenation part of the Sql query.

When I do:

 cmd = New OleDbCommand("Select max(ID) from Table1", con)

There is no error but when I do

 cmd = New OleDbCommand("Select max(ID) from'" & tablename & "'", con)

The vb.net error comes: Syntax error in query. Incomplete query clause.

Here is the full code

Function Get_Max(ByVal Get_Table_Name As String)
    Dim tablename As String = Get_Table_Name
    Dim found_max As Integer
    Call connect()
    con.Open()
    cmd = New OleDbCommand("Select max(ID) from'" & tablename & "'", con)
    dr = cmd.ExecuteReader
    While dr.Read
        found_max = dr(0)
    End While
    con.Close()
    MsgBox(found_max)

    Return found_max

End Function

Solution

  • Do not put single quotes around the variable tablename

    cmd = New OleDbCommand("Select max(ID) from " & tablename, con)
    

    Otherwise the tablename variable becomes a literal string and, from the database point of view you are requesting the MAX(ID) of the string 'Table1'.

    A part from this you should be absolutely sure about the value of the variable tablename.

    Do not allow the end user to directly type this value (at least let him choose between a list of predefined names).
    This kind of code is very weak and open to Sql Injections.

    And, as other answers have already outlined, a couple of Square Brackets around the table name are required if one or more of your tables contains a space or have the same name as a reserved keyword

    cmd = New OleDbCommand("Select max(ID) from [" & tablename & "]", con)