1

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

1
  • You'r approach is called quirky update. There's a great article by Jeff Moden on it. This can be used and is very fast - but there are side-effects you must know about and some condtions to clear in advance in order to get a reliable result. If performance is not the most important for you, rather use other approaches like FOR XML or STRING_AGG (see the existing answer). Commented Oct 30, 2018 at 10:49

1 Answer 1

2

One Final Edit: Updated my solution to include parenthesis.

That approach works by appending the values from dbo.dice to your variable, @concatString. It's not reliable; see this article. You can use FOR XML PATH or STRING_AGG on 2017+. Both methods are nasty fast. When using FOR XML PATH you must include an ORDER BY if the order of items must be guaranteed. STRING_AGG is my favorite method by far.

-- Sample data
DECLARE @dice TABLE (dice1 TINYINT);
INSERT @dice(dice1)
VALUES(1),(2),(3),(4),(5),(6);

-- Solution #1: FOR XML PATH
SELECT newString = STUFF((
SELECT   ',('+CAST(d.dice1 AS VARCHAR(8000))+')'
FROM     @dice AS d
ORDER BY d.dice1
FOR XML PATH('')),1,1,'');

-- Solution #2: STRING_AGG (SQL 2017+)
SELECT newString = STRING_AGG(CONCAT('(',d.dice1,')'),',') WITHIN GROUP (ORDER BY d.dice1)
FROM     @dice AS d;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Alan, are you suggesting that I do not use the approach I posted (it does work). I was really looking to try to understand the logic as to how the string is built up in the sql I posted.
Yes - sorry, I only pasted my code and deleted my comments. See my updated post. Yes, that method is not reliable (though I've never personally had a problem with it). The for XML PATH and STRING_AGG methods are the way to go

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.