6

我正在使用 Visual Studio 2010 和 SQL Management Studio R2 虽然 sql 查询在 sql management studio 中运行良好。它在视觉工作室中引发异常。超出索引异常,当我编辑以进行任何其他调整时,它会引发超出格式异常。请帮我。代码如下:

 string sql = "SELECT DISTINCT Year(tdate) FROM saletransaction ORDER BY Year(tdate) DESC";
 cmd = new SqlCommand(sql, con);                
 dr = cmd.ExecuteReader();
 DateTime dt;
 while (dr.Read())
 {
     if (dr.HasRows == true)
     {
         dt = Convert.ToDateTime(dr["tdate"].ToString()); //tdate is the name of the column (getting an error at this line. )
         comboBox1.Items.Add(dt.Year.ToString());
     }
 }
4

3 回答 3

4

您不是在选择tdate,而是在选择Year(tdate)

我会将查询修改为:

string sql = "SELECT DISTINCT Year(tdate) AS tdate_year FROM saletransaction ORDER BY Year(tdate) DESC";

并使用dr["tdate_year"]

于 2013-05-02T08:37:53.580 回答
3

您错过了在 sql 查询中给出列名

尝试这个

string sql = "SELECT DISTINCT Year(tdate) AS tdate FROM saletransaction ORDER BY Year(tdate) DESC";
于 2013-05-02T08:39:11.567 回答
3

看起来您没有为tdate查询提供别名。因此,当您尝试引用时tdate,该列不存在并且 Visual Studio 会引发错误。

将查询更改为:

 string sql = "SELECT DISTINCT Year(tdate) AS tdate FROM saletransaction ORDER BY Year(tdate) DESC";

这将返回列 name 下的所有结果tdate

于 2013-05-02T08:39:25.737 回答