Saturday, August 7, 2010

Concatenating Row Values using Transact-SQL

Sometime SQL programmers come across a requirement to concatene a result-set using T-SQL query.
Below is an example of this scenarion:
SELECT Dept_Code,Emp_Name
FROM Employee (NOLOCK)
ORDER BY Dept_Code,Emp_Name

And user wants to see the data in below format:

You can do these using Transact SQL. Below is the T-SQL query to achieve this solution:

Method1: Concatenation that uses the FOR XML clause with PATH mode:
SELECT E1.Dept_Code,
(
   SELECT Emp_Name + ',' FROM Employee E2
   WHERE E2.Dept_Code = E1.Dept_Code
   ORDER BY Emp_Name
   FOR XML PATH('')
) AS Emp_Name
FROM Employee E1
GROUP BY Dept_Code

Method2: There is a similar approach using the CROSS APPLY operator.
SELECT DISTINCT E1.Dept_Code, Temp.Emp_Name
FROM Employee E1 CROSS APPLY
(
   SELECT Emp_Name + ',' FROM Employee E2
   WHERE E2.Dept_Code = E1.Dept_Code
   ORDER BY Emp_Name
   FOR XML PATH('')
) AS Temp (Emp_Name)

2 comments:

  1. Hi Hari,

    This is a very good example and new for me.
    I just want to know ...What is "FOR XML PATH('')" and why and where we can use it.
    Please help me.
    My Email Id is -- saw.ashishkumar@gmail.com

    Regards,
    Ashish Kumar

    ReplyDelete
  2. Ashish,
    use of FOR XML PATH depends on the requirement. Basically the FOR XML PATH allows you to use an XPath-like syntax as a column name which is mapped to an attribute/element/sub-element of the XML as per you specify and you can have multiple level of hierarchy and can mix elements n attributes.

    For more information, read details with suitable examples in MSDN: http://msdn.microsoft.com/en-us/library/ms345137(SQL.90).aspx

    ReplyDelete