如何将asp.net中调用的存储过程的结果转换为以逗号分隔的列表?
然后,此列表将用作另一个存储过程的参数。
我使用的是C#,Visual Studio 2010,asp.net 4.0版,SQL Server 2008 R2。
我正在创建批量报告并通过电子邮件发送出去。
这是我到目前为止所拥有的:
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["SomeConnectString"].ConnectionString);
con.Open();
using (var command = new SqlCommand("Report_FilterSproc", con)
{
CommandType = System.Data.CommandType.StoredProcedure
})
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something here to convert these results to a comma-separated list.
}
};
con.Close();
答案 0 :(得分:2)
您可以使用List<string>
和string.join
List<string> lstString = new List<string>();
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["SomeConnectString"].ConnectionString);
con.Open();
using (var command = new SqlCommand("Report_FilterSproc", con))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lstString.Add(reader["ColumnName"].ToString());
//do something here to convert these results to a comma separated list.
}
}
}
con.Close();
string result = string.Join(",", lstString.ToArray());
顺便说一下,请以正确的方式使用SqlCommand
。
答案 1 :(得分:0)
一种方法,使用ICollection<String>
,构建它,然后使用String.Join()
将其转储为CSV格式:
/* ... */
ICollection<String> values = new HashSet<String>();
while (reader.Read())
{
values.Add(/*reader value*/);
}
String csv = String.Join(",", values);
另一个选择是使用StringBuilder
:
/*...*/
var builder = new StringBuilder();
while (reader.Read())
{
builder.Append(builder.Length > 0 "," : "").Append(/*reader value */);
}
String csv = builder.ToString();
答案 2 :(得分:-1)
SqlConnection con = new
SqlConnection(WebConfigurationManager.ConnectionStrings["SomeConnectString"].ConnectionString);
con.Open();
List<string> lt = new List<string>();
using (var command = new SqlCommand("Report_FilterSproc", con)
{
CommandType = System.Data.CommandType.StoredProcedure
})
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lt.add(reader.GetString(1));
}
};
con.Close();
doStuff(string.Join<string>(";", lt);