Return comma separated value with For XML Path in SQL Server 2008/2005

We many time needs to return value of one column as a comma separated value, we can use COALESCE or ISNULL for this task but it is a lengthy process. I also have written one article for same task with COALESCE function, have a look:
Today I am going to show you one of the easy methods to do same task. Let us create one dummy table and move ahead.
use Adventureworks
CREATE TABLE [dbo].[emps](
[Name] [varchar](50),
[Dept] [varchar](10),
[Company] [varchar](15)
) ON [PRIMARY]
GO
–insert records
INSERT INTO emps
SELECT ‘RITESH’,‘MIS’,‘ECHEM’ UNION ALL
SELECT ‘Rajan’,‘MIS’,‘mar’
Now this is a time to show you how to get all names with separated by comma.
select left(t.name,len(t.name)-1) as ‘allName’ from
(
select name + ‘,’  from emps for xml path()
) as t(name)
Isn’t is easy to use method rather than ISNULL and COALESCE? Yes, it is!!!
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com
Advertisements

4 Responses to “Return comma separated value with For XML Path in SQL Server 2008/2005”

  1. Anonymous Says:

    Stupid looking Picture

  2. Anonymous Says:

    Stupid looking Picture

  3. Ritesh Shah Says:

    thank you very much for comment and keep comming to my blog, actually I was eagerly waiting for your comment as you didn't give any since long!!!

  4. Ritesh Shah Says:

    thank you very much for comment and keep comming to my blog, actually I was eagerly waiting for your comment as you didn't give any since long!!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: