Technical Article

Get concatenated value for a column without cursor

,

This is a sample script. Copy and paste this query in SQL 2005. First it creates and inserts sample data in Test Table. Then it concatenates the value of col2 for each different value in col1. It is using CTE and recursion to get comma separated values. It avoids the use of cursor.

---------------------------------------------------------------------
-- Create Table and Insert data
---------------------------------------------------------------------
Create Table TestTable (RowID Int Identity(1, 1), Col1 int, Col2 char(3))

Insert TestTable Values (1, 'ABC') 
Insert TestTable Values (1, 'DEF') 
Insert TestTable Values (1, 'GHI') 
Insert TestTable Values (2, 'JKL') 
Insert TestTable Values (2, 'MNO') 
Insert TestTable Values (3, 'PQR') 
Insert TestTable Values (3, 'STU') 

select * from TestTable
---------------------------------------------------------------------
-- Add TestTable column and Insert Row Number
---------------------------------------------------------------------
Alter Table TestTable Add ColRowNo int

Update TestTable 
Set ColRowNo = RowNo
From 
(
    Select RowID, Row_Number() Over (Partition By Col1 Order by RowID) RowNo From TestTable
) B Where TestTable.RowID = B.RowID
;
---------------------------------------------------------------------
-- Concatenate Col2 in comma seperated form Group by Col1 
---------------------------------------------------------------------
With CTE (X, Y, Z) AS
(
    Select Col1, Convert(Varchar,Col2), ColRowNo From TestTable Where ColRowNo = 1
    Union All
    Select Col1, Convert(Varchar, Y + ',' + Convert(Varchar, Col2)) Y, ColRowNo 
    From TestTable 
    Inner Join CTE on Col1 = X and ColRowNo = Z + 1
)

Select X Col1, Y [Concatenated Col2] From CTE
Inner Join 
(
    Select Col1, Max(ColRowNo) ColRowNo From TestTable Group by Col1
) TestTable on X = Col1 and Z = ColRowNo 
Order by X
OPTION (MAXRECURSION 2);

Drop Table TestTable 
GO

Rate

4 (3)

You rated this post out of 5. Change rating

Share

Share

Rate

4 (3)

You rated this post out of 5. Change rating