开发者

Comma Seprate Field Name in Sql Server 2008

开发者 https://www.devze.com 2023-03-04 18:30 出处:网络
I have a table Name \"EmpMast\" i want开发者_运维技巧 to add all emp_name with comma separate like

I have a table Name "EmpMast" i want开发者_运维技巧 to add all emp_name with comma separate like "Mahesh,Vipul,Ritesh" How could i do that???


I assume you're importing a CSV file. There's a good example here

BULK INSERT [orders]
FROM 'c:\orders.csv'
WITH (FIELDTERMINATOR = ',')


This can be achieved using SQL Server's built-in XML capabilities:

SELECT
   STUFF
   (
       (
           SELECT ',' + emp_name
           FROM EmpMast
           ORDER BY emp_name
           FOR XML PATH('')
       ), 1, 1, ''
   ) AS employee_names

The STUFF statement here simply removes the first comma from the list.

More on FOR XML here: http://msdn.microsoft.com/en-us/library/ms345137(v=sql.90).aspx More on STUFF here: http://msdn.microsoft.com/en-us/library/ms188043.aspx

I've done a full write-up on this technique here: http://davidduffett.net/post/5334646215/get-a-column-separated-list-of-values-with-for-xml

0

精彩评论

暂无评论...
验证码 换一张
取 消