6
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.

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
subhro
  • 171
  • 1
  • 2
  • 14

7 Answers7

5

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

Mohit S
  • 13,723
  • 6
  • 34
  • 69
3

Best practice would be to use string.format

string table = "City";
string query = string.format("Select * from {0}", table);
Madcow69
  • 31
  • 1
  • 2
2

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.,

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
1

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";
thepirat000
  • 12,362
  • 4
  • 46
  • 72
0

You can make it work like this:

string table ="City"
string query = "Select * from "+table;
Abhash Upadhyaya
  • 717
  • 14
  • 34
0

Hope this helps.,

string table = "City";

//You don't need to have single quote...

string query = " Select * From " + table; 
Coder
  • 240
  • 2
  • 4
  • 20
0

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.

Community
  • 1
  • 1
Yoav
  • 3,326
  • 3
  • 32
  • 73