25 November 2009

Comma Separated Values (CSV) from Table Column

vedi anche qui.

USE AdventureWorks
GO

-- Check Table Column
SELECT Name
FROM HumanResources.Shift
GO

-- Get CSV values
SELECT SUBSTRING(
(SELECT ',' + s.Name
FROM HumanResources.Shift s
ORDER BY s.Name
FOR XML PATH('')),2,200000) AS CSV
GO
Risultati:
Name                                               
--------------------------------------------------
Day
Evening
Night

CSV
--------------------------------------------------
Day,Evening,Night

Altro metodo:

DECLARE @a AS VARCHAR(4000)
SET @a = ''
SELECT @a = @a + Nome + ','
FROM Argomenti_tb

SELECT @a
Risultati:
---------------------------------------------------------------------------------
Notizie,Primo Piano,Galleria Fotografica,Argomento pubblico 1,Aromento Privato 1,

Altro metodo: COALESCE

DECLARE @fruitNames VARCHAR(8000)
SELECT @fruitNames = COALESCE(@fruitNames + ', ', '') + FruitName FROM Fruits
SELECT FruitNames = @fruitNames
Risultati:
FruitNames
‐‐‐‐‐‐‐‐‐‐
Apple, Orange, Mango, Banana, Grape

The COALESCE function is used to ensure that there is no comma (,) after the last FruitName.

trovati qui.