我正在运行存储过程,结果是这种格式
+------+--------+-----+-------+
| ID | Resign | Sum | Count |
+------+--------+-----+-------+
| 1234 | 0 | 400 | 3 |
| 1234 | 1 | 800 | 4 |
+------+--------+-----+-------+
我尝试使用此代码来引用查询返回的值,但它看起来不像我想要的那样工作
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand sc = new SqlCommand();
sc.CommandText = "usp_GetResignPool";
sc.CommandType = CommandType.StoredProcedure;
sc.Connection = conn;
sc.Parameters.Add(AddParam(EndDate, "@EndDate"));
sc.Parameters.Add(AddParam(am_id, "@id"));
SqlDataReader reader;
reader = sc.ExecuteReader();
while (reader.Read())
{
if reader. // lost here
}
int resigned = 0, resign_count = 0, not_resigned = 0, notresign_count =0;
if (read["Resigned"] == 1)
{
resigned = read["sum"];
resign_count = read["count"];
}
else
{
not_resigned = read["sum"];
notresign_count = read["count"];
}
使用SQLDataReader并不重要。
编辑:实名列
ID Resigned sum count
--------- ----------- ---------------------- -----------
答案 0 :(得分:3)
它不起作用,因为您的表中没有名为"Resigned"
的列,就像您使用SqlDataReader
时一样。
编辑:我认为问题的根源在于您添加参数的方式。 AddParam()
不是您要使用的方法。因此,您的结果集可能是空的。
....
SqlCommand sc = new SqlCommand();
sc.CommandText = "usp_GetResignPool";
sc.CommandType = CommandType.StoredProcedure;
sc.Connection = conn;
sc.Parameters.AddWithValue("@EndDate", EndDate);
sc.Parameters.AddWithValue("id", am_id);
SqlDataReader reader;
reader = sc.ExecuteReader();
using (reader = sc.ExecuteReader())
{
while (reader.Read())
{
if (Convert.ToInt32(read["Resign"]) == 1)
{
resigned = Convert.ToInt32(read["Sum"]);
resign_count = Convert.ToInt32(read["Count"]);
}
else
{
not_resigned = Convert.ToInt32(read["Sum"]);
notresign_count = Convert.ToInt32(read["Count"]);
}
}
}
注意我如何将元素指示器更改为"Resign"
。这需要匹配数据集中返回的列。或者,您可以使用列号来实现此目的,如下所示:
if (Convert.ToInt32(read[1]) == 1)
{
resigned = Convert.ToInt32(read[2]);
resign_count = read[3];
}
else
{
not_resigned = Convert.ToInt32(read[2]);
notresign_count = Convert.ToInt32(read[3]);
}
另外,在每次迭代或while
循环中保留我的内容,您将覆盖变量resigned
,resign_count
或{{1} }和not_resigned
。
答案 1 :(得分:1)
这会有用吗?
int resign = 0;
int not_resign = 0;
int resign_count = 0;
int not_resign_count = 0;
while (reader.Read())
{
if (Convert.ToInt32(reader["Resigned"]) == 1)
{
resign = Convert.ToInt32(reader["Sum"]);
resign_count = Convert.ToInt32(reader["Count"]);
}
else
{
not_resign = Convert.ToInt32(reader["Sum"]);
not_resign_count = Convert.ToInt32(reader["Count"]);
}
}
答案 2 :(得分:0)
您可以从程序中发布查询吗? 列名是否真的是“Sum”和“Count”? 有保留字,也许您应该尝试使用“AS”并在投影中为这些列指定其他名称。