robjlong
6/16/2015 - 8:48 PM

Creates a CSV List of values from a SQL query

Creates a CSV List of values from a SQL query

--------------- SQL Code Snippet ---------------
------------------------------------------------
-- Purpose			:	This is used to return a Comma Separated List of Values
-- Details			:	Remove the SampleCTE
--------------------------------------------------------------------------------
-- Change History
--------------------------------------------------------------------------------
-- Version  Date       	Author				Description
-- -------  ---------- 	-----------			------------------------------------
--  1.0		6/16/2015	Rob Long			Initial Creation
--------------------------------------------------------------------------------
--
-- Instructions
--	1.	Change the SELECT statement to return the one column that needs to be
--		converted into CSV format. ** This should NOT be aliased.  The alias will
--		return un-wanted results.
--	2.	DELETE the SampleCTE
--------------------------------------------------------------------------------
WITH    SampleCTE
          AS ( SELECT   'Madison' CityName
               UNION
               SELECT   'Oshkosh' CityName
               UNION
               SELECT   'Green Bay' CityName
               UNION
               SELECT   'Marion' CityName
             )
    SELECT  STUFF(( SELECT  ', ' + s.CityName
                    FROM    SampleCTE s
                  FOR
                    XML PATH('')
                  ), 1, 2, '') AS CSV_Result;