Question

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

Was it helpful?

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.

OTHER TIPS

This affected me too on SqlCe. But in Sql Server and in SqlExpress you can use a paarameter for table name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top