I have seen the below as a solution to concatenating the values of a number of rows into a single string, however I cannot understand how it actually works.
DECLARE @ConcatString nvarchar(max);
SELECT @ConcatString = COALESCE(@ConcatString + ', ['+ cast([Dice1] as
nvarchar(10)) + ']', '['+ cast([Dice1] as nvarchar(10)) + ']')
FROM [dbo].[Dice]
SELECT @ConcatString
Output: [1], [2], [3], [4], [5], [6]
Please could you explain how it works, and if there are any risks using this approach.
Thanks in advance
FOR XMLorSTRING_AGG(see the existing answer).