0

I keep getting an error while trying to parse a parametrized query. Error: Token in error = @tableName

Seems that everything is ok with the variables, tried passing strings still the same.

using (SqlCeCommand command = new SqlCeCommand("SELECT * FROM @tableName WHERE @columnName = @id", connection))
            {
                command.Parameters.Add(new SqlCeParameter("tableName", tableName));
                command.Parameters.Add(new SqlCeParameter("columnName", column));
                command.Parameters.Add(new SqlCeParameter("id", id));

EDIT1:

Yes it might be wrong way of querying the database. For example if you need to access different tables at a different time of runtime whats the most suitable way of doing it. I mean the architecture of the class which accesses the database.

I am trying to use this to access two tables at a different runtime. I just pass these three variables and return the output.

P.S apologise if im breaking the rules.

EDIT2:

Sorry if I didnt make it clear but theres my question.

What architecture(if I can call that) is better for accessing different database tables at a different time while running the application? I mean what would be your solution to that? Is it good or bad and so on.

DasBoot
  • 469
  • 6
  • 17
  • Read this post: http://stackoverflow.com/questions/1325044/dynamic-sql-passing-table-name-as-parameter – bp4D Jun 03 '14 at 16:55
  • 1
    You are not breaking the rules, but if you want directions you have to tell us where you want to go and we don't know that. Instead of telling us what solution you're using, [tell us what you want to do](http://meta.stackexchange.com/questions/66377/). – Dour High Arch Jun 03 '14 at 18:28

2 Answers2

0

I believe SqlCeCommand and SqlCommands work the same so parameters must be passed with a leading @ : "@Name".

Besides "TableName" and "columnName" in your query are supposed to be Sql object names, so don't parameterize them.

Build your query dynamically instead, then pass the filtering parameter @id.
You could try something like that:

using (SqlCeCommand command = new SqlCeCommand(string.Format("SELECT * FROM {0} WHERE {1} = @id", tableName, column), connection))
            {
                command.Parameters.Add(new SqlCeParameter("@id", id));
Gus
  • 46
  • 2
0

You cannot put parameters on table names and columns. I am seeing also you are using SQL Compact edition. You can set your command in C# like this:

sqlCommand.CommandText = "SELECT * FROM " + yourtablename + " WHERE " + yourcolumnname+" LIKE @param";
sqlCommand.Parameters.Add("@param", SqlDbType.NVarChar).Value = paramVal + "%"; 

FYI, you should be aware that this code is open to SQL Injection.

Bura Chuhadar
  • 3,653
  • 1
  • 14
  • 17