A multiple assignment variable, sometimes called an aggregate concatenation, is a fascinating method that appends a variable to itself using a select statement. Though nearly undocumented, the method's been around since at least SQL Server 2000. It’s been bashed as a kludge and hack by some and revered as the embodiment of elegance by others. The primary complaint has been that the sort order of the concatenation is not guaranteed by the SQL statement. Using a multiple assignment variable method depended on the behavior of the engine instead of on the declarative nature of SQL - Horrors to even a non-purist pragmatic minded fellow such as myself.
But, while writing about this technique for SQL Server 2008 Bible, I discovered (are you sitting down?) that SQL Server 2008 does indeed respond to an order by in a multiple assignment variable query!
The first query has an order by name:
USE AdventureWorks2008;
Declare @MAV VARCHAR(max)
SELECT @MAV = Coalesce(@MAV + ', ' + Name, Name)
FROM (select name, DepartmentID from HumanResources.Department) D
order by name
Select @MAV
Result:
--------------------------------------
Changed Name, Document Control, Engineering, Executive, Facilities and Maintenance, Finance, Human Resources, Information Services, Marketing, Production, Production Control, Purchasing, Quality Assurance, Research and Development, Sales, Shipping and Receiving, Test Two, Tool Design
Change the order by clause and re-run the query:
Declare @MAV VARCHAR(max)
SELECT @MAV = Coalesce(@MAV + ', ' + Name, Name)
FROM (select name, DepartmentID from HumanResources.Department) D
order by DepartmentID
Select @MAV
Result:
--------------------------------------
Engineering, Tool Design, Sales, Marketing, Purchasing, Research and Development, Production, Production Control, Human Resources, Finance, Information Services, Document Control, Quality Assurance, Facilities and Maintenance, Shipping and Receiving, Executive, Changed Name, Test Two
I haven’t tested MAV and order by on SQL Server 2005 for quite some time. I don’t recall it responding to order by in 2005, but I could be wrong. In any case it works great in 2008. If this is a new improvement in 2008, then I sure missed it in the Microsoft presentations.