2015-12-30 46 views
1

我是SQL新手。如何从SQL表中动态获取单元格值?

screenshot

正如秀截图,如何能根据列名,我收到了任何特定的单元格的值?

String s = Item1; 
SqlCommand cm = new SqlCommand("SELECT SizeM FROM Table1 where Items = '" +s+ "' "); 

结果是:JH

但我

这种查询可以根据查询(列名SizeM固定在查询中)内列名给你具体的单元格的值想要控制查询中的列名,例如我想要在查询中放置一个带有列名称的变量,但是如果我这样做,它会给出错误提示该变量不是列名,这是代码:

var C = SizeM; 
String s = Item1; 
SqlCommand cm = new SqlCommand("SELECT C FROM Table1 where Items = '" + s+ "' "); 

任何人都知道如何根据具有列名称的变量来控制列名,以便根据此变量获得任何单元格值。谢谢

+1

string Columns = "SizeL, SizeM"; // Dynamic Columns Goes Here String s = Item1; SqlCommand cm = new SqlCommand("SELECT "+ Columns +" FROM Table1 where Items = '" +s+ "' "); 

甚至可以使用数组哪里是你的代码时,你使用的列名的变量? – Shaharyar

+0

@ Shaharyar。我更新了它 – Serena

+1

你没有真正使用这个变量。像你使用's'一样使用它。 – Shaharyar

回答

1

您可以在SQL查询字符串中使用字符串连接。在这里,我以变量列 来存储列值并连接到SQL查询。列

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+ "' "); 
2

我想你想要这样的:

String s = Item1; 
String Column = "SizeL"; 

SqlCommand cm = new SqlCommand("SELECT " + Column + " FROM Table1 where Items = '" +s+ "' "); 
+0

只是nit挑选,但局部范围变量应该是较低的骆驼大小写。所以,'列'不'列' –

+1

如果你指导OP预防SQL注入会更好。 – Shaharyar

+0

@JamesRalston这不是挑剔,那是错误地认为你的标准是正确的,其他人都是错的。 –

1

你可以这样说:

String s = Item1; 
string column_name = "SizeS"; 
SqlCommand cm = new SqlCommand("SELECT " + column_name + " FROM Table1 where Items = '" +s+ "' ");