Itzik Ben-Gan explains in his book ‘Inside Microsoft® SQL Server® 2008: T-SQL’ how Appoach A works, because of the undocumented behavior of SQL Server in which it performs assignment for each result record from the SELECT.
A well respected collegue and DB guru has suggested that Approach B is guaranteed to work. His argument is based on the recursive nature of COALESCE versus the ‘values expansion’ method of CAST.
Actually, I have no idea what ‘values expansion’ refers to (except for the fact that it is casting one value to another) or how it applies to this problem? Perhaps he misunderstood? Yes COALESCE is recursive in a sense, but as far as I can see it is irrelevant and the desired result is produced because of the undocumented behavior of multiple assignment.
Is he correct? Please, no “Use FOR XML PATH instead” answers!
Approach A
DECLARE @output VARCHAR(100);
SET @output = '';
SELECT @output = @output + CAST(COL_VCHAR AS VARCHAR(10)) + ';'
FROM someTable;
Approach B
DECLARE @output VARCHAR(100);
SELECT @output = COALESCE(@output + ', ', '') + COL_VCHAR
from someTable;
Since a conforming SQL implementation could evaluate all of the output rows simultaneously, in parallel, neither is guaranteed to work. That they happen to work, today, is an artifact of the current SQL Server implementation.
Your colleague is incorrect to assert that
COALESCEsomehow changes the processing model.I.e. a conforming implementation could effectively hand each potential row in the result set (having evaluated
FROMandWHERE) to a separate thread, that then performs whatever processing is required in theSELECTclause (before presumably recombining results in order to assessGROUP BY,HAVINGandORDER BY).There are no standard requirements governing access to variables during such processing, so each thread could “see” the same initial value of
@output(NULLor'', depending on which form you’re using), perform it’s own update calculation, and assign that result value to@output– the final value of@outputmight then any of the individual row results – or anything else for that matter.