February 1, 2016 at 3:27 pm
Hi!
I'll start with the code:
CREATE TABLE #MyTable
(
MyPk INT,
MyValue VARCHAR(50)
)
INSERT INTO #MyTable VALUES (1,'Value1')
INSERT INTO #MyTable VALUES (2,'Value2')
INSERT INTO #MyTable VALUES (3,'Value3')
SELECT * FROM #MyTable
--Here is what I want to see:
SELECT 'Value1,Value2,Value3'
DROP TABLE #MyTable
I'm trying to identify the best way to retrieve the values from the MyValue column as a single, comma-delimited value. How can this be done through SQL Server?
I greatly appreciate any help!
February 1, 2016 at 5:46 pm
You may want to use a Table variable.
See M.Ali's post >> http://stackoverflow.com/questions/21760969/multiple-rows-to-one-comma-separated-value
See if it helps.
-Regards,
February 1, 2016 at 6:44 pm
The FOR XML approach is a good one for creating a delimited list. Wayne Sheffield has an article that explains it at http://www.sqlservercentral.com/articles/comma+separated+list/71700/.
If you're looking at converting it into columns instead, it's called a pivot of the data, converting rows into columns. SQL Server has one, but it's slow. A crosstab query may is significantly faster and may be exactly what you're looking for. Jeff Moden has an excellent article on them at http://www.sqlservercentral.com/articles/T-SQL/63681/.
February 1, 2016 at 10:17 pm
tarr94 (2/1/2016)
I'm trying to identify the best way to retrieve the values from the MyValue column as a single, comma-delimited value. How can this be done through SQL Server?
It can be done many different ways. Here is a rundown of the most used methods to concatenate grouped strings, complete with performance statistics:
Grouped Concatenation in SQL Server
There are no special teachers of virtue, because virtue is taught by the whole community.
--Plato
February 2, 2016 at 7:14 am
Thank you for the responses. I will give these a try!
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply