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
?
Well, this is an ugly hack, I have to go and wash my hands now, but it works (in a way :-D)
The result
The parameter is a
FOR XML
sub-select within paranthesis. This will implicitly pass the sub-selects result as an XML into the function.To be honest: I would not use this myself...
A query like this
produces the same result and is almost the same amount of typing - but should be faster then calling a slow UDF...
Ok.. so with the first comment of @MichałTurczyn I run into this Microsoft article about CLR User-Defined Aggregate - Invoking Functions
Once I compile the code into SrAggFunc.dll, I was trying to register the aggregate in SQL Server as follows:
But I got the following error.
So I used this excellant part of @SanderRijken code and then change the command to
and then,
Now it's done.
You can see it under your Database -> Programmability on SSMS
and used like :
Thanks all =)