A bit late to the party. To answer the second part of the question
is there any other or short way to do this
There is. I am sure this explanation exists in the vasts of the SO, but I did not look for.
The code below does exactly the same thing as STUFF( SELECT .. FOR XML PATH
.
DECLARE @agg VARCHAR(MAX)
SELECT @agg = CONCAT(@agg + ',', name) FROM temp1
SELECT @agg
When @agg
is declared, its value is NULL
.
When the first row of the temp1
is fetched @agg
is still NULL
.
@agg + ','
equals to NULL + ','
which results in NULL
.
See Microsoft Documentation
However, CONCAT(NULL, Name)
produces aaa
, not NULL
!
Then aaa
is stored in @agg
.
When the second row of the Temp1
is fetched CONCAT(@agg + ',', Name)
produces aaa,bbb
. Then this value is stored in @agg
.
And so forth