I've seen solutions using UDFs in SQL 2000, but they are scary - they're basically doing a brand-new SELECT
for every group that might be executed hundreds or thousands of times. You're actually better off using a cursor:
DECLARE @Temp TABLE
(
Company int NOT NULL PRIMARY KEY,
Employees varchar(4000) NOT NULL
)
DECLARE
@LastCompany int,
@Company int,
@Employee varchar(100),
@Employees varchar(4000)
DECLARE crEmployee CURSOR FAST_FORWARD FOR
SELECT Company, Employee
FROM @Tbl
ORDER BY Company
OPEN crEmployee
FETCH NEXT FROM crEmployee INTO @Company, @Employee
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF (@LastCompany IS NULL)
SET @Employees = @Employee
ELSE IF (@Company = @LastCompany)
SET @Employees = @Employees + ',' + @Employee
ELSE BEGIN
INSERT @Temp (Company, Employees)
VALUES (@LastCompany, @Employees)
SET @Employees = @Employee
END
SET @LastCompany = @Company
FETCH NEXT FROM crEmployee INTO @Company, @Employee
END
CLOSE crEmployee
DEALLOCATE crEmployee
IF (@Employees IS NOT NULL)
INSERT @Temp (Company, Employees)
VALUES (@LastCompany, @Employees)
SELECT * FROM @Temp
There's a solution using a temporary table and UPDATE
similar to that used to compute running totals, but it's a beast to look at and in most cases won't do much better than the cursor for performance.
If anyone really desperately wants to see the UPDATE
version, I'll post it, but I suggest trying the cursor version first and seeing if it's "good enough."