Hi @MrFlinstone ,
For versions before 2016, need to create a custom function to merge and separate strings.Please refer to the following method:
CREATE FUNCTION SplitStr(@Sourcestr VARCHAR(8000), @Seprate VARCHAR(100))
RETURNS @result TABLE(F1 VARCHAR(100))
AS
BEGIN
DECLARE @sql AS VARCHAR(100)
SET @Sourcestr=@Sourcestr+@Seprate
WHILE(@Sourcestr<>'')
BEGIN
SET @sql=left(@Sourcestr,CHARINDEX(',',@Sourcestr,1)-1)
INSERT @result VALUES(@sql)
SET @Sourcestr=STUFF(@Sourcestr,1,CHARINDEX(',',@Sourcestr,1),'')
END
RETURN
END
GO
;WITH cte
as(SELECT jobid,employee_id,F1 as resource_id
FROM #jobs s
CROSS APPLY SplitStr(S.resource_id,',') V)
,cte2 as
(SELECT c.*,e.employee_name FROM cte c
join #employees e
ON c.employee_id=e.employee_id)
,cte3 as
(SELECT c2.*,e.employee_name as help FROM cte2 c2
left join #employees e
ON c2.resource_id=e.employee_id)
SELECT jobid,employee_name
, STUFF((SELECT ',' + CAST(help AS VARCHAR(30)) AS [text()]
FROM cte3 AS O
WHERE O.jobid = C.jobid
FOR XML PATH('')), 1, 1, NULL) as help
FROM cte3 as c
GROUP BY jobid,employee_name
ORDER BY jobid
Output:
jobid employee_name help
1234 Tom NULL
1235 Emily NULL
1236 William Tom
1237 Tom Emily,George
1238 George William
If you have any question, please feel free to let me know.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.