Hi,
We have a requirement like to retrieve a concatenated string of values as a column. For this whether i should use UDF with SQL query or STUFF.
Please suggest.
Here is my Example
------------------
--Create function
CREATE FUNCTION dbo.GroupsList(@AgentID NVARCHAR(32))
RETURNS NVARCHAR(MAX)
AS
-- Returns the grouplist
BEGIN
DECLARE @listStr VARCHAR(MAX);
SELECT @listStr = COALESCE(@listStr+',' ,'') + g.GroupName
FROM
AgentIDGroup ag
INNER JOIN Groups g
ON ag.idindex = g.IDOrPhoneNoIndex
WHERE
ag.AgentID = @AgentID;
IF(@listStr IS NULL)
SET @listStr = '';
RETURN @listStr;
END;
GO
--Call UDF to get resultset
SELECT
a.*
,dbo.GroupsList(a.PhoneUserID) as GroupsList
FROM
Agents a
--CTE with STUFF function and XML PATH clause
WITH CTE AS (
SELECT AgentID,
STUFF((SELECT ', ' + rtrim(convert(nvarchar(32),G.GroupName))
FROM AgentIDGroup AG1 JOIN Groups G on G.IDOrPhoneNoIndex = AG1.idindex WHERE AG.AgentID = AG1.AgentID AND G.GroupFlag = 0
FOR XML PATH('')),1,1,'')
GroupsList FROM AgentIDGroup AG GROUP BY AgentID )
SELECT A.*, ISNULL(CTE.GroupsList,'') as GroupsList
FROM Agents A LEFT JOIN CTE on A.PhoneUserID = CTE.AgentID
--In both case the output will be like this
------------------------------------------------------------------------------------------------------------
PhoneUserID | FirstName | LastName | MiddleName | GroupsList
------------------------------------------------------------------------------------------------------------
6001 Jill Steeves J test
group,Delegates
Thanks,
Bijay