简体   繁体   中英

ASP.NET C# How to retrieve data from SQL Server and convert multi-row data into one row seperated by comma?

I have this table in SQL Server:

Colors
-----------
Grey
Black
Pink.Red

I wish to retrieve data from SQL Server and display in a label.

Expected output:

Grey,Black,Pink.Red

The code I have tried:

SqlCommand cmd2 = new SqlCommand("SELECT Colors FROM ROCK", con);
cmd.Connection.Open();
pdl.Text = cmd.ExecuteScalar().ToString(); // assign to label
cmd.Connection.Close();

Does anyone have any ideas?

you can try using STRING_AGG (this works only from SQL Server 2017 onwards)

SELECT STRING_AGG (Colors, ',') AS csv FROM ROCK; 

Or you can using STUFF & XML PATH

SELECT STUFF((SELECT ',' + Colors FROM ROCK FOR XML PATH('')), 1, 1, '')

STRING_AGG function is not available in sql server 2016. It is available in higher version of sql server. To achieve your task you can use LINQ and sting join function of C# .

For example take all row of sql data into a DataTable dt.

var res = string.Join(",", dt.AsEnumerable().Select(x =>x["Colors"]));

Or you can use COALESCE function of sql server like this

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + Colors 
FROM ROCK
SELECT @listStr  

Please use the below code in your .cs page

string color="";
for (int i = 0; i < Colors.Items.Count; i++)
        {
            if (Colors.Items[i].Selected == true)
            {
                color += Colors.Items[i].Text + ",";
            }
        }
        color = color.TrimEnd(',');
        pd1.text=color; 

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