Convert row values in a Table to Single Concatenated String in SQL Server 2012
In this article I am going to explain about how to convert row values in a table to single concatenated string.
Introduction
In this article I am going to explain about how to convert row values in a table to single concatenated string.
Create Table
CREATE TABLE ConcatenationDemo
(
RowID INT PRIMARY KEY
,Txt VARCHAR(MAX)
)
INSERT INTO ConcatenationDemo
(RowID,Txt)
SELECT 1,'A1'UNION all
SELECT 2,'A2'UNION all
SELECT 3,'A3'UNION all
SELECT 4,'A4'UNION all
SELECT 5,'A5'UNION all
SELECT 6,'A6'UNION all
SELECT 7,'A7'UNION all
SELECT 8,'A8'
Output:
![table-in-sql.jpg](/UploadFile/6982/Images/table-in-sql.jpg)
Type following code to concatenate Txt field of table
DECLARE @Txt1 VARCHAR(MAX)
SET @Txt1=''
SELECT @Txt1 = @Txt1 + Txt +','
FROM ConcatenationDemo
SELECT LEFT(@Txt1,LEN(@Txt1)-1) AS Txt
Output:
![concatenated string.jpg](/UploadFile/6982/Images/concatenated%20string.jpg)