I try to create a generic function that can be used like this example of using the new string_agg built-in function on SQL Server 2017
the inside implementation can be something like the follow
with tbl as(
select a.Id, c.Desc
from TableA a
join TableB b on b.aId = a.Id
join TableC c on c.Code = b.bCode
)
select distinct ID
, STUFF(( select ', ' + Desc from tbl t where t.ID = tbl.ID
for xml path(''),TYPE).value('.','VARCHAR(MAX)'),1,2,'') Desc
from tbl
But how to receives the field key, the field to be connected, the separator char, and the scoped select context?
Is it related to Inline
or Multi-Statement Table-Valued Functions
?
for xml
clause. – ValoniahSTRING_AGG
was added to the language. A custom CLR aggregate can do it, but there's no need for you to reinvent the wheel in that case; plenty of examples of that on the web. – MongrelizeGROUP BY
and introducing a subquery, neither of whichSTRING_AGG
requires. As far as the spirit goes, though, I'll readily acknowledge your answer comes as close as you can get. – MongrelizeHTML
table out of anySELECT
you pass into. For the given case it was better to use theSTUFF-FOR XML
-hack directly within the statement, rather than call an UDF... – Guerrilla