string table = "City";
string query = "Select * from '"+table+"'";
This gives me error stating incorrect symbol near ".
However,
string query = "Select * from City";
Gives the proper output.
string table = "City";
string query = "Select * from '"+table+"'";
This gives me error stating incorrect symbol near ".
However,
string query = "Select * from City";
Gives the proper output.
You just this
string query = "Select * from '"+table+"'";
to be replaced by
string query = "Select * from " + table;
Because you Query string is not "Select * from City";
While it is forming "Select * from 'City'";
and thus you getting error
Best practice would be to use string.format
string table = "City";
string query = string.format("Select * from {0}", table);
You need to form your query like below.,
string table = "City";
//You don't need to have single quote...
string query = " Select * From " + table;
In order to use Where
condition do like below.,
//Where clause only needs single quotes, to define the SQL parameter value in between...
string query = " Select * From " + table + " Where CityId = '" + cityId + "'";
Hope this helps.,
Best-Practice should be not to do this, because it's susceptible to malicious SQL injection.
Anyway, if you have control over the table
variable, you should do it as @madcow69 suggested, but I suggest to add the delimiters, so you always have a valid delimited identifier (for example if your table name is "order" or any other SQL reserved word).
string table = "City";
string query = string.format("Select * from [{0}]", table);
But what if table
is the following?:
string table = "City]; DROP DATABASE [YourDB";
You can make it work like this:
string table ="City"
string query = "Select * from "+table;
Hope this helps.,
string table = "City";
//You don't need to have single quote...
string query = " Select * From " + table;
If you're using .NET4.6
you could use the new "composite string formatting" feature introduced with C# 6.0
(read about it here).
this enables you to write your statement like this:
string query = $"Select * from {table}";
However I would strongly recommend not writing queries like that and use sql parameters. this will help you avoid SQL Injection attacks.