Other answers explained why this creates a comma-separated list. You will notice that at the end you will get an extra comma, which you can remove after that if you want. If you are using SQL Server 2005 or later, you can use COALESCE
and not have this comma:
SELECT @MyList = COALESCE(@MyList + ', ','') + Title FROM Titles
For the first line, @MyList
will be NULL
, so @MyList + ', '
will be evaluated to NULL
, and COALESCE
will return. ''
Essentially, processing the first line does this:
SELECT @MyList = '' + Title
For subsequent lines, COALESCE
will return @MyList + ', '
and you will get the equivalent
SELECT @MyList = @MyList + ', ' + Title
.
source share