【问题标题】:Datareader not working with Select Upper and Group By UpperDatareader 不使用 Select Upper 和 Group By Upper
【发布时间】:2015-09-01 16:12:28
【问题描述】:

我正在尝试在 Visual Studios 2015 Express 中使用 c# 从 Microsoft SQL 数据库中获取数据。到目前为止,我使用的所有命令都有效。现在我正在尝试使用 SqlDataReader 执行此命令:

SELECT UPPER(Company) FROM MY_TABLE GROUP BY UPPER(Company) HAVING COUNT(*) > 0;

这是我的代码:

//open the sql connection
sqlConn.Open();

/*
    * This Sql command will get the field entries from all the selected fields and group them into selection groups.
    * 
    * This is important because it gives a list of arguments to group docId's with.
    */

string selectCommand = "SELECT UPPER(Company) FROM MY_TABLE GROUP BY UPPER(Company) HAVING COUNT(*) > 0;";

// Declare list for storing select groups. This will be returned
List <String> groupList = new List<string>();

// Set up table reader
SqlCommand sqlcmd = new SqlCommand(selectCommand, sqlConn);
dataRead = sqlcmd.ExecuteReader();

for (int i = 0; i < dataRead.FieldCount; i++)
{

    Console.WriteLine("DATAREAD: '" + dataRead.GetName(i) + "' .");
}

while (dataRead.Read())
{
    // select string for selecting groups
    string select = "";
    foreach (string colname in staple.fieldsToList())
    {
        // check for null
        if(dataRead[colname] == DBNull.Value)
        {
            select = select + "NULL,";
        }else{
            select = select + dataRead[colname].ToString()
        }

    }
    //store the select string in a list
    groupList.Add(select);
}

return groupList;

当这段代码到达 dataRead[colname] 部分时,它会抛出一个错误:

System.IndexOutOfRangeException: Company

所以我检查了 dataRead 中的名称,发现 Company 的索引应该是一个空字符串。我用 Company 替换了我的 selectCommand 字符串中的 UPPER(Company) 并且它工作正常,所以不知何故使用 UPPER() 命令会使 DataReader 在没有正确名称的情况下初始化。

有人知道解决办法吗?

【问题讨论】:

    标签: c# sql database sqldatareader


    【解决方案1】:

    将您的查询更改为:

    SELECT UPPER(Company) As Company FROM MY_TABLE GROUP BY UPPER(Company) HAVING COUNT(*) > 0;
    

    如果你应用像UPPER 这样的sql 函数而不应用别名,它会返回(No column name) 作为结果。

    【讨论】:

    • 效果很好!谢谢。
    【解决方案2】:

    试着把名字放回去:

    SELECT UPPER(Company) AS Company ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2016-10-12
      • 2022-01-13
      相关资源
      最近更新 更多