Datareader不使用Select Upper和Group By Upper

时间:2015-09-01 16:12:29

标签: c# sql database sqldatareader

我正在尝试使用Visual Studio 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中的名字,发现公司应该有一个空字符串的索引。我用我的selectCommand字符串替换了公司的UPPER(公司),它运行正常,所以使用UPPER()命令以不正确的名称初始化DataReader。

有人知道修复吗?

2 个答案:

答案 0 :(得分:2)

将您的查询更改为:

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

如果在不应用别名的情况下应用UPPER之类的sql函数,则返回(No column name)作为结果。

答案 1 :(得分:1)

尝试重新输入名称:

SELECT UPPER(Company) AS Company ...