STUFF AND FOR XML PATH for String Concatenation in SqlServer

 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.
 

STUFF:

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.

Syntax:
STUFF(string1, start, length, add_string)
Parameter Description
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 !

相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院