I want to run a stored procedure that returns a whole bunch of stuff, one of which is a comma separated string of results.
I have read about the COALESCE and created a function that does it like this:
DECLARE @ListOfStuff NVARCHAR(4000)
SELECT @ListOfStuff = COALESCE(@ListOfStuff + ', ', '') + Z.SingleStuff
FROM X
INNER JOIN Y ON X.SomeId = Y.Id
INNER JOIN Z ON Y.SomeId = Z.id
WHERE --Some condition
RETURN ISNULL(@ListOfStuff, '')
And then in my main SELECT I call this function and it works as expected. However, the procedure now takes a really long time to run and it often times out. What I'm wondering is, whether someone has an idea how to optimise it. I believe getting rid of the function and incorporating this logic within the procedure will make it run a lot faster but I couldn't figure out a way to have a sub select that uses COALESCE this way.
Any ideas how to optimise this logic? Many thanks in advance