Search code examples
c#asp.netvisual-studio-2010sql-server-ceparameterized-query

error with SqlCe Parameters


I have made MANY parameterised queries in my time on this lovely planet, and none have thrown an error like this... WTFudge?!?!

ERROR:

There was an error parsing the query. [
Token line number = 1,
Token line offset = 20,
Token in error = @table ]

Obviously the compiler doesn't like my SQL statement... but I see no problem???

Here is my code.

using (SqlCeConnection con = new SqlCeConnection(_connection))
{
    string sqlString = "SELECT @colID FROM @table WHERE @keyCol = @key";

    SqlCeCommand cmd = new SqlCeCommand(sqlString, con);
    cmd.Parameters.Add(new SqlCeParameter("@table", tableName));
    cmd.Parameters.Add(new SqlCeParameter("@colID", columnIdName));
    cmd.Parameters.Add(new SqlCeParameter("@keyCol", keyColumnName));
    cmd.Parameters.Add(new SqlCeParameter("@key", key));

    try
    {
        con.Open();
        return cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.Write(ex.Message);
        throw new System.InvalidOperationException("Invalid Read. Are You Sure The Record Exists", ex);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
            con.Close();
        cmd.Dispose();
        GC.Collect();
    }
}

as you can see its a VERY simple SQL statement. I though "@table" may have been stupidly reserved or something... so ive tried @tableName, @var, @everything!!! dont know what the problem is.

During debug I checked that there was actually a @table parameter in the SqlCeParameterCollection And it was there. Clear as day!!

Image: Debug Information


Solution

  • Since you are in C# (as opposed to stored procs)

    string sqlString = "SELECT " + columnIdName + 
    " FROM " +tableName "WHERE " + keyColumnName + "= @key";
    

    You will want to verify that columnIdName, tableName, keyColumnName are all restricted to a list of values (or at the very least, restrict the length to, say 50 characters), otherwise this procedure is optimized for insecurity and sql injection attacks.