Today ,we should concatenate column data into single row.
To make you understand better,we learn about “STUFF AND FOR XML PATH for String Concatenation in SqlServer”with demo.
Let’s learn “SQL Server STUFF() Function” first.
|Example one——Delete 3 characters from a string and then insert another sequence of characters, starting in position 1:|
SELECT STUFF('SQL Tutorial', 1, 3, 'HTML');
when we run the Query. We will get “HTML Tutorial” like the image.
After learning the demo,we can learn about the Definition and Usage
The STUFF() function deletes a sequence of characters from a string and then inserts another sequence of characters into the string, starting at a specified position.
STUFF(string1, start, length, add_string)
|string1||Required. The source string to modify|
|start||Required. The position in string1 to start delete length characters, and then insert add_string|
|length||Required. The number of characters to delete from string1|
|add_string||Required. The sequence of characters to insert into string1 at the start position|
|STUFF AND FOR XML PATH for String Concatenation:|
OK，after learning about Stuff function(),we can learn ‘STUFF AND FOR XML PATH for String Concatenation in SqlServer’
In the work，we should concatenate all the name data in a department into single row. Like the Image:
select distinct 部门 , STUFF((Select ','+姓名 from Employees T1 where T1.部门=T2.部门 FOR XML PATH('')),1,1,'') as 同一个部门的人员名单 from Employees T2
We can use XmlPath(”) to concatenate column data into single row. Stuff is used to remove the first ‘,’ after string concatenation.
If you have discovered something I should add, let me know.thanks you very much !