Concatenate Values in Single Cell in SQL

DECLARE @t TABLE (EmpId INT, EmpName VARCHAR(100)) — Here @t is a static table with Columns EmpId & EmpName
INSERT @t VALUES
(1, ‘Bhavik’),(1, ‘Mayank’),(1, ‘Keyur’),(2, ‘Sudarshan’),(2, ‘Sohan’) –Values are inserted in the Table.
SELECT distinct
EmpId,
(
SELECT EmpName+’,’
FROM @t t2
WHERE t2.EmpId = t1.EmpId
FOR XML PATH(”)
) Concatenated –Names with Same ID are Concatenated and Displayed in Single Cell.
FROM @t t1

Posts Tagged with…

Write a Comment

Your email address will not be published. Required fields are marked *