Reputation: 125
I am new to SQL.
As show in screenshot, how can I get a any specific cell value according to column name?
This query can get you specific cell value according to the column name inside the query (the column name SizeM is fixed inside the query):
String s = Item1;
SqlCommand cm = new SqlCommand("SELECT SizeM FROM Table1 where Items = '" +s+ "' ");
The result is : JH
But I want to control the column name inside the query, for example I want to place a variable which carries the column name inside the query but if I do this it gives error stating that this variable is not column name, this is the code:
var C = SizeM;
String s = Item1;
SqlCommand cm = new SqlCommand("SELECT C FROM Table1 where Items = '" + s+ "' ");
Anyone knows how can I control the column name according to a variable which has the column name so I can get any cell value according to this variable. Thank you
Upvotes: 1
Views: 1243
Reputation: 558
You can use string concatenation in SQL Query string. Here i Take variable Columns to store Columns value and concatenate in to SQL Query.
string Columns = "SizeL, SizeM"; // Dynamic Columns Goes Here
String s = Item1;
SqlCommand cm = new SqlCommand("SELECT "+ Columns +" FROM Table1 where Items = '" +s+ "' ");
Or Even you can use array of columns
string ParaCol = "2,3";
string[] iCol = ParaCol.split(',');
string[] Table1Colms = {"Items", "Sizes", "SizeM","SizeL"};
string Columns = "";
for(int i =0 ; i < Table1Colms.Count() ; i++)
{
if(iCol.contains(i.ToString()))
{
Columns = Columns != ""? Columns + ", " + Table1Colms[i] : Columns + Table1Colms[i];
}
}
SqlCommand cm = new SqlCommand("SELECT "+ Columns +" FROM Table1 where Items = '" +s+ "' ");
Upvotes: 1
Reputation: 27861
You can do it like this:
String s = Item1;
string column_name = "SizeS";
SqlCommand cm = new SqlCommand("SELECT " + column_name + " FROM Table1 where Items = '" +s+ "' ");
Upvotes: 1
Reputation: 20620
I think you want this:
String s = Item1;
String Column = "SizeL";
SqlCommand cm = new SqlCommand("SELECT " + Column + " FROM Table1 where Items = '" +s+ "' ");
Upvotes: 2