CREATE TABLE #SameRowsTogether ( Cdescription Char(1), Comment Varchar(100) ) INSERT INTO #SameRowsTogether VALUES('A','1Atext..........') INSERT INTO #SameRowsTogether VALUES('A','2Atext..........') INSERT INTO #SameRowsTogether VALUES('A','3Atext..........') INSERT INTO #SameRowsTogether VALUES('B','1Btext..........') INSERT INTO #SameRowsTogether VALUES('B','2Btext..........') INSERT INTO #SameRowsTogether VALUES('B','3Btext..........') INSERT INTO #SameRowsTogether VALUES('C','1Ctext..........') INSERT INTO #SameRowsTogether VALUES('C','2Ctext..........') INSERT INTO #SameRowsTogether VALUES('C','3Ctext..........') INSERT INTO #SameRowsTogether VALUES('C','4Ctext..........') ---below solution im trying with or the same out put with optimised query CREATE NONCLUSTERED INDEX IDX_COMMENT ON #SameRowsTogether(COMMENT) SELECT Cdescription , COMMENT = SUBSTRING(( SELECT ', ' + COMMENT as [text()] FROM #SameRowsTogether t2 WHERE t2.Cdescription = t1.Cdescription FOR XML path(''), elements), 2, 8000 ) FROM #SameRowsTogether t1
required below output this is only for few row i can fetch faster.
but i have lakhs of real data,taking 4 to 5 minutes to fetch records this way.