I'm porting an application I originally wrote to run on Apache using PHP and a MySQL database. One of the queries used the MySQL functions of Concat_WS
and Group_Concat
to first concatenate a few different columns into one string, and then concatenate all items that were grouped together by the Group_By
clause.
As an example:
ID Name Candy
1 John M&Ms
1 John KitKat
The query:
Select Group_Concat(Concat_WS('-',Name, Candy) Separator '00--00') as UserCandy
From ExampleTable
Group By ID
The result:
UserCandy
John-M&Ms00--00John-KitKat
Now, I am trying to accomplish the same result in SQL Server 2008 using PHP 5.4+.
What I've tried:
SELECT Stuff(name + ';' + candy, 1, 0, '-----') AS UserCandy
FROM test
The problem can be seen in the fiddle that I have setup.
The expected result would be:
-----John;MMs-----John;KitKat
Lastly, this becomes even more difficult when I add more columns to the mix. I want to merge the results (as shown above) where the ID is the same. This works very well with group_concat
because it will automatically merge rows that have been grouped together.