【问题标题】:How to dynamically get cell value from SQL table?如何从 SQL 表中动态获取单元格值?
【发布时间】:2015-12-30 17:21:54
【问题描述】:

我是 SQL 新手。

如屏幕截图所示,如何根据列名获取任何特定的单元格值?

这个查询可以根据查询内的列名得到你具体的单元格值(列名SizeM在查询内是固定的):

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

结果是:JH

但是我想控制查询中的列名,例如我想在查询中放置一个带有列名的变量,但是如果我这样做,它会给出错误,说明这个变量不是列名,这是代码:

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

任何人都知道如何根据具有列名的变量控制列名,以便我可以根据该变量获取任何单元格值。谢谢

【问题讨论】:

  • 当您使用变量作为列名时,您的代码在哪里?
  • @Shaharyar。我更新了它
  • 您实际上没有使用该变量。像使用 s 一样使用它。

标签: c# sql


【解决方案1】:

我想你想要这个:

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

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

【讨论】:

  • 只是挑剔,但局部范围的变量应该是小写的。所以,column 不是 Column
  • 如果能指导OP预防SQL注入就更好了。
  • @JamesRalston 这不是挑剔,而是错误地假设您的标准是正确的,而其他人的标准都是错误的。
  • @Shaharyar 我差点就 SQL 注入向 OP 提出建议,但我们不知道数据来自哪里,我不想让他感到困惑。
  • @SteveWellens 非常正确。我想我是在挑剔,因为语法突出显示使它显示为一种类型。团队决定什么是最好的,只要它是一致的。
【解决方案2】:

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

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

或者你甚至可以使用列数组

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

【讨论】:

    【解决方案3】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多