As I mentioned in the comment, the logic you have in your query is a documented antipattern. Effectively you are relying on that query is row in a row by row basis, and for each row the variable is updated.
So, you are hoping, that the variable is first set to the value '' + 's,'
(which is 's,'
), then for the second row, the prior rows value of variable would be used ('s,'
) and concatenated to the next ('r'
), resulting in 's,r,'
. For the third row, again use the prior rows value of variable ('s,r,'
) and concatenate it to the next ('i'
), resulting in 's,r,i'
. Repeat until you get to the end of the dataset.
Per the documentation, however, there is no guarantee that'll actually happen though:
In this case, it is not guaranteed that @Var
would be updated on a row by row basis. For example, @Var
may be set to initial value of @Var
for all rows. This is because the order and frequency in which the assignments are processed is nondeterminant. This applies to expressions containing variables string concatenation, as demonstrated below, but also to expressions with non-string variables or += style operators. Use aggregation functions instead for a set-based operation instead of a row-by-row operation.
So this means you could simply end up with a single delimited value like 'u,'
, or perhaps some missing values (maybe 'n,u,'
) due to when the rows and variable assignments were processed.
Instead, as the documentation also states, use string aggregation. On all (fully) support versions of SQL Server, that would be STRING_AGG
:
SELECT @var = STRING_AGG(name,',')
FROM dbo.Names;
If you are on an older version of SQL Server, then you would need to use the "old" FOR XML PATH
(with STUFF
) method, like shown in this question.