I need use a query that'll get multiple rows and insert it in an Array. Please refer to the example below.
Ex.
[Day] | [Fruit]
01/02/2014 | {A, B, C, D}
01/03/2014 | {A, C, D}
01/04/2014 | {A, B, D, E}
01/05/2014 | {A, C}
01/06/2014 | {A, B, C, D, E}
01/07/2014 | {A}
Here's my code:
using (var conn = new SqlConnection("DataSource Here"))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT DISTINCT [Fruit], [DateReceive] FROM [FruitsDB].[dbo].[dummy] WHERE [Location]=@loca AND [DateReceive] BETWEEN '2014-01-02' AND '2014-01-07' ORDER BY [DateReceive]";
cmd.Parameters.AddWithValue("@loca", DropDownList1.SelectedValue.ToString());
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["Fruit"];
if (tmp != DBNull.Value || tmp2 != DBNull.Value)
{
ListBox1.Items.Add(tmp.ToString());
}
IList<string> list1 = new List<string>();
foreach (var items in ListBox1.Items)
{
list1.Add(items.ToString());
}
lbList.Text = string.Join(",", list1);
}
}
}
}
I hope you can help me guys.
SOLVED
-Using Christian G.'s FOR XML query
HERE'S THE SOLUTION
Thank you Mr. Christian Graus for helping me!
replacement for cmd.CommandText above
SELECT DAY(o.DateReceive) AS DayReceive,
STUFF
(
(SELECT ',' + convert(varchar(99), s.Fruit)
FROM [FruitsDB].[dbo].[dummy] s
WHERE DAY(s.DateReceive) = DAY(o.DateReceive)
AND Location = 'Quezon'
GROUP BY s.Fruit
ORDER BY s.Fruit
FOR XML PATH('')
), 1, 1, ''
) AS Fruit
FROM [FruitsDB].[dbo].[dummy] o
WHERE o.DateReceive IS NOT NULL
GROUP BY Day(o.DateReceive)
RESULT:
[Day] | [Fruit]
2 | Apple, Orange, Grapes, Lemon
3 | Apple, Figs, Lemon
4 | Apple, Figs, Grapes, Strawberry
5 | Grapes, Lychee, Strawberry
6 | Apple, Orange, Grapes
7 | Apple, Figs, Grapes, Lychee