将一列数据转换成一个字段数据,逗号分隔

这个场景很常见,在网上查了一下,人家说用xpath 方法,亲测有效。

	select stuff(
	(select ','+cast(u.UserName_Chn as varchar(max)) from BO_ManagementPeo b inner join V_P_UserInfo
	u on u.UserGUID = b.UserGUID where a.ObjectGUID=b.ObjectGUID for xml path(''))
	,1,1,'') as JoinUsers, ObjectGUID
	from BO_ManagementPeo a
	group by ObjectGUID

  

如果只是单个

select a.*,
stuff(
(select ','+cast(FullName as varchar(max)) from  erp.dbo.yx_khinfo where CHARINDEX('首利', FullName) > 0 for xml path(''))
,1,1,'') fullname
from (select '首利' col1) a