Monday, April 11, 2011

Comma-Delimited Output

DECLARE cCustomerIDs CURSOR FOR
    SELECT [CustomerID] FROM [dbo].[Customers] ORDER BY [CustomerID]
DECLARE @CustomerIDs    VARCHAR(8000)
DECLARE @CustomerID     VARCHAR(10)

OPEN cCustomerIDs
FETCH NEXT FROM cCustomerIDs INTO @CustomerID
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @CustomerIDs = ISNULL(@CustomerIDs + ',', '') + @CustomerID
    FETCH NEXT FROM cCustomerIDs INTO @CustomerID
END

CLOSE cCustomerIDs
DEALLOCATE cCustomerIDs

SELECT @CustomerIDs AS CustomerIDs
GO
A sample output of this script is as follows, using just the first 10 Customer IDs from the Customers table.
CustomerIDs
-----------------------------------------------------------
ALFKI,ANATR,ANTON,AROUT,BERGS,BLAUS,BLONP,BOLID,BONAP,BOTTM


http://www.sql-server-helper.com/tips/comma-delimited-output.aspxhttp://www.sql-server-helper.com/tips/comma-delimited-output.aspx