简体   繁体   中英

How can I turn the results of a stored procedure into a comma-separated list in asp.net?

How can I turn the results of a stored procedure called in asp.net into a comma-separated list?

This list will then be used as a parameter for another stored procedure.

I'm using C#, Visual Studio 2010, asp.net version 4.0, SQL Server 2008 R2.

I'm creating batch reports and emailing them out.

Here's what I have so far:

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();

You can create comma seperated string using List<string> and 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());

BTW, please use the SqlCommand using in the right way.

One method, use an ICollection<String> , built it up then use String.Join() to dump it as a CSV:

/* ... */
ICollection<String> values = new HashSet<String>();
while (reader.Read())
{
    values.Add(/*reader value*/);
}
String csv = String.Join(",", values);

Another options is to use a StringBuilder :

/*...*/
var builder = new StringBuilder();
while (reader.Read())
{
    builder.Append(builder.Length > 0 "," : "").Append(/*reader value */);
}
String csv = builder.ToString();
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM