How to insert a variable inside a Select statement

string table = "City"; string query = "Select * from '"+table+"'"; 

This gives me an error indicating the wrong character next to ".

but

 string query = "Select * from City"; 

Gives the correct conclusion.

+6
source share
7 answers

You only that

 string query = "Select * from '"+table+"'"; 

replaced by

 string query = "Select * from " + table; 

Because the query string is not "Select * from City"; While she forms "Select * from 'City'";

and therefore you get an error

+5
source

Best practice would be to use string.format

 string table = "City"; string query = string.format("Select * from {0}", table); 
+3
source

You need to form your request as shown below.

 string table = "City"; //You don't need to have single quote... string query = " Select * From " + table; 

To use the Where clause, follow these steps:

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

+2
source

Best practice should be to not do this because it is prone to malicious SQL injection.

In any case, if you have control over the table variable, you should do it as @ madcow69 suggested, but I suggest adding delimiters, so you always have a valid delimited identifier (for example, if your table name is β€œorder” or whatever another SQL reserved word).

 string table = "City"; string query = string.format("Select * from [{0}]", table); 

But what if table following ?:

 string table = "City]; DROP DATABASE [YourDB"; 
+1
source

You can make it work as follows:

 string table ="City" string query = "Select * from "+table; 
0
source

Hope this helps.,

 string table = "City"; //You don't need to have single quote... string query = " Select * From " + table; 
0
source

If you are using .NET4.6 , you can use the new "compound string formatting" feature introduced with C# 6.0 (read about it here) .
this allows you to write your expression as follows:

 string query = $"Select * from {table}"; 

However, I would strongly recommend against writing such queries and using sql parameters . this will help you avoid SQL injection attacks.

0
source

All Articles