MS SQL tutorial on FOR XML and concatenation and STUFF function

https://www.youtube.com/watch?v=OBNIoyqnRLg 

Sample Query:

select de.Name, stuff(( select ',', em.NationalIDNumber as [text()] from HumanResources.Employee em inner join HumanResources.EmployeeDepartmentHistory eh on em.BusinessEntityID = eh.BusinessEntityID and eh.EndDate is null where eh.DepartmentID = de.DepartmentID for xml path('') ), 1, 1, '') from HumanResources.Department de order by de.Name

NOTES:

as [text()] removes the XML tags in the single column. This just returns a comma-separated list in the single column.

STUFF removes the leading ','. see 1,1,''



Comments

Popular posts from this blog

Using sp_executesql with OPENQUERY

Executing Remote Queries Safely and Efficiently with sp_executesql